@langchain/core 0.1.42 → 0.1.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/language_models/base.d.ts +12 -12
- package/dist/output_parsers/index.cjs +1 -0
- package/dist/output_parsers/index.d.ts +1 -0
- package/dist/output_parsers/index.js +1 -0
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +22 -2
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts +6 -2
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +23 -3
- package/dist/output_parsers/structured.cjs +190 -0
- package/dist/output_parsers/structured.d.ts +88 -0
- package/dist/output_parsers/structured.js +184 -0
- package/dist/utils/testing/index.cjs +1 -1
- package/dist/utils/testing/index.d.ts +3 -3
- package/dist/utils/testing/index.js +1 -1
- package/package.json +1 -1
|
@@ -107,7 +107,14 @@ export interface BaseFunctionCallOptions extends BaseLanguageModelCallOptions {
|
|
|
107
107
|
}
|
|
108
108
|
export type BaseLanguageModelInput = BasePromptValueInterface | string | BaseMessageLike[];
|
|
109
109
|
export type StructuredOutputType = z.infer<z.ZodObject<any, any, any, any>>;
|
|
110
|
-
export type
|
|
110
|
+
export type StructuredOutputMethodOptions<IncludeRaw extends boolean = false> = {
|
|
111
|
+
name?: string;
|
|
112
|
+
method?: "functionCalling" | "jsonMode";
|
|
113
|
+
includeRaw?: IncludeRaw;
|
|
114
|
+
};
|
|
115
|
+
/** @deprecated Use StructuredOutputMethodOptions instead */
|
|
116
|
+
export type StructuredOutputMethodParams<RunOutput, IncludeRaw extends boolean = false> = {
|
|
117
|
+
/** @deprecated Pass schema in as the first argument */
|
|
111
118
|
schema: z.ZodType<RunOutput> | Record<string, any>;
|
|
112
119
|
name?: string;
|
|
113
120
|
method?: "functionCalling" | "jsonMode";
|
|
@@ -184,8 +191,8 @@ export declare abstract class BaseLanguageModel<RunOutput = any, CallOptions ext
|
|
|
184
191
|
* Load an LLM from a json-like object describing it.
|
|
185
192
|
*/
|
|
186
193
|
static deserialize(_data: SerializedLLM): Promise<BaseLanguageModel>;
|
|
187
|
-
withStructuredOutput?<RunOutput extends Record<string, any> = Record<string, any>>(
|
|
188
|
-
withStructuredOutput?<RunOutput extends Record<string, any> = Record<string, any>>(
|
|
194
|
+
withStructuredOutput?<RunOutput extends Record<string, any> = Record<string, any>>(schema: z.ZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
195
|
+
withStructuredOutput?<RunOutput extends Record<string, any> = Record<string, any>>(schema: z.ZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
189
196
|
raw: BaseMessage;
|
|
190
197
|
parsed: RunOutput;
|
|
191
198
|
}>;
|
|
@@ -196,20 +203,13 @@ export declare abstract class BaseLanguageModel<RunOutput = any, CallOptions ext
|
|
|
196
203
|
* @template {Record<string, any>} RunOutput The output type for the Runnable, expected to be a Zod schema object for structured output validation.
|
|
197
204
|
*
|
|
198
205
|
* @param {z.ZodEffects<RunOutput>} schema The schema for the structured output. Either as a Zod schema or a valid JSON schema object.
|
|
206
|
+
* If a Zod schema is passed, the returned attributes will be validated, whereas with JSON schema they will not be.
|
|
199
207
|
* @param {string} name The name of the function to call.
|
|
200
208
|
* @param {"functionCalling" | "jsonMode"} [method=functionCalling] The method to use for getting the structured output. Defaults to "functionCalling".
|
|
201
209
|
* @param {boolean | undefined} [includeRaw=false] Whether to include the raw output in the result. Defaults to false.
|
|
202
210
|
* @returns {Runnable<RunInput, RunOutput> | Runnable<RunInput, { raw: BaseMessage; parsed: RunOutput }>} A new runnable that calls the LLM with structured output.
|
|
203
211
|
*/
|
|
204
|
-
withStructuredOutput?<RunOutput extends Record<string, any> = Record<string, any>>(
|
|
205
|
-
/**
|
|
206
|
-
* @default functionCalling
|
|
207
|
-
*/
|
|
208
|
-
method,
|
|
209
|
-
/**
|
|
210
|
-
* @default false
|
|
211
|
-
*/
|
|
212
|
-
includeRaw, }: StructuredOutputMethodParams<RunOutput>): Runnable<BaseLanguageModelInput, RunOutput> | Runnable<BaseLanguageModelInput, {
|
|
212
|
+
withStructuredOutput?<RunOutput extends Record<string, any> = Record<string, any>>(schema: z.ZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<boolean>): Runnable<BaseLanguageModelInput, RunOutput> | Runnable<BaseLanguageModelInput, {
|
|
213
213
|
raw: BaseMessage;
|
|
214
214
|
parsed: RunOutput;
|
|
215
215
|
}>;
|
|
@@ -18,6 +18,7 @@ __exportStar(require("./base.cjs"), exports);
|
|
|
18
18
|
__exportStar(require("./bytes.cjs"), exports);
|
|
19
19
|
__exportStar(require("./list.cjs"), exports);
|
|
20
20
|
__exportStar(require("./string.cjs"), exports);
|
|
21
|
+
__exportStar(require("./structured.cjs"), exports);
|
|
21
22
|
__exportStar(require("./transform.cjs"), exports);
|
|
22
23
|
__exportStar(require("./json.cjs"), exports);
|
|
23
24
|
__exportStar(require("./xml.cjs"), exports);
|
|
@@ -121,9 +121,28 @@ class JsonOutputKeyToolsParser extends base_js_1.BaseLLMOutputParser {
|
|
|
121
121
|
writable: true,
|
|
122
122
|
value: void 0
|
|
123
123
|
});
|
|
124
|
+
Object.defineProperty(this, "zodSchema", {
|
|
125
|
+
enumerable: true,
|
|
126
|
+
configurable: true,
|
|
127
|
+
writable: true,
|
|
128
|
+
value: void 0
|
|
129
|
+
});
|
|
124
130
|
this.keyName = params.keyName;
|
|
125
131
|
this.returnSingle = params.returnSingle ?? this.returnSingle;
|
|
126
132
|
this.initialParser = new JsonOutputToolsParser(params);
|
|
133
|
+
this.zodSchema = params.zodSchema;
|
|
134
|
+
}
|
|
135
|
+
async _validateResult(result) {
|
|
136
|
+
if (this.zodSchema === undefined) {
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
const zodParsedResult = await this.zodSchema.safeParseAsync(result);
|
|
140
|
+
if (zodParsedResult.success) {
|
|
141
|
+
return zodParsedResult.data;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
throw new base_js_1.OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.errors)}`, JSON.stringify(result, null, 2));
|
|
145
|
+
}
|
|
127
146
|
}
|
|
128
147
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
129
148
|
async parseResult(generations) {
|
|
@@ -135,9 +154,10 @@ class JsonOutputKeyToolsParser extends base_js_1.BaseLLMOutputParser {
|
|
|
135
154
|
returnedValues = matchingResults.map((result) => result.args);
|
|
136
155
|
}
|
|
137
156
|
if (this.returnSingle) {
|
|
138
|
-
return returnedValues[0];
|
|
157
|
+
return this._validateResult(returnedValues[0]);
|
|
139
158
|
}
|
|
140
|
-
|
|
159
|
+
const toolCallResults = await Promise.all(returnedValues.map((value) => this._validateResult(value)));
|
|
160
|
+
return toolCallResults;
|
|
141
161
|
}
|
|
142
162
|
}
|
|
143
163
|
exports.JsonOutputKeyToolsParser = JsonOutputKeyToolsParser;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
1
2
|
import { ChatGeneration } from "../../outputs.js";
|
|
2
3
|
import { BaseLLMOutputParser } from "../base.js";
|
|
3
4
|
export type ParsedToolCall = {
|
|
@@ -30,11 +31,12 @@ export declare class JsonOutputToolsParser extends BaseLLMOutputParser<ParsedToo
|
|
|
30
31
|
*/
|
|
31
32
|
parseResult(generations: ChatGeneration[]): Promise<ParsedToolCall[]>;
|
|
32
33
|
}
|
|
33
|
-
export type JsonOutputKeyToolsParserParams = {
|
|
34
|
+
export type JsonOutputKeyToolsParserParams<T extends Record<string, any> = Record<string, any>> = {
|
|
34
35
|
keyName: string;
|
|
35
36
|
returnSingle?: boolean;
|
|
36
37
|
/** Whether to return the tool call id. */
|
|
37
38
|
returnId?: boolean;
|
|
39
|
+
zodSchema?: z.ZodType<T>;
|
|
38
40
|
};
|
|
39
41
|
/**
|
|
40
42
|
* Class for parsing the output of a tool-calling LLM into a JSON object if you are
|
|
@@ -50,6 +52,8 @@ export declare class JsonOutputKeyToolsParser<T extends Record<string, any> = Re
|
|
|
50
52
|
/** Whether to return only the first tool call. */
|
|
51
53
|
returnSingle: boolean;
|
|
52
54
|
initialParser: JsonOutputToolsParser;
|
|
53
|
-
|
|
55
|
+
zodSchema?: z.ZodType<T>;
|
|
56
|
+
constructor(params: JsonOutputKeyToolsParserParams<T>);
|
|
57
|
+
protected _validateResult(result: unknown): Promise<T>;
|
|
54
58
|
parseResult(generations: ChatGeneration[]): Promise<any>;
|
|
55
59
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BaseLLMOutputParser } from "../base.js";
|
|
1
|
+
import { BaseLLMOutputParser, OutputParserException } from "../base.js";
|
|
2
2
|
/**
|
|
3
3
|
* Class for parsing the output of a tool-calling LLM into a JSON object.
|
|
4
4
|
*/
|
|
@@ -117,9 +117,28 @@ export class JsonOutputKeyToolsParser extends BaseLLMOutputParser {
|
|
|
117
117
|
writable: true,
|
|
118
118
|
value: void 0
|
|
119
119
|
});
|
|
120
|
+
Object.defineProperty(this, "zodSchema", {
|
|
121
|
+
enumerable: true,
|
|
122
|
+
configurable: true,
|
|
123
|
+
writable: true,
|
|
124
|
+
value: void 0
|
|
125
|
+
});
|
|
120
126
|
this.keyName = params.keyName;
|
|
121
127
|
this.returnSingle = params.returnSingle ?? this.returnSingle;
|
|
122
128
|
this.initialParser = new JsonOutputToolsParser(params);
|
|
129
|
+
this.zodSchema = params.zodSchema;
|
|
130
|
+
}
|
|
131
|
+
async _validateResult(result) {
|
|
132
|
+
if (this.zodSchema === undefined) {
|
|
133
|
+
return result;
|
|
134
|
+
}
|
|
135
|
+
const zodParsedResult = await this.zodSchema.safeParseAsync(result);
|
|
136
|
+
if (zodParsedResult.success) {
|
|
137
|
+
return zodParsedResult.data;
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.errors)}`, JSON.stringify(result, null, 2));
|
|
141
|
+
}
|
|
123
142
|
}
|
|
124
143
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
125
144
|
async parseResult(generations) {
|
|
@@ -131,8 +150,9 @@ export class JsonOutputKeyToolsParser extends BaseLLMOutputParser {
|
|
|
131
150
|
returnedValues = matchingResults.map((result) => result.args);
|
|
132
151
|
}
|
|
133
152
|
if (this.returnSingle) {
|
|
134
|
-
return returnedValues[0];
|
|
153
|
+
return this._validateResult(returnedValues[0]);
|
|
135
154
|
}
|
|
136
|
-
|
|
155
|
+
const toolCallResults = await Promise.all(returnedValues.map((value) => this._validateResult(value)));
|
|
156
|
+
return toolCallResults;
|
|
137
157
|
}
|
|
138
158
|
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AsymmetricStructuredOutputParser = exports.JsonMarkdownStructuredOutputParser = exports.StructuredOutputParser = void 0;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
const zod_to_json_schema_1 = require("zod-to-json-schema");
|
|
6
|
+
const base_js_1 = require("./base.cjs");
|
|
7
|
+
class StructuredOutputParser extends base_js_1.BaseOutputParser {
|
|
8
|
+
static lc_name() {
|
|
9
|
+
return "StructuredOutputParser";
|
|
10
|
+
}
|
|
11
|
+
toJSON() {
|
|
12
|
+
return this.toJSONNotImplemented();
|
|
13
|
+
}
|
|
14
|
+
constructor(schema) {
|
|
15
|
+
super(schema);
|
|
16
|
+
Object.defineProperty(this, "schema", {
|
|
17
|
+
enumerable: true,
|
|
18
|
+
configurable: true,
|
|
19
|
+
writable: true,
|
|
20
|
+
value: schema
|
|
21
|
+
});
|
|
22
|
+
Object.defineProperty(this, "lc_namespace", {
|
|
23
|
+
enumerable: true,
|
|
24
|
+
configurable: true,
|
|
25
|
+
writable: true,
|
|
26
|
+
value: ["langchain", "output_parsers", "structured"]
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Creates a new StructuredOutputParser from a Zod schema.
|
|
31
|
+
* @param schema The Zod schema which the output should match
|
|
32
|
+
* @returns A new instance of StructuredOutputParser.
|
|
33
|
+
*/
|
|
34
|
+
static fromZodSchema(schema) {
|
|
35
|
+
return new this(schema);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Creates a new StructuredOutputParser from a set of names and
|
|
39
|
+
* descriptions.
|
|
40
|
+
* @param schemas An object where each key is a name and each value is a description
|
|
41
|
+
* @returns A new instance of StructuredOutputParser.
|
|
42
|
+
*/
|
|
43
|
+
static fromNamesAndDescriptions(schemas) {
|
|
44
|
+
const zodSchema = zod_1.z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, zod_1.z.string().describe(description)])));
|
|
45
|
+
return new this(zodSchema);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Returns a markdown code snippet with a JSON object formatted according
|
|
49
|
+
* to the schema.
|
|
50
|
+
* @param options Optional. The options for formatting the instructions
|
|
51
|
+
* @returns A markdown code snippet with a JSON object formatted according to the schema.
|
|
52
|
+
*/
|
|
53
|
+
getFormatInstructions() {
|
|
54
|
+
return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
55
|
+
|
|
56
|
+
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
57
|
+
|
|
58
|
+
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}
|
|
59
|
+
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.
|
|
60
|
+
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.
|
|
61
|
+
|
|
62
|
+
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!
|
|
63
|
+
|
|
64
|
+
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
65
|
+
\`\`\`json
|
|
66
|
+
${JSON.stringify((0, zod_to_json_schema_1.zodToJsonSchema)(this.schema))}
|
|
67
|
+
\`\`\`
|
|
68
|
+
`;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Parses the given text according to the schema.
|
|
72
|
+
* @param text The text to parse
|
|
73
|
+
* @returns The parsed output.
|
|
74
|
+
*/
|
|
75
|
+
async parse(text) {
|
|
76
|
+
try {
|
|
77
|
+
const json = text.includes("```")
|
|
78
|
+
? text.trim().split(/```(?:json)?/)[1]
|
|
79
|
+
: text.trim();
|
|
80
|
+
return await this.schema.parseAsync(JSON.parse(json));
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
throw new base_js_1.OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
exports.StructuredOutputParser = StructuredOutputParser;
|
|
88
|
+
/**
|
|
89
|
+
* A specific type of `StructuredOutputParser` that parses JSON data
|
|
90
|
+
* formatted as a markdown code snippet.
|
|
91
|
+
*/
|
|
92
|
+
class JsonMarkdownStructuredOutputParser extends StructuredOutputParser {
|
|
93
|
+
static lc_name() {
|
|
94
|
+
return "JsonMarkdownStructuredOutputParser";
|
|
95
|
+
}
|
|
96
|
+
getFormatInstructions(options) {
|
|
97
|
+
const interpolationDepth = options?.interpolationDepth ?? 1;
|
|
98
|
+
if (interpolationDepth < 1) {
|
|
99
|
+
throw new Error("f string interpolation depth must be at least 1");
|
|
100
|
+
}
|
|
101
|
+
return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction((0, zod_to_json_schema_1.zodToJsonSchema)(this.schema))
|
|
102
|
+
.replaceAll("{", "{".repeat(interpolationDepth))
|
|
103
|
+
.replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``;
|
|
104
|
+
}
|
|
105
|
+
_schemaToInstruction(schemaInput, indent = 2) {
|
|
106
|
+
const schema = schemaInput;
|
|
107
|
+
if ("type" in schema) {
|
|
108
|
+
let nullable = false;
|
|
109
|
+
let type;
|
|
110
|
+
if (Array.isArray(schema.type)) {
|
|
111
|
+
const nullIdx = schema.type.findIndex((type) => type === "null");
|
|
112
|
+
if (nullIdx !== -1) {
|
|
113
|
+
nullable = true;
|
|
114
|
+
schema.type.splice(nullIdx, 1);
|
|
115
|
+
}
|
|
116
|
+
type = schema.type.join(" | ");
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
type = schema.type;
|
|
120
|
+
}
|
|
121
|
+
if (schema.type === "object" && schema.properties) {
|
|
122
|
+
const description = schema.description
|
|
123
|
+
? ` // ${schema.description}`
|
|
124
|
+
: "";
|
|
125
|
+
const properties = Object.entries(schema.properties)
|
|
126
|
+
.map(([key, value]) => {
|
|
127
|
+
const isOptional = schema.required?.includes(key)
|
|
128
|
+
? ""
|
|
129
|
+
: " (optional)";
|
|
130
|
+
return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`;
|
|
131
|
+
})
|
|
132
|
+
.join("\n");
|
|
133
|
+
return `{\n${properties}\n${" ".repeat(indent - 2)}}${description}`;
|
|
134
|
+
}
|
|
135
|
+
if (schema.type === "array" && schema.items) {
|
|
136
|
+
const description = schema.description
|
|
137
|
+
? ` // ${schema.description}`
|
|
138
|
+
: "";
|
|
139
|
+
return `array[\n${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)}\n${" ".repeat(indent - 2)}] ${description}`;
|
|
140
|
+
}
|
|
141
|
+
const isNullable = nullable ? " (nullable)" : "";
|
|
142
|
+
const description = schema.description ? ` // ${schema.description}` : "";
|
|
143
|
+
return `${type}${description}${isNullable}`;
|
|
144
|
+
}
|
|
145
|
+
if ("anyOf" in schema) {
|
|
146
|
+
return schema.anyOf
|
|
147
|
+
.map((s) => this._schemaToInstruction(s, indent))
|
|
148
|
+
.join(`\n${" ".repeat(indent - 2)}`);
|
|
149
|
+
}
|
|
150
|
+
throw new Error("unsupported schema type");
|
|
151
|
+
}
|
|
152
|
+
static fromZodSchema(schema) {
|
|
153
|
+
return new this(schema);
|
|
154
|
+
}
|
|
155
|
+
static fromNamesAndDescriptions(schemas) {
|
|
156
|
+
const zodSchema = zod_1.z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, zod_1.z.string().describe(description)])));
|
|
157
|
+
return new this(zodSchema);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
exports.JsonMarkdownStructuredOutputParser = JsonMarkdownStructuredOutputParser;
|
|
161
|
+
/**
|
|
162
|
+
* A type of `StructuredOutputParser` that handles asymmetric input and
|
|
163
|
+
* output schemas.
|
|
164
|
+
*/
|
|
165
|
+
class AsymmetricStructuredOutputParser extends base_js_1.BaseOutputParser {
|
|
166
|
+
constructor({ inputSchema }) {
|
|
167
|
+
super(...arguments);
|
|
168
|
+
Object.defineProperty(this, "structuredInputParser", {
|
|
169
|
+
enumerable: true,
|
|
170
|
+
configurable: true,
|
|
171
|
+
writable: true,
|
|
172
|
+
value: void 0
|
|
173
|
+
});
|
|
174
|
+
this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema);
|
|
175
|
+
}
|
|
176
|
+
async parse(text) {
|
|
177
|
+
let parsedInput;
|
|
178
|
+
try {
|
|
179
|
+
parsedInput = await this.structuredInputParser.parse(text);
|
|
180
|
+
}
|
|
181
|
+
catch (e) {
|
|
182
|
+
throw new base_js_1.OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
|
|
183
|
+
}
|
|
184
|
+
return this.outputProcessor(parsedInput);
|
|
185
|
+
}
|
|
186
|
+
getFormatInstructions() {
|
|
187
|
+
return this.structuredInputParser.getFormatInstructions();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
exports.AsymmetricStructuredOutputParser = AsymmetricStructuredOutputParser;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { BaseOutputParser, FormatInstructionsOptions } from "./base.js";
|
|
3
|
+
export type JsonMarkdownStructuredOutputParserInput = {
|
|
4
|
+
interpolationDepth?: number;
|
|
5
|
+
};
|
|
6
|
+
export interface JsonMarkdownFormatInstructionsOptions extends FormatInstructionsOptions {
|
|
7
|
+
interpolationDepth?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare class StructuredOutputParser<T extends z.ZodTypeAny> extends BaseOutputParser<z.infer<T>> {
|
|
10
|
+
schema: T;
|
|
11
|
+
static lc_name(): string;
|
|
12
|
+
lc_namespace: string[];
|
|
13
|
+
toJSON(): import("../load/serializable.js").SerializedNotImplemented;
|
|
14
|
+
constructor(schema: T);
|
|
15
|
+
/**
|
|
16
|
+
* Creates a new StructuredOutputParser from a Zod schema.
|
|
17
|
+
* @param schema The Zod schema which the output should match
|
|
18
|
+
* @returns A new instance of StructuredOutputParser.
|
|
19
|
+
*/
|
|
20
|
+
static fromZodSchema<T extends z.ZodTypeAny>(schema: T): StructuredOutputParser<T>;
|
|
21
|
+
/**
|
|
22
|
+
* Creates a new StructuredOutputParser from a set of names and
|
|
23
|
+
* descriptions.
|
|
24
|
+
* @param schemas An object where each key is a name and each value is a description
|
|
25
|
+
* @returns A new instance of StructuredOutputParser.
|
|
26
|
+
*/
|
|
27
|
+
static fromNamesAndDescriptions<S extends {
|
|
28
|
+
[key: string]: string;
|
|
29
|
+
}>(schemas: S): StructuredOutputParser<z.ZodObject<{
|
|
30
|
+
[k: string]: z.ZodString;
|
|
31
|
+
}, "strip", z.ZodTypeAny, {
|
|
32
|
+
[x: string]: string;
|
|
33
|
+
}, {
|
|
34
|
+
[x: string]: string;
|
|
35
|
+
}>>;
|
|
36
|
+
/**
|
|
37
|
+
* Returns a markdown code snippet with a JSON object formatted according
|
|
38
|
+
* to the schema.
|
|
39
|
+
* @param options Optional. The options for formatting the instructions
|
|
40
|
+
* @returns A markdown code snippet with a JSON object formatted according to the schema.
|
|
41
|
+
*/
|
|
42
|
+
getFormatInstructions(): string;
|
|
43
|
+
/**
|
|
44
|
+
* Parses the given text according to the schema.
|
|
45
|
+
* @param text The text to parse
|
|
46
|
+
* @returns The parsed output.
|
|
47
|
+
*/
|
|
48
|
+
parse(text: string): Promise<z.infer<T>>;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* A specific type of `StructuredOutputParser` that parses JSON data
|
|
52
|
+
* formatted as a markdown code snippet.
|
|
53
|
+
*/
|
|
54
|
+
export declare class JsonMarkdownStructuredOutputParser<T extends z.ZodTypeAny> extends StructuredOutputParser<T> {
|
|
55
|
+
static lc_name(): string;
|
|
56
|
+
getFormatInstructions(options?: JsonMarkdownFormatInstructionsOptions): string;
|
|
57
|
+
private _schemaToInstruction;
|
|
58
|
+
static fromZodSchema<T extends z.ZodTypeAny>(schema: T): JsonMarkdownStructuredOutputParser<T>;
|
|
59
|
+
static fromNamesAndDescriptions<S extends {
|
|
60
|
+
[key: string]: string;
|
|
61
|
+
}>(schemas: S): JsonMarkdownStructuredOutputParser<z.ZodObject<{
|
|
62
|
+
[k: string]: z.ZodString;
|
|
63
|
+
}, "strip", z.ZodTypeAny, {
|
|
64
|
+
[x: string]: string;
|
|
65
|
+
}, {
|
|
66
|
+
[x: string]: string;
|
|
67
|
+
}>>;
|
|
68
|
+
}
|
|
69
|
+
export interface AsymmetricStructuredOutputParserFields<T extends z.ZodTypeAny> {
|
|
70
|
+
inputSchema: T;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* A type of `StructuredOutputParser` that handles asymmetric input and
|
|
74
|
+
* output schemas.
|
|
75
|
+
*/
|
|
76
|
+
export declare abstract class AsymmetricStructuredOutputParser<T extends z.ZodTypeAny, Y = unknown> extends BaseOutputParser<Y> {
|
|
77
|
+
private structuredInputParser;
|
|
78
|
+
constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>);
|
|
79
|
+
/**
|
|
80
|
+
* Processes the parsed input into the desired output format. Must be
|
|
81
|
+
* implemented by subclasses.
|
|
82
|
+
* @param input The parsed input
|
|
83
|
+
* @returns The processed output.
|
|
84
|
+
*/
|
|
85
|
+
abstract outputProcessor(input: z.infer<T>): Promise<Y>;
|
|
86
|
+
parse(text: string): Promise<Y>;
|
|
87
|
+
getFormatInstructions(): string;
|
|
88
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { zodToJsonSchema, } from "zod-to-json-schema";
|
|
3
|
+
import { BaseOutputParser, OutputParserException, } from "./base.js";
|
|
4
|
+
export class StructuredOutputParser extends BaseOutputParser {
|
|
5
|
+
static lc_name() {
|
|
6
|
+
return "StructuredOutputParser";
|
|
7
|
+
}
|
|
8
|
+
toJSON() {
|
|
9
|
+
return this.toJSONNotImplemented();
|
|
10
|
+
}
|
|
11
|
+
constructor(schema) {
|
|
12
|
+
super(schema);
|
|
13
|
+
Object.defineProperty(this, "schema", {
|
|
14
|
+
enumerable: true,
|
|
15
|
+
configurable: true,
|
|
16
|
+
writable: true,
|
|
17
|
+
value: schema
|
|
18
|
+
});
|
|
19
|
+
Object.defineProperty(this, "lc_namespace", {
|
|
20
|
+
enumerable: true,
|
|
21
|
+
configurable: true,
|
|
22
|
+
writable: true,
|
|
23
|
+
value: ["langchain", "output_parsers", "structured"]
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Creates a new StructuredOutputParser from a Zod schema.
|
|
28
|
+
* @param schema The Zod schema which the output should match
|
|
29
|
+
* @returns A new instance of StructuredOutputParser.
|
|
30
|
+
*/
|
|
31
|
+
static fromZodSchema(schema) {
|
|
32
|
+
return new this(schema);
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Creates a new StructuredOutputParser from a set of names and
|
|
36
|
+
* descriptions.
|
|
37
|
+
* @param schemas An object where each key is a name and each value is a description
|
|
38
|
+
* @returns A new instance of StructuredOutputParser.
|
|
39
|
+
*/
|
|
40
|
+
static fromNamesAndDescriptions(schemas) {
|
|
41
|
+
const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)])));
|
|
42
|
+
return new this(zodSchema);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Returns a markdown code snippet with a JSON object formatted according
|
|
46
|
+
* to the schema.
|
|
47
|
+
* @param options Optional. The options for formatting the instructions
|
|
48
|
+
* @returns A markdown code snippet with a JSON object formatted according to the schema.
|
|
49
|
+
*/
|
|
50
|
+
getFormatInstructions() {
|
|
51
|
+
return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
52
|
+
|
|
53
|
+
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
54
|
+
|
|
55
|
+
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}
|
|
56
|
+
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.
|
|
57
|
+
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.
|
|
58
|
+
|
|
59
|
+
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!
|
|
60
|
+
|
|
61
|
+
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
62
|
+
\`\`\`json
|
|
63
|
+
${JSON.stringify(zodToJsonSchema(this.schema))}
|
|
64
|
+
\`\`\`
|
|
65
|
+
`;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Parses the given text according to the schema.
|
|
69
|
+
* @param text The text to parse
|
|
70
|
+
* @returns The parsed output.
|
|
71
|
+
*/
|
|
72
|
+
async parse(text) {
|
|
73
|
+
try {
|
|
74
|
+
const json = text.includes("```")
|
|
75
|
+
? text.trim().split(/```(?:json)?/)[1]
|
|
76
|
+
: text.trim();
|
|
77
|
+
return await this.schema.parseAsync(JSON.parse(json));
|
|
78
|
+
}
|
|
79
|
+
catch (e) {
|
|
80
|
+
throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* A specific type of `StructuredOutputParser` that parses JSON data
|
|
86
|
+
* formatted as a markdown code snippet.
|
|
87
|
+
*/
|
|
88
|
+
export class JsonMarkdownStructuredOutputParser extends StructuredOutputParser {
|
|
89
|
+
static lc_name() {
|
|
90
|
+
return "JsonMarkdownStructuredOutputParser";
|
|
91
|
+
}
|
|
92
|
+
getFormatInstructions(options) {
|
|
93
|
+
const interpolationDepth = options?.interpolationDepth ?? 1;
|
|
94
|
+
if (interpolationDepth < 1) {
|
|
95
|
+
throw new Error("f string interpolation depth must be at least 1");
|
|
96
|
+
}
|
|
97
|
+
return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(zodToJsonSchema(this.schema))
|
|
98
|
+
.replaceAll("{", "{".repeat(interpolationDepth))
|
|
99
|
+
.replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``;
|
|
100
|
+
}
|
|
101
|
+
_schemaToInstruction(schemaInput, indent = 2) {
|
|
102
|
+
const schema = schemaInput;
|
|
103
|
+
if ("type" in schema) {
|
|
104
|
+
let nullable = false;
|
|
105
|
+
let type;
|
|
106
|
+
if (Array.isArray(schema.type)) {
|
|
107
|
+
const nullIdx = schema.type.findIndex((type) => type === "null");
|
|
108
|
+
if (nullIdx !== -1) {
|
|
109
|
+
nullable = true;
|
|
110
|
+
schema.type.splice(nullIdx, 1);
|
|
111
|
+
}
|
|
112
|
+
type = schema.type.join(" | ");
|
|
113
|
+
}
|
|
114
|
+
else {
|
|
115
|
+
type = schema.type;
|
|
116
|
+
}
|
|
117
|
+
if (schema.type === "object" && schema.properties) {
|
|
118
|
+
const description = schema.description
|
|
119
|
+
? ` // ${schema.description}`
|
|
120
|
+
: "";
|
|
121
|
+
const properties = Object.entries(schema.properties)
|
|
122
|
+
.map(([key, value]) => {
|
|
123
|
+
const isOptional = schema.required?.includes(key)
|
|
124
|
+
? ""
|
|
125
|
+
: " (optional)";
|
|
126
|
+
return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`;
|
|
127
|
+
})
|
|
128
|
+
.join("\n");
|
|
129
|
+
return `{\n${properties}\n${" ".repeat(indent - 2)}}${description}`;
|
|
130
|
+
}
|
|
131
|
+
if (schema.type === "array" && schema.items) {
|
|
132
|
+
const description = schema.description
|
|
133
|
+
? ` // ${schema.description}`
|
|
134
|
+
: "";
|
|
135
|
+
return `array[\n${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)}\n${" ".repeat(indent - 2)}] ${description}`;
|
|
136
|
+
}
|
|
137
|
+
const isNullable = nullable ? " (nullable)" : "";
|
|
138
|
+
const description = schema.description ? ` // ${schema.description}` : "";
|
|
139
|
+
return `${type}${description}${isNullable}`;
|
|
140
|
+
}
|
|
141
|
+
if ("anyOf" in schema) {
|
|
142
|
+
return schema.anyOf
|
|
143
|
+
.map((s) => this._schemaToInstruction(s, indent))
|
|
144
|
+
.join(`\n${" ".repeat(indent - 2)}`);
|
|
145
|
+
}
|
|
146
|
+
throw new Error("unsupported schema type");
|
|
147
|
+
}
|
|
148
|
+
static fromZodSchema(schema) {
|
|
149
|
+
return new this(schema);
|
|
150
|
+
}
|
|
151
|
+
static fromNamesAndDescriptions(schemas) {
|
|
152
|
+
const zodSchema = z.object(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, z.string().describe(description)])));
|
|
153
|
+
return new this(zodSchema);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* A type of `StructuredOutputParser` that handles asymmetric input and
|
|
158
|
+
* output schemas.
|
|
159
|
+
*/
|
|
160
|
+
export class AsymmetricStructuredOutputParser extends BaseOutputParser {
|
|
161
|
+
constructor({ inputSchema }) {
|
|
162
|
+
super(...arguments);
|
|
163
|
+
Object.defineProperty(this, "structuredInputParser", {
|
|
164
|
+
enumerable: true,
|
|
165
|
+
configurable: true,
|
|
166
|
+
writable: true,
|
|
167
|
+
value: void 0
|
|
168
|
+
});
|
|
169
|
+
this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema);
|
|
170
|
+
}
|
|
171
|
+
async parse(text) {
|
|
172
|
+
let parsedInput;
|
|
173
|
+
try {
|
|
174
|
+
parsedInput = await this.structuredInputParser.parse(text);
|
|
175
|
+
}
|
|
176
|
+
catch (e) {
|
|
177
|
+
throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text);
|
|
178
|
+
}
|
|
179
|
+
return this.outputProcessor(parsedInput);
|
|
180
|
+
}
|
|
181
|
+
getFormatInstructions() {
|
|
182
|
+
return this.structuredInputParser.getFormatInstructions();
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -311,7 +311,7 @@ class FakeListChatModel extends chat_models_js_1.BaseChatModel {
|
|
|
311
311
|
this.i = 0;
|
|
312
312
|
}
|
|
313
313
|
}
|
|
314
|
-
withStructuredOutput(_params) {
|
|
314
|
+
withStructuredOutput(_params, _config) {
|
|
315
315
|
return base_js_2.RunnableLambda.from(async (input) => {
|
|
316
316
|
const message = await this.invoke(input);
|
|
317
317
|
return JSON.parse(message.content);
|
|
@@ -12,7 +12,7 @@ import { Runnable } from "../../runnables/base.js";
|
|
|
12
12
|
import { StructuredTool, ToolParams } from "../../tools.js";
|
|
13
13
|
import { BaseTracer, Run } from "../../tracers/base.js";
|
|
14
14
|
import { Embeddings, EmbeddingsParams } from "../../embeddings.js";
|
|
15
|
-
import { StructuredOutputMethodParams, BaseLanguageModelInput } from "../../language_models/base.js";
|
|
15
|
+
import { StructuredOutputMethodParams, BaseLanguageModelInput, StructuredOutputMethodOptions } from "../../language_models/base.js";
|
|
16
16
|
/**
|
|
17
17
|
* Parser for comma-separated values. It splits the input text by commas
|
|
18
18
|
* and trims the resulting values.
|
|
@@ -114,8 +114,8 @@ export declare class FakeListChatModel extends BaseChatModel {
|
|
|
114
114
|
_createResponseChunk(text: string): ChatGenerationChunk;
|
|
115
115
|
_currentResponse(): string;
|
|
116
116
|
_incrementResponse(): void;
|
|
117
|
-
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
118
|
-
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, true>): Runnable<BaseLanguageModelInput, {
|
|
117
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, false> | z.ZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
118
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(_params: StructuredOutputMethodParams<RunOutput, true> | z.ZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
119
119
|
raw: BaseMessage;
|
|
120
120
|
parsed: RunOutput;
|
|
121
121
|
}>;
|
|
@@ -302,7 +302,7 @@ export class FakeListChatModel extends BaseChatModel {
|
|
|
302
302
|
this.i = 0;
|
|
303
303
|
}
|
|
304
304
|
}
|
|
305
|
-
withStructuredOutput(_params) {
|
|
305
|
+
withStructuredOutput(_params, _config) {
|
|
306
306
|
return RunnableLambda.from(async (input) => {
|
|
307
307
|
const message = await this.invoke(input);
|
|
308
308
|
return JSON.parse(message.content);
|