@langchain/core 0.1.43 → 0.1.45-rc.0
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/callbacks/base.cjs +3 -4
- package/dist/callbacks/base.d.ts +1 -0
- package/dist/callbacks/base.js +3 -4
- package/dist/callbacks/manager.cjs +10 -0
- package/dist/callbacks/manager.js +10 -0
- package/dist/language_models/base.d.ts +1 -0
- package/dist/load/serializable.d.ts +6 -1
- package/dist/output_parsers/base.cjs +9 -3
- package/dist/output_parsers/base.d.ts +3 -1
- package/dist/output_parsers/base.js +9 -3
- 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/string.cjs +21 -0
- package/dist/output_parsers/string.d.ts +5 -0
- package/dist/output_parsers/string.js +21 -0
- 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/output_parsers/transform.cjs +1 -3
- package/dist/output_parsers/transform.js +1 -3
- package/dist/runnables/base.cjs +44 -1
- package/dist/runnables/base.d.ts +6 -25
- package/dist/runnables/base.js +45 -2
- package/dist/runnables/graph.cjs +164 -0
- package/dist/runnables/graph.d.ts +25 -0
- package/dist/runnables/graph.js +159 -0
- package/dist/runnables/index.d.ts +2 -1
- package/dist/runnables/types.cjs +2 -0
- package/dist/runnables/types.d.ts +33 -0
- package/dist/runnables/types.js +1 -0
- package/dist/runnables/utils.cjs +6 -1
- package/dist/runnables/utils.d.ts +2 -0
- package/dist/runnables/utils.js +4 -0
- package/dist/tracers/log_stream.cjs +1 -1
- package/dist/tracers/log_stream.js +1 -1
- package/dist/tracers/root_listener.cjs +1 -1
- package/dist/tracers/root_listener.js +1 -1
- package/dist/tracers/run_collector.cjs +1 -1
- package/dist/tracers/run_collector.js +1 -1
- package/package.json +1 -1
package/dist/callbacks/base.cjs
CHANGED
|
@@ -26,6 +26,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
26
26
|
exports.BaseCallbackHandler = void 0;
|
|
27
27
|
const uuid = __importStar(require("uuid"));
|
|
28
28
|
const serializable_js_1 = require("../load/serializable.cjs");
|
|
29
|
+
const env_js_1 = require("../utils/env.cjs");
|
|
29
30
|
/**
|
|
30
31
|
* Abstract class that provides a set of optional methods that can be
|
|
31
32
|
* overridden in derived classes to handle various events during the
|
|
@@ -112,10 +113,7 @@ class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
|
|
|
112
113
|
enumerable: true,
|
|
113
114
|
configurable: true,
|
|
114
115
|
writable: true,
|
|
115
|
-
value:
|
|
116
|
-
? // eslint-disable-next-line no-process-env
|
|
117
|
-
process.env?.LANGCHAIN_CALLBACKS_BACKGROUND !== "true"
|
|
118
|
-
: true
|
|
116
|
+
value: (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND") !== "true"
|
|
119
117
|
});
|
|
120
118
|
this.lc_kwargs = input || {};
|
|
121
119
|
if (input) {
|
|
@@ -123,6 +121,7 @@ class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
|
|
|
123
121
|
this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
|
|
124
122
|
this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
|
|
125
123
|
this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
|
|
124
|
+
this.awaitHandlers = input._awaitHandler ?? this.awaitHandlers;
|
|
126
125
|
}
|
|
127
126
|
}
|
|
128
127
|
copy() {
|
package/dist/callbacks/base.d.ts
CHANGED
package/dist/callbacks/base.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as uuid from "uuid";
|
|
2
2
|
import { Serializable, get_lc_unique_name, } from "../load/serializable.js";
|
|
3
|
+
import { getEnvironmentVariable } from "../utils/env.js";
|
|
3
4
|
/**
|
|
4
5
|
* Abstract class that provides a set of optional methods that can be
|
|
5
6
|
* overridden in derived classes to handle various events during the
|
|
@@ -86,10 +87,7 @@ export class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
|
|
|
86
87
|
enumerable: true,
|
|
87
88
|
configurable: true,
|
|
88
89
|
writable: true,
|
|
89
|
-
value:
|
|
90
|
-
? // eslint-disable-next-line no-process-env
|
|
91
|
-
process.env?.LANGCHAIN_CALLBACKS_BACKGROUND !== "true"
|
|
92
|
-
: true
|
|
90
|
+
value: getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") !== "true"
|
|
93
91
|
});
|
|
94
92
|
this.lc_kwargs = input || {};
|
|
95
93
|
if (input) {
|
|
@@ -97,6 +95,7 @@ export class BaseCallbackHandler extends BaseCallbackHandlerMethodsClass {
|
|
|
97
95
|
this.ignoreChain = input.ignoreChain ?? this.ignoreChain;
|
|
98
96
|
this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent;
|
|
99
97
|
this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever;
|
|
98
|
+
this.awaitHandlers = input._awaitHandler ?? this.awaitHandlers;
|
|
100
99
|
}
|
|
101
100
|
}
|
|
102
101
|
copy() {
|
|
@@ -9,6 +9,16 @@ const index_js_1 = require("../messages/index.cjs");
|
|
|
9
9
|
const env_js_1 = require("../utils/env.cjs");
|
|
10
10
|
const tracer_langchain_js_1 = require("../tracers/tracer_langchain.cjs");
|
|
11
11
|
const promises_js_1 = require("./promises.cjs");
|
|
12
|
+
if (
|
|
13
|
+
/* #__PURE__ */ (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_TRACING_V2") === "true" &&
|
|
14
|
+
/* #__PURE__ */ (0, env_js_1.getEnvironmentVariable)("LANGCHAIN_CALLBACKS_BACKGROUND") !==
|
|
15
|
+
"true") {
|
|
16
|
+
/* #__PURE__ */ console.warn([
|
|
17
|
+
"[WARN]: You have enabled LangSmith tracing without backgrounding callbacks.",
|
|
18
|
+
"[WARN]: If you are not using a serverless environment where you must wait for tracing calls to finish,",
|
|
19
|
+
`[WARN]: we suggest setting "process.env.LANGCHAIN_CALLBACKS_BACKGROUND=true" to avoid additional latency.`,
|
|
20
|
+
].join("\n"));
|
|
21
|
+
}
|
|
12
22
|
function parseCallbackConfigArg(arg) {
|
|
13
23
|
if (!arg) {
|
|
14
24
|
return {};
|
|
@@ -6,6 +6,16 @@ import { getBufferString } from "../messages/index.js";
|
|
|
6
6
|
import { getEnvironmentVariable } from "../utils/env.js";
|
|
7
7
|
import { LangChainTracer, } from "../tracers/tracer_langchain.js";
|
|
8
8
|
import { consumeCallback } from "./promises.js";
|
|
9
|
+
if (
|
|
10
|
+
/* #__PURE__ */ getEnvironmentVariable("LANGCHAIN_TRACING_V2") === "true" &&
|
|
11
|
+
/* #__PURE__ */ getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") !==
|
|
12
|
+
"true") {
|
|
13
|
+
/* #__PURE__ */ console.warn([
|
|
14
|
+
"[WARN]: You have enabled LangSmith tracing without backgrounding callbacks.",
|
|
15
|
+
"[WARN]: If you are not using a serverless environment where you must wait for tracing calls to finish,",
|
|
16
|
+
`[WARN]: we suggest setting "process.env.LANGCHAIN_CALLBACKS_BACKGROUND=true" to avoid additional latency.`,
|
|
17
|
+
].join("\n"));
|
|
18
|
+
}
|
|
9
19
|
export function parseCallbackConfigArg(arg) {
|
|
10
20
|
if (!arg) {
|
|
11
21
|
return {};
|
|
@@ -203,6 +203,7 @@ export declare abstract class BaseLanguageModel<RunOutput = any, CallOptions ext
|
|
|
203
203
|
* @template {Record<string, any>} RunOutput The output type for the Runnable, expected to be a Zod schema object for structured output validation.
|
|
204
204
|
*
|
|
205
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.
|
|
206
207
|
* @param {string} name The name of the function to call.
|
|
207
208
|
* @param {"functionCalling" | "jsonMode"} [method=functionCalling] The method to use for getting the structured output. Defaults to "functionCalling".
|
|
208
209
|
* @param {boolean | undefined} [includeRaw=false] Whether to include the raw output in the result. Defaults to false.
|
|
@@ -3,6 +3,8 @@ export interface BaseSerialized<T extends string> {
|
|
|
3
3
|
lc: number;
|
|
4
4
|
type: T;
|
|
5
5
|
id: string[];
|
|
6
|
+
name?: string;
|
|
7
|
+
graph?: Record<string, any>;
|
|
6
8
|
}
|
|
7
9
|
export interface SerializedConstructor extends BaseSerialized<"constructor"> {
|
|
8
10
|
kwargs: SerializedFields;
|
|
@@ -17,7 +19,10 @@ export type Serialized = SerializedConstructor | SerializedSecret | SerializedNo
|
|
|
17
19
|
* Should not be subclassed, subclass lc_name above instead.
|
|
18
20
|
*/
|
|
19
21
|
export declare function get_lc_unique_name(serializableClass: typeof Serializable): string;
|
|
20
|
-
export
|
|
22
|
+
export interface SerializableInterface {
|
|
23
|
+
get lc_id(): string[];
|
|
24
|
+
}
|
|
25
|
+
export declare abstract class Serializable implements SerializableInterface {
|
|
21
26
|
lc_serializable: boolean;
|
|
22
27
|
lc_kwargs: SerializedFields;
|
|
23
28
|
/**
|
|
@@ -19,6 +19,14 @@ class BaseLLMOutputParser extends index_js_1.Runnable {
|
|
|
19
19
|
parseResultWithPrompt(generations, _prompt, callbacks) {
|
|
20
20
|
return this.parseResult(generations, callbacks);
|
|
21
21
|
}
|
|
22
|
+
_baseMessageToString(message) {
|
|
23
|
+
return typeof message.content === "string"
|
|
24
|
+
? message.content
|
|
25
|
+
: this._baseMessageContentToString(message.content);
|
|
26
|
+
}
|
|
27
|
+
_baseMessageContentToString(content) {
|
|
28
|
+
return JSON.stringify(content);
|
|
29
|
+
}
|
|
22
30
|
/**
|
|
23
31
|
* Calls the parser with a given input and optional configuration options.
|
|
24
32
|
* If the input is a string, it creates a generation with the input as
|
|
@@ -37,9 +45,7 @@ class BaseLLMOutputParser extends index_js_1.Runnable {
|
|
|
37
45
|
return this._callWithConfig(async (input) => this.parseResult([
|
|
38
46
|
{
|
|
39
47
|
message: input,
|
|
40
|
-
text:
|
|
41
|
-
? input.content
|
|
42
|
-
: JSON.stringify(input.content),
|
|
48
|
+
text: this._baseMessageToString(input),
|
|
43
49
|
},
|
|
44
50
|
]), input, { ...options, runType: "parser" });
|
|
45
51
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Runnable } from "../runnables/index.js";
|
|
2
2
|
import type { RunnableConfig } from "../runnables/config.js";
|
|
3
3
|
import type { BasePromptValueInterface } from "../prompt_values.js";
|
|
4
|
-
import type { BaseMessage } from "../messages/index.js";
|
|
4
|
+
import type { BaseMessage, MessageContentComplex } from "../messages/index.js";
|
|
5
5
|
import type { Callbacks } from "../callbacks/manager.js";
|
|
6
6
|
import type { Generation, ChatGeneration } from "../outputs.js";
|
|
7
7
|
/**
|
|
@@ -33,6 +33,8 @@ export declare abstract class BaseLLMOutputParser<T = unknown> extends Runnable<
|
|
|
33
33
|
* @returns A promise of the parsed output.
|
|
34
34
|
*/
|
|
35
35
|
parseResultWithPrompt(generations: Generation[] | ChatGeneration[], _prompt: BasePromptValueInterface, callbacks?: Callbacks): Promise<T>;
|
|
36
|
+
protected _baseMessageToString(message: BaseMessage): string;
|
|
37
|
+
protected _baseMessageContentToString(content: MessageContentComplex[]): string;
|
|
36
38
|
/**
|
|
37
39
|
* Calls the parser with a given input and optional configuration options.
|
|
38
40
|
* If the input is a string, it creates a generation with the input as
|
|
@@ -16,6 +16,14 @@ export class BaseLLMOutputParser extends Runnable {
|
|
|
16
16
|
parseResultWithPrompt(generations, _prompt, callbacks) {
|
|
17
17
|
return this.parseResult(generations, callbacks);
|
|
18
18
|
}
|
|
19
|
+
_baseMessageToString(message) {
|
|
20
|
+
return typeof message.content === "string"
|
|
21
|
+
? message.content
|
|
22
|
+
: this._baseMessageContentToString(message.content);
|
|
23
|
+
}
|
|
24
|
+
_baseMessageContentToString(content) {
|
|
25
|
+
return JSON.stringify(content);
|
|
26
|
+
}
|
|
19
27
|
/**
|
|
20
28
|
* Calls the parser with a given input and optional configuration options.
|
|
21
29
|
* If the input is a string, it creates a generation with the input as
|
|
@@ -34,9 +42,7 @@ export class BaseLLMOutputParser extends Runnable {
|
|
|
34
42
|
return this._callWithConfig(async (input) => this.parseResult([
|
|
35
43
|
{
|
|
36
44
|
message: input,
|
|
37
|
-
text:
|
|
38
|
-
? input.content
|
|
39
|
-
: JSON.stringify(input.content),
|
|
45
|
+
text: this._baseMessageToString(input),
|
|
40
46
|
},
|
|
41
47
|
]), input, { ...options, runType: "parser" });
|
|
42
48
|
}
|
|
@@ -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
|
}
|
|
@@ -53,5 +53,26 @@ class StringOutputParser extends transform_js_1.BaseTransformOutputParser {
|
|
|
53
53
|
getFormatInstructions() {
|
|
54
54
|
return "";
|
|
55
55
|
}
|
|
56
|
+
_textContentToString(content) {
|
|
57
|
+
return content.text;
|
|
58
|
+
}
|
|
59
|
+
_imageUrlContentToString(_content) {
|
|
60
|
+
throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`);
|
|
61
|
+
}
|
|
62
|
+
_messageContentComplexToString(content) {
|
|
63
|
+
switch (content.type) {
|
|
64
|
+
case "text":
|
|
65
|
+
return this._textContentToString(content);
|
|
66
|
+
case "image_url":
|
|
67
|
+
return this._imageUrlContentToString(content);
|
|
68
|
+
default:
|
|
69
|
+
throw new Error(
|
|
70
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
71
|
+
`Cannot coerce "${content.type}" message part into a string.`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
_baseMessageContentToString(content) {
|
|
75
|
+
return content.reduce((acc, item) => acc + this._messageContentComplexToString(item), "");
|
|
76
|
+
}
|
|
56
77
|
}
|
|
57
78
|
exports.StringOutputParser = StringOutputParser;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BaseTransformOutputParser } from "./transform.js";
|
|
2
|
+
import { MessageContentComplex, MessageContentImageUrl, MessageContentText } from "../messages/index.js";
|
|
2
3
|
/**
|
|
3
4
|
* OutputParser that parses LLMResult into the top likely string.
|
|
4
5
|
* @example
|
|
@@ -31,4 +32,8 @@ export declare class StringOutputParser extends BaseTransformOutputParser<string
|
|
|
31
32
|
*/
|
|
32
33
|
parse(text: string): Promise<string>;
|
|
33
34
|
getFormatInstructions(): string;
|
|
35
|
+
protected _textContentToString(content: MessageContentText): string;
|
|
36
|
+
protected _imageUrlContentToString(_content: MessageContentImageUrl): string;
|
|
37
|
+
protected _messageContentComplexToString(content: MessageContentComplex): string;
|
|
38
|
+
protected _baseMessageContentToString(content: MessageContentComplex[]): string;
|
|
34
39
|
}
|
|
@@ -50,4 +50,25 @@ export class StringOutputParser extends BaseTransformOutputParser {
|
|
|
50
50
|
getFormatInstructions() {
|
|
51
51
|
return "";
|
|
52
52
|
}
|
|
53
|
+
_textContentToString(content) {
|
|
54
|
+
return content.text;
|
|
55
|
+
}
|
|
56
|
+
_imageUrlContentToString(_content) {
|
|
57
|
+
throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`);
|
|
58
|
+
}
|
|
59
|
+
_messageContentComplexToString(content) {
|
|
60
|
+
switch (content.type) {
|
|
61
|
+
case "text":
|
|
62
|
+
return this._textContentToString(content);
|
|
63
|
+
case "image_url":
|
|
64
|
+
return this._imageUrlContentToString(content);
|
|
65
|
+
default:
|
|
66
|
+
throw new Error(
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
68
|
+
`Cannot coerce "${content.type}" message part into a string.`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
_baseMessageContentToString(content) {
|
|
72
|
+
return content.reduce((acc, item) => acc + this._messageContentComplexToString(item), "");
|
|
73
|
+
}
|
|
53
74
|
}
|
|
@@ -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;
|