/
structured.ts
232 lines (201 loc) Β· 7.31 KB
/
structured.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import { JsonSchema7Type } from "zod-to-json-schema/src/parseDef.js";
import { JsonSchema7ArrayType } from "zod-to-json-schema/src/parsers/array.js";
import { JsonSchema7ObjectType } from "zod-to-json-schema/src/parsers/object.js";
import { JsonSchema7StringType } from "zod-to-json-schema/src/parsers/string.js";
import { JsonSchema7NumberType } from "zod-to-json-schema/src/parsers/number.js";
import { JsonSchema7NullableType } from "zod-to-json-schema/src/parsers/nullable.js";
import {
BaseOutputParser,
FormatInstructionsOptions,
OutputParserException,
} from "../schema/output_parser.js";
export type JsonMarkdownStructuredOutputParserInput = {
interpolationDepth?: number;
};
export interface JsonMarkdownFormatInstructionsOptions
extends FormatInstructionsOptions {
interpolationDepth?: number;
}
export class StructuredOutputParser<
T extends z.ZodTypeAny
> extends BaseOutputParser<z.infer<T>> {
lc_namespace = ["langchain", "output_parsers", "structured"];
toJSON() {
return this.toJSONNotImplemented();
}
constructor(public schema: T) {
super(schema);
}
static fromZodSchema<T extends z.ZodTypeAny>(schema: T) {
return new this(schema);
}
static fromNamesAndDescriptions<S extends { [key: string]: string }>(
schemas: S
) {
const zodSchema = z.object(
Object.fromEntries(
Object.entries(schemas).map(
([name, description]) =>
[name, z.string().describe(description)] as const
)
)
);
return new this(zodSchema);
}
getFormatInstructions(): string {
return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(zodToJsonSchema(this.schema))}
\`\`\`
`;
}
async parse(text: string): Promise<z.infer<T>> {
try {
const json = text.includes("```")
? text.trim().split(/```(?:json)?/)[1]
: text.trim();
return this.schema.parseAsync(JSON.parse(json));
} catch (e) {
throw new OutputParserException(
`Failed to parse. Text: "${text}". Error: ${e}`,
text
);
}
}
}
export class JsonMarkdownStructuredOutputParser<
T extends z.ZodTypeAny
> extends StructuredOutputParser<T> {
getFormatInstructions(
options?: JsonMarkdownFormatInstructionsOptions
): string {
const interpolationDepth = options?.interpolationDepth ?? 1;
if (interpolationDepth < 1) {
throw new Error("f string interpolation depth must be at least 1");
}
return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(
zodToJsonSchema(this.schema)
)
.replaceAll("{", "{".repeat(interpolationDepth))
.replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``;
}
private _schemaToInstruction(
schemaInput: JsonSchema7Type,
indent = 2
): string {
const schema = schemaInput as Extract<
JsonSchema7Type,
| JsonSchema7ObjectType
| JsonSchema7ArrayType
| JsonSchema7StringType
| JsonSchema7NumberType
| JsonSchema7NullableType
>;
if ("type" in schema) {
let nullable = false;
let type: string;
if (Array.isArray(schema.type)) {
const nullIdx = schema.type.findIndex((type) => type === "null");
if (nullIdx !== -1) {
nullable = true;
schema.type.splice(nullIdx, 1);
}
type = schema.type.join(" | ") as string;
} else {
type = schema.type;
}
if (schema.type === "object" && schema.properties) {
const description = schema.description
? ` // ${schema.description}`
: "";
const properties = Object.entries(schema.properties)
.map(([key, value]) => {
const isOptional = schema.required?.includes(key)
? ""
: " (optional)";
return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(
value,
indent + 2
)}${isOptional}`;
})
.join("\n");
return `{\n${properties}\n${" ".repeat(indent - 2)}}${description}`;
}
if (schema.type === "array" && schema.items) {
const description = schema.description
? ` // ${schema.description}`
: "";
return `array[\n${" ".repeat(indent)}${this._schemaToInstruction(
schema.items,
indent + 2
)}\n${" ".repeat(indent - 2)}] ${description}`;
}
const isNullable = nullable ? " (nullable)" : "";
const description = schema.description ? ` // ${schema.description}` : "";
return `${type}${description}${isNullable}`;
}
if ("anyOf" in schema) {
return schema.anyOf
.map((s) => this._schemaToInstruction(s, indent))
.join(`\n${" ".repeat(indent - 2)}`);
}
throw new Error("unsupported schema type");
}
static fromZodSchema<T extends z.ZodTypeAny>(schema: T) {
return new this<T>(schema);
}
static fromNamesAndDescriptions<S extends { [key: string]: string }>(
schemas: S
) {
const zodSchema = z.object(
Object.fromEntries(
Object.entries(schemas).map(
([name, description]) =>
[name, z.string().describe(description)] as const
)
)
);
return new this<typeof zodSchema>(zodSchema);
}
}
export interface AsymmetricStructuredOutputParserFields<
T extends z.ZodTypeAny
> {
inputSchema: T;
}
export abstract class AsymmetricStructuredOutputParser<
T extends z.ZodTypeAny,
Y = unknown
> extends BaseOutputParser<Y> {
private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;
constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {
super(...arguments);
this.structuredInputParser = new JsonMarkdownStructuredOutputParser(
inputSchema
);
}
abstract outputProcessor(input: z.infer<T>): Promise<Y>;
async parse(text: string): Promise<Y> {
let parsedInput;
try {
parsedInput = await this.structuredInputParser.parse(text);
} catch (e) {
throw new OutputParserException(
`Failed to parse. Text: "${text}". Error: ${e}`,
text
);
}
return this.outputProcessor(parsedInput);
}
getFormatInstructions(): string {
return this.structuredInputParser.getFormatInstructions();
}
}