@langchain/openai 0.6.8 → 1.0.0-alpha.1
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/README.md +8 -8
- package/dist/_virtual/rolldown_runtime.cjs +25 -0
- package/dist/azure/chat_models.cjs +661 -808
- package/dist/azure/chat_models.cjs.map +1 -0
- package/dist/azure/chat_models.d.cts +449 -0
- package/dist/azure/chat_models.d.cts.map +1 -0
- package/dist/azure/chat_models.d.ts +32 -28
- package/dist/azure/chat_models.d.ts.map +1 -0
- package/dist/azure/chat_models.js +660 -804
- package/dist/azure/chat_models.js.map +1 -0
- package/dist/azure/embeddings.cjs +81 -130
- package/dist/azure/embeddings.cjs.map +1 -0
- package/dist/azure/embeddings.d.cts +27 -0
- package/dist/azure/embeddings.d.cts.map +1 -0
- package/dist/azure/embeddings.d.ts +25 -20
- package/dist/azure/embeddings.d.ts.map +1 -0
- package/dist/azure/embeddings.js +80 -126
- package/dist/azure/embeddings.js.map +1 -0
- package/dist/azure/llms.cjs +109 -168
- package/dist/azure/llms.cjs.map +1 -0
- package/dist/azure/llms.d.cts +33 -0
- package/dist/azure/llms.d.cts.map +1 -0
- package/dist/azure/llms.d.ts +31 -25
- package/dist/azure/llms.d.ts.map +1 -0
- package/dist/azure/llms.js +108 -164
- package/dist/azure/llms.js.map +1 -0
- package/dist/chat_models.cjs +1951 -2763
- package/dist/chat_models.cjs.map +1 -0
- package/dist/chat_models.d.cts +930 -0
- package/dist/chat_models.d.cts.map +1 -0
- package/dist/chat_models.d.ts +365 -336
- package/dist/chat_models.d.ts.map +1 -0
- package/dist/chat_models.js +1946 -2753
- package/dist/chat_models.js.map +1 -0
- package/dist/embeddings.cjs +136 -193
- package/dist/embeddings.cjs.map +1 -0
- package/dist/embeddings.d.cts +115 -0
- package/dist/embeddings.d.cts.map +1 -0
- package/dist/embeddings.d.ts +88 -81
- package/dist/embeddings.d.ts.map +1 -0
- package/dist/embeddings.js +134 -188
- package/dist/embeddings.js.map +1 -0
- package/dist/index.cjs +47 -34
- package/dist/index.d.cts +16 -0
- package/dist/index.d.ts +16 -13
- package/dist/index.js +17 -13
- package/dist/langchain-core/dist/types/_internal.d.cts +11 -0
- package/dist/langchain-core/dist/types/_internal.d.cts.map +1 -0
- package/dist/langchain-core/dist/types/_internal.d.ts +11 -0
- package/dist/langchain-core/dist/types/_internal.d.ts.map +1 -0
- package/dist/langchain-core/dist/utils/stream.d.cts +26 -0
- package/dist/langchain-core/dist/utils/stream.d.cts.map +1 -0
- package/dist/langchain-core/dist/utils/stream.d.ts +26 -0
- package/dist/langchain-core/dist/utils/stream.d.ts.map +1 -0
- package/dist/llms.cjs +312 -468
- package/dist/llms.cjs.map +1 -0
- package/dist/llms.d.cts +123 -0
- package/dist/llms.d.cts.map +1 -0
- package/dist/llms.d.ts +93 -87
- package/dist/llms.d.ts.map +1 -0
- package/dist/llms.js +309 -462
- package/dist/llms.js.map +1 -0
- package/dist/tools/custom.cjs +25 -26
- package/dist/tools/custom.cjs.map +1 -0
- package/dist/tools/custom.d.cts +10 -0
- package/dist/tools/custom.d.cts.map +1 -0
- package/dist/tools/custom.d.ts +8 -3
- package/dist/tools/custom.d.ts.map +1 -0
- package/dist/tools/custom.js +24 -23
- package/dist/tools/custom.js.map +1 -0
- package/dist/tools/dalle.cjs +104 -194
- package/dist/tools/dalle.cjs.map +1 -0
- package/dist/tools/dalle.d.cts +123 -0
- package/dist/tools/dalle.d.cts.map +1 -0
- package/dist/tools/dalle.d.ts +111 -104
- package/dist/tools/dalle.d.ts.map +1 -0
- package/dist/tools/dalle.js +102 -189
- package/dist/tools/dalle.js.map +1 -0
- package/dist/tools/index.cjs +1 -17
- package/dist/tools/index.js +1 -1
- package/dist/types.d.cts +263 -0
- package/dist/types.d.cts.map +1 -0
- package/dist/types.d.ts +244 -234
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/azure.cjs +86 -47
- package/dist/utils/azure.cjs.map +1 -0
- package/dist/utils/azure.d.cts +76 -0
- package/dist/utils/azure.d.cts.map +1 -0
- package/dist/utils/azure.d.ts +51 -9
- package/dist/utils/azure.d.ts.map +1 -0
- package/dist/utils/azure.js +85 -45
- package/dist/utils/azure.js.map +1 -0
- package/dist/utils/client.cjs +25 -0
- package/dist/utils/client.cjs.map +1 -0
- package/dist/utils/client.d.cts +5 -0
- package/dist/utils/client.d.cts.map +1 -0
- package/dist/utils/client.d.ts +5 -0
- package/dist/utils/client.d.ts.map +1 -0
- package/dist/utils/client.js +24 -0
- package/dist/utils/client.js.map +1 -0
- package/dist/utils/errors.cjs +9 -8
- package/dist/utils/errors.cjs.map +1 -0
- package/dist/utils/errors.js +9 -6
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/message_inputs.cjs +139 -0
- package/dist/utils/message_inputs.cjs.map +1 -0
- package/dist/utils/message_inputs.d.cts +9 -0
- package/dist/utils/message_inputs.d.cts.map +1 -0
- package/dist/utils/message_inputs.d.ts +9 -0
- package/dist/utils/message_inputs.d.ts.map +1 -0
- package/dist/utils/message_inputs.js +137 -0
- package/dist/utils/message_inputs.js.map +1 -0
- package/dist/utils/misc.cjs +30 -0
- package/dist/utils/misc.cjs.map +1 -0
- package/dist/utils/misc.d.cts +9 -0
- package/dist/utils/misc.d.cts.map +1 -0
- package/dist/utils/misc.d.ts +9 -0
- package/dist/utils/misc.d.ts.map +1 -0
- package/dist/utils/misc.js +27 -0
- package/dist/utils/misc.js.map +1 -0
- package/dist/utils/output.cjs +74 -0
- package/dist/utils/output.cjs.map +1 -0
- package/dist/utils/output.js +72 -0
- package/dist/utils/output.js.map +1 -0
- package/dist/utils/prompts.cjs +39 -38
- package/dist/utils/prompts.cjs.map +1 -0
- package/dist/utils/prompts.d.cts +42 -0
- package/dist/utils/prompts.d.cts.map +1 -0
- package/dist/utils/prompts.d.ts +10 -4
- package/dist/utils/prompts.d.ts.map +1 -0
- package/dist/utils/prompts.js +40 -36
- package/dist/utils/prompts.js.map +1 -0
- package/dist/utils/standard.cjs +113 -0
- package/dist/utils/standard.cjs.map +1 -0
- package/dist/utils/standard.js +111 -0
- package/dist/utils/standard.js.map +1 -0
- package/dist/utils/tools.cjs +150 -127
- package/dist/utils/tools.cjs.map +1 -0
- package/dist/utils/tools.d.cts +13 -0
- package/dist/utils/tools.d.cts.map +1 -0
- package/dist/utils/tools.d.ts +12 -42
- package/dist/utils/tools.d.ts.map +1 -0
- package/dist/utils/tools.js +146 -123
- package/dist/utils/tools.js.map +1 -0
- package/package.json +33 -41
- package/dist/tools/index.d.ts +0 -1
- package/dist/types.cjs +0 -2
- package/dist/types.js +0 -1
- package/dist/utils/errors.d.ts +0 -2
- package/dist/utils/headers.cjs +0 -39
- package/dist/utils/headers.d.ts +0 -8
- package/dist/utils/headers.js +0 -35
- package/dist/utils/openai-format-fndef.cjs +0 -80
- package/dist/utils/openai-format-fndef.d.ts +0 -44
- package/dist/utils/openai-format-fndef.js +0 -77
- package/dist/utils/openai.cjs +0 -127
- package/dist/utils/openai.d.ts +0 -15
- package/dist/utils/openai.js +0 -119
- package/index.cjs +0 -1
- package/index.d.cts +0 -1
- package/index.d.ts +0 -1
- package/index.js +0 -1
package/dist/chat_models.cjs
CHANGED
|
@@ -1,2769 +1,1957 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const
|
|
7
|
-
const
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
const
|
|
19
|
-
const
|
|
20
|
-
|
|
1
|
+
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_misc = require('./utils/misc.cjs');
|
|
3
|
+
const require_azure = require('./utils/azure.cjs');
|
|
4
|
+
const require_client = require('./utils/client.cjs');
|
|
5
|
+
const require_tools = require('./utils/tools.cjs');
|
|
6
|
+
const require_output = require('./utils/output.cjs');
|
|
7
|
+
const require_standard = require('./utils/standard.cjs');
|
|
8
|
+
const require_message_inputs = require('./utils/message_inputs.cjs');
|
|
9
|
+
const openai = require_rolldown_runtime.__toESM(require("openai"));
|
|
10
|
+
const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
|
|
11
|
+
const __langchain_core_outputs = require_rolldown_runtime.__toESM(require("@langchain/core/outputs"));
|
|
12
|
+
const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
|
|
13
|
+
const __langchain_core_language_models_chat_models = require_rolldown_runtime.__toESM(require("@langchain/core/language_models/chat_models"));
|
|
14
|
+
const __langchain_core_language_models_base = require_rolldown_runtime.__toESM(require("@langchain/core/language_models/base"));
|
|
15
|
+
const __langchain_core_runnables = require_rolldown_runtime.__toESM(require("@langchain/core/runnables"));
|
|
16
|
+
const __langchain_core_output_parsers = require_rolldown_runtime.__toESM(require("@langchain/core/output_parsers"));
|
|
17
|
+
const __langchain_core_output_parsers_openai_tools = require_rolldown_runtime.__toESM(require("@langchain/core/output_parsers/openai_tools"));
|
|
18
|
+
const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
|
|
19
|
+
const __langchain_core_utils_json_schema = require_rolldown_runtime.__toESM(require("@langchain/core/utils/json_schema"));
|
|
20
|
+
|
|
21
|
+
//#region src/chat_models.ts
|
|
21
22
|
const _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__";
|
|
22
|
-
function isReasoningModel(model) {
|
|
23
|
-
if (!model)
|
|
24
|
-
return false;
|
|
25
|
-
if (/^o\d/.test(model ?? ""))
|
|
26
|
-
return true;
|
|
27
|
-
if (model.startsWith("gpt-5") && !model.startsWith("gpt-5-chat"))
|
|
28
|
-
return true;
|
|
29
|
-
return false;
|
|
30
|
-
}
|
|
31
|
-
function isStructuredOutputMethodParams(x
|
|
32
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
33
|
-
) {
|
|
34
|
-
return (x !== undefined &&
|
|
35
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
36
|
-
typeof x.schema ===
|
|
37
|
-
"object");
|
|
38
|
-
}
|
|
39
|
-
function extractGenericMessageCustomRole(message) {
|
|
40
|
-
if (message.role !== "system" &&
|
|
41
|
-
message.role !== "developer" &&
|
|
42
|
-
message.role !== "assistant" &&
|
|
43
|
-
message.role !== "user" &&
|
|
44
|
-
message.role !== "function" &&
|
|
45
|
-
message.role !== "tool") {
|
|
46
|
-
console.warn(`Unknown message role: ${message.role}`);
|
|
47
|
-
}
|
|
48
|
-
return message.role;
|
|
49
|
-
}
|
|
50
|
-
function messageToOpenAIRole(message) {
|
|
51
|
-
const type = message._getType();
|
|
52
|
-
switch (type) {
|
|
53
|
-
case "system":
|
|
54
|
-
return "system";
|
|
55
|
-
case "ai":
|
|
56
|
-
return "assistant";
|
|
57
|
-
case "human":
|
|
58
|
-
return "user";
|
|
59
|
-
case "function":
|
|
60
|
-
return "function";
|
|
61
|
-
case "tool":
|
|
62
|
-
return "tool";
|
|
63
|
-
case "generic": {
|
|
64
|
-
if (!messages_1.ChatMessage.isInstance(message))
|
|
65
|
-
throw new Error("Invalid generic chat message");
|
|
66
|
-
return extractGenericMessageCustomRole(message);
|
|
67
|
-
}
|
|
68
|
-
default:
|
|
69
|
-
throw new Error(`Unknown message type: ${type}`);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
const completionsApiContentBlockConverter = {
|
|
73
|
-
providerName: "ChatOpenAI",
|
|
74
|
-
fromStandardTextBlock(block) {
|
|
75
|
-
return { type: "text", text: block.text };
|
|
76
|
-
},
|
|
77
|
-
fromStandardImageBlock(block) {
|
|
78
|
-
if (block.source_type === "url") {
|
|
79
|
-
return {
|
|
80
|
-
type: "image_url",
|
|
81
|
-
image_url: {
|
|
82
|
-
url: block.url,
|
|
83
|
-
...(block.metadata?.detail
|
|
84
|
-
? { detail: block.metadata.detail }
|
|
85
|
-
: {}),
|
|
86
|
-
},
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
if (block.source_type === "base64") {
|
|
90
|
-
const url = `data:${block.mime_type ?? ""};base64,${block.data}`;
|
|
91
|
-
return {
|
|
92
|
-
type: "image_url",
|
|
93
|
-
image_url: {
|
|
94
|
-
url,
|
|
95
|
-
...(block.metadata?.detail
|
|
96
|
-
? { detail: block.metadata.detail }
|
|
97
|
-
: {}),
|
|
98
|
-
},
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
throw new Error(`Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);
|
|
102
|
-
},
|
|
103
|
-
fromStandardAudioBlock(block) {
|
|
104
|
-
if (block.source_type === "url") {
|
|
105
|
-
const data = (0, messages_1.parseBase64DataUrl)({ dataUrl: block.url });
|
|
106
|
-
if (!data) {
|
|
107
|
-
throw new Error(`URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`);
|
|
108
|
-
}
|
|
109
|
-
const rawMimeType = data.mime_type || block.mime_type || "";
|
|
110
|
-
let mimeType;
|
|
111
|
-
try {
|
|
112
|
-
mimeType = (0, messages_1.parseMimeType)(rawMimeType);
|
|
113
|
-
}
|
|
114
|
-
catch {
|
|
115
|
-
throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);
|
|
116
|
-
}
|
|
117
|
-
if (mimeType.type !== "audio" ||
|
|
118
|
-
(mimeType.subtype !== "wav" && mimeType.subtype !== "mp3")) {
|
|
119
|
-
throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);
|
|
120
|
-
}
|
|
121
|
-
return {
|
|
122
|
-
type: "input_audio",
|
|
123
|
-
input_audio: {
|
|
124
|
-
format: mimeType.subtype,
|
|
125
|
-
data: data.data,
|
|
126
|
-
},
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
if (block.source_type === "base64") {
|
|
130
|
-
let mimeType;
|
|
131
|
-
try {
|
|
132
|
-
mimeType = (0, messages_1.parseMimeType)(block.mime_type ?? "");
|
|
133
|
-
}
|
|
134
|
-
catch {
|
|
135
|
-
throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);
|
|
136
|
-
}
|
|
137
|
-
if (mimeType.type !== "audio" ||
|
|
138
|
-
(mimeType.subtype !== "wav" && mimeType.subtype !== "mp3")) {
|
|
139
|
-
throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`);
|
|
140
|
-
}
|
|
141
|
-
return {
|
|
142
|
-
type: "input_audio",
|
|
143
|
-
input_audio: {
|
|
144
|
-
format: mimeType.subtype,
|
|
145
|
-
data: block.data,
|
|
146
|
-
},
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
throw new Error(`Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);
|
|
150
|
-
},
|
|
151
|
-
fromStandardFileBlock(block) {
|
|
152
|
-
if (block.source_type === "url") {
|
|
153
|
-
const data = (0, messages_1.parseBase64DataUrl)({ dataUrl: block.url });
|
|
154
|
-
if (!data) {
|
|
155
|
-
throw new Error(`URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`);
|
|
156
|
-
}
|
|
157
|
-
return {
|
|
158
|
-
type: "file",
|
|
159
|
-
file: {
|
|
160
|
-
file_data: block.url, // formatted as base64 data URL
|
|
161
|
-
...(block.metadata?.filename || block.metadata?.name
|
|
162
|
-
? {
|
|
163
|
-
filename: (block.metadata?.filename ||
|
|
164
|
-
block.metadata?.name),
|
|
165
|
-
}
|
|
166
|
-
: {}),
|
|
167
|
-
},
|
|
168
|
-
};
|
|
169
|
-
}
|
|
170
|
-
if (block.source_type === "base64") {
|
|
171
|
-
return {
|
|
172
|
-
type: "file",
|
|
173
|
-
file: {
|
|
174
|
-
file_data: `data:${block.mime_type ?? ""};base64,${block.data}`,
|
|
175
|
-
...(block.metadata?.filename ||
|
|
176
|
-
block.metadata?.name ||
|
|
177
|
-
block.metadata?.title
|
|
178
|
-
? {
|
|
179
|
-
filename: (block.metadata?.filename ||
|
|
180
|
-
block.metadata?.name ||
|
|
181
|
-
block.metadata?.title),
|
|
182
|
-
}
|
|
183
|
-
: {}),
|
|
184
|
-
},
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
if (block.source_type === "id") {
|
|
188
|
-
return {
|
|
189
|
-
type: "file",
|
|
190
|
-
file: {
|
|
191
|
-
file_id: block.id,
|
|
192
|
-
},
|
|
193
|
-
};
|
|
194
|
-
}
|
|
195
|
-
throw new Error(`File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`);
|
|
196
|
-
},
|
|
197
|
-
};
|
|
198
|
-
// Used in LangSmith, export is important here
|
|
199
|
-
// TODO: put this conversion elsewhere
|
|
200
|
-
function _convertMessagesToOpenAIParams(messages, model) {
|
|
201
|
-
// TODO: Function messages do not support array content, fix cast
|
|
202
|
-
return messages.flatMap((message) => {
|
|
203
|
-
let role = messageToOpenAIRole(message);
|
|
204
|
-
if (role === "system" && isReasoningModel(model)) {
|
|
205
|
-
role = "developer";
|
|
206
|
-
}
|
|
207
|
-
const content = typeof message.content === "string"
|
|
208
|
-
? message.content
|
|
209
|
-
: message.content.map((m) => {
|
|
210
|
-
if ((0, messages_1.isDataContentBlock)(m)) {
|
|
211
|
-
return (0, messages_1.convertToProviderContentBlock)(m, completionsApiContentBlockConverter);
|
|
212
|
-
}
|
|
213
|
-
return m;
|
|
214
|
-
});
|
|
215
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
216
|
-
const completionParam = {
|
|
217
|
-
role,
|
|
218
|
-
content,
|
|
219
|
-
};
|
|
220
|
-
if (message.name != null) {
|
|
221
|
-
completionParam.name = message.name;
|
|
222
|
-
}
|
|
223
|
-
if (message.additional_kwargs.function_call != null) {
|
|
224
|
-
completionParam.function_call = message.additional_kwargs.function_call;
|
|
225
|
-
completionParam.content = "";
|
|
226
|
-
}
|
|
227
|
-
if ((0, messages_1.isAIMessage)(message) && !!message.tool_calls?.length) {
|
|
228
|
-
completionParam.tool_calls = message.tool_calls.map(openai_tools_1.convertLangChainToolCallToOpenAI);
|
|
229
|
-
completionParam.content = "";
|
|
230
|
-
}
|
|
231
|
-
else {
|
|
232
|
-
if (message.additional_kwargs.tool_calls != null) {
|
|
233
|
-
completionParam.tool_calls = message.additional_kwargs.tool_calls;
|
|
234
|
-
}
|
|
235
|
-
if (message.tool_call_id != null) {
|
|
236
|
-
completionParam.tool_call_id = message.tool_call_id;
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
if (message.additional_kwargs.audio &&
|
|
240
|
-
typeof message.additional_kwargs.audio === "object" &&
|
|
241
|
-
"id" in message.additional_kwargs.audio) {
|
|
242
|
-
const audioMessage = {
|
|
243
|
-
role: "assistant",
|
|
244
|
-
audio: {
|
|
245
|
-
id: message.additional_kwargs.audio.id,
|
|
246
|
-
},
|
|
247
|
-
};
|
|
248
|
-
return [
|
|
249
|
-
completionParam,
|
|
250
|
-
audioMessage,
|
|
251
|
-
];
|
|
252
|
-
}
|
|
253
|
-
return completionParam;
|
|
254
|
-
});
|
|
255
|
-
}
|
|
256
23
|
/** @internal */
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
const nameCount = message.name !== undefined
|
|
764
|
-
? tokensPerName + (await this.getNumTokens(message.name))
|
|
765
|
-
: 0;
|
|
766
|
-
let count = textCount + tokensPerMessage + roleCount + nameCount;
|
|
767
|
-
// From: https://github.com/hmarr/openai-chat-tokens/blob/main/src/index.ts messageTokenEstimate
|
|
768
|
-
const openAIMessage = message;
|
|
769
|
-
if (openAIMessage._getType() === "function") {
|
|
770
|
-
count -= 2;
|
|
771
|
-
}
|
|
772
|
-
if (openAIMessage.additional_kwargs?.function_call) {
|
|
773
|
-
count += 3;
|
|
774
|
-
}
|
|
775
|
-
if (openAIMessage?.additional_kwargs.function_call?.name) {
|
|
776
|
-
count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name);
|
|
777
|
-
}
|
|
778
|
-
if (openAIMessage.additional_kwargs.function_call?.arguments) {
|
|
779
|
-
try {
|
|
780
|
-
count += await this.getNumTokens(
|
|
781
|
-
// Remove newlines and spaces
|
|
782
|
-
JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments)));
|
|
783
|
-
}
|
|
784
|
-
catch (error) {
|
|
785
|
-
console.error("Error parsing function arguments", error, JSON.stringify(openAIMessage.additional_kwargs.function_call));
|
|
786
|
-
count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments);
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
totalCount += count;
|
|
790
|
-
return count;
|
|
791
|
-
}));
|
|
792
|
-
totalCount += 3; // every reply is primed with <|start|>assistant<|message|>
|
|
793
|
-
return { totalCount, countPerMessage };
|
|
794
|
-
}
|
|
795
|
-
/** @internal */
|
|
796
|
-
async _getNumTokensFromGenerations(generations) {
|
|
797
|
-
const generationUsages = await Promise.all(generations.map(async (generation) => {
|
|
798
|
-
if (generation.message.additional_kwargs?.function_call) {
|
|
799
|
-
return (await this.getNumTokensFromMessages([generation.message]))
|
|
800
|
-
.countPerMessage[0];
|
|
801
|
-
}
|
|
802
|
-
else {
|
|
803
|
-
return await this.getNumTokens(generation.message.content);
|
|
804
|
-
}
|
|
805
|
-
}));
|
|
806
|
-
return generationUsages.reduce((a, b) => a + b, 0);
|
|
807
|
-
}
|
|
808
|
-
/** @internal */
|
|
809
|
-
async _getEstimatedTokenCountFromPrompt(messages, functions, function_call) {
|
|
810
|
-
// It appears that if functions are present, the first system message is padded with a trailing newline. This
|
|
811
|
-
// was inferred by trying lots of combinations of messages and functions and seeing what the token counts were.
|
|
812
|
-
let tokens = (await this.getNumTokensFromMessages(messages)).totalCount;
|
|
813
|
-
// If there are functions, add the function definitions as they count towards token usage
|
|
814
|
-
if (functions && function_call !== "auto") {
|
|
815
|
-
const promptDefinitions = (0, openai_format_fndef_js_1.formatFunctionDefinitions)(functions);
|
|
816
|
-
tokens += await this.getNumTokens(promptDefinitions);
|
|
817
|
-
tokens += 9; // Add nine per completion
|
|
818
|
-
}
|
|
819
|
-
// If there's a system message _and_ functions are present, subtract four tokens. I assume this is because
|
|
820
|
-
// functions typically add a system message, but reuse the first one if it's already there. This offsets
|
|
821
|
-
// the extra 9 tokens added by the function definitions.
|
|
822
|
-
if (functions && messages.find((m) => m._getType() === "system")) {
|
|
823
|
-
tokens -= 4;
|
|
824
|
-
}
|
|
825
|
-
// If function_call is 'none', add one token.
|
|
826
|
-
// If it's a FunctionCall object, add 4 + the number of tokens in the function name.
|
|
827
|
-
// If it's undefined or 'auto', don't add anything.
|
|
828
|
-
if (function_call === "none") {
|
|
829
|
-
tokens += 1;
|
|
830
|
-
}
|
|
831
|
-
else if (typeof function_call === "object") {
|
|
832
|
-
tokens += (await this.getNumTokens(function_call.name)) + 4;
|
|
833
|
-
}
|
|
834
|
-
return tokens;
|
|
835
|
-
}
|
|
836
|
-
/** @internal */
|
|
837
|
-
_getStructuredOutputMethod(config) {
|
|
838
|
-
const ensuredConfig = { ...config };
|
|
839
|
-
if (!this.model.startsWith("gpt-3") &&
|
|
840
|
-
!this.model.startsWith("gpt-4-") &&
|
|
841
|
-
this.model !== "gpt-4") {
|
|
842
|
-
if (ensuredConfig?.method === undefined) {
|
|
843
|
-
return "jsonSchema";
|
|
844
|
-
}
|
|
845
|
-
}
|
|
846
|
-
else if (ensuredConfig.method === "jsonSchema") {
|
|
847
|
-
console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);
|
|
848
|
-
}
|
|
849
|
-
return ensuredConfig.method;
|
|
850
|
-
}
|
|
851
|
-
withStructuredOutput(outputSchema, config) {
|
|
852
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
853
|
-
let schema;
|
|
854
|
-
let name;
|
|
855
|
-
let method;
|
|
856
|
-
let includeRaw;
|
|
857
|
-
if (isStructuredOutputMethodParams(outputSchema)) {
|
|
858
|
-
schema = outputSchema.schema;
|
|
859
|
-
name = outputSchema.name;
|
|
860
|
-
method = outputSchema.method;
|
|
861
|
-
includeRaw = outputSchema.includeRaw;
|
|
862
|
-
}
|
|
863
|
-
else {
|
|
864
|
-
schema = outputSchema;
|
|
865
|
-
name = config?.name;
|
|
866
|
-
method = config?.method;
|
|
867
|
-
includeRaw = config?.includeRaw;
|
|
868
|
-
}
|
|
869
|
-
let llm;
|
|
870
|
-
let outputParser;
|
|
871
|
-
if (config?.strict !== undefined && method === "jsonMode") {
|
|
872
|
-
throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");
|
|
873
|
-
}
|
|
874
|
-
method = this._getStructuredOutputMethod({ ...config, method });
|
|
875
|
-
if (method === "jsonMode") {
|
|
876
|
-
if ((0, types_1.isInteropZodSchema)(schema)) {
|
|
877
|
-
outputParser = output_parsers_1.StructuredOutputParser.fromZodSchema(schema);
|
|
878
|
-
}
|
|
879
|
-
else {
|
|
880
|
-
outputParser = new output_parsers_1.JsonOutputParser();
|
|
881
|
-
}
|
|
882
|
-
const asJsonSchema = (0, json_schema_1.toJsonSchema)(schema);
|
|
883
|
-
llm = this.withConfig({
|
|
884
|
-
response_format: { type: "json_object" },
|
|
885
|
-
ls_structured_output_format: {
|
|
886
|
-
kwargs: { method: "json_mode" },
|
|
887
|
-
schema: { title: name ?? "extract", ...asJsonSchema },
|
|
888
|
-
},
|
|
889
|
-
});
|
|
890
|
-
}
|
|
891
|
-
else if (method === "jsonSchema") {
|
|
892
|
-
const openaiJsonSchemaParams = {
|
|
893
|
-
name: name ?? "extract",
|
|
894
|
-
description: (0, types_1.getSchemaDescription)(schema),
|
|
895
|
-
schema,
|
|
896
|
-
strict: config?.strict,
|
|
897
|
-
};
|
|
898
|
-
const asJsonSchema = (0, json_schema_1.toJsonSchema)(openaiJsonSchemaParams.schema);
|
|
899
|
-
llm = this.withConfig({
|
|
900
|
-
response_format: {
|
|
901
|
-
type: "json_schema",
|
|
902
|
-
json_schema: openaiJsonSchemaParams,
|
|
903
|
-
},
|
|
904
|
-
ls_structured_output_format: {
|
|
905
|
-
kwargs: { method: "json_schema" },
|
|
906
|
-
schema: {
|
|
907
|
-
title: openaiJsonSchemaParams.name,
|
|
908
|
-
description: openaiJsonSchemaParams.description,
|
|
909
|
-
...asJsonSchema,
|
|
910
|
-
},
|
|
911
|
-
},
|
|
912
|
-
});
|
|
913
|
-
if ((0, types_1.isInteropZodSchema)(schema)) {
|
|
914
|
-
const altParser = output_parsers_1.StructuredOutputParser.fromZodSchema(schema);
|
|
915
|
-
outputParser = runnables_1.RunnableLambda.from((aiMessage) => {
|
|
916
|
-
if ("parsed" in aiMessage.additional_kwargs) {
|
|
917
|
-
return aiMessage.additional_kwargs.parsed;
|
|
918
|
-
}
|
|
919
|
-
return altParser;
|
|
920
|
-
});
|
|
921
|
-
}
|
|
922
|
-
else {
|
|
923
|
-
outputParser = new output_parsers_1.JsonOutputParser();
|
|
924
|
-
}
|
|
925
|
-
}
|
|
926
|
-
else {
|
|
927
|
-
let functionName = name ?? "extract";
|
|
928
|
-
// Is function calling
|
|
929
|
-
if ((0, types_1.isInteropZodSchema)(schema)) {
|
|
930
|
-
const asJsonSchema = (0, json_schema_1.toJsonSchema)(schema);
|
|
931
|
-
llm = this.withConfig({
|
|
932
|
-
tools: [
|
|
933
|
-
{
|
|
934
|
-
type: "function",
|
|
935
|
-
function: {
|
|
936
|
-
name: functionName,
|
|
937
|
-
description: asJsonSchema.description,
|
|
938
|
-
parameters: asJsonSchema,
|
|
939
|
-
},
|
|
940
|
-
},
|
|
941
|
-
],
|
|
942
|
-
tool_choice: {
|
|
943
|
-
type: "function",
|
|
944
|
-
function: {
|
|
945
|
-
name: functionName,
|
|
946
|
-
},
|
|
947
|
-
},
|
|
948
|
-
ls_structured_output_format: {
|
|
949
|
-
kwargs: { method: "function_calling" },
|
|
950
|
-
schema: { title: functionName, ...asJsonSchema },
|
|
951
|
-
},
|
|
952
|
-
// Do not pass `strict` argument to OpenAI if `config.strict` is undefined
|
|
953
|
-
...(config?.strict !== undefined ? { strict: config.strict } : {}),
|
|
954
|
-
});
|
|
955
|
-
outputParser = new openai_tools_1.JsonOutputKeyToolsParser({
|
|
956
|
-
returnSingle: true,
|
|
957
|
-
keyName: functionName,
|
|
958
|
-
zodSchema: schema,
|
|
959
|
-
});
|
|
960
|
-
}
|
|
961
|
-
else {
|
|
962
|
-
let openAIFunctionDefinition;
|
|
963
|
-
if (typeof schema.name === "string" &&
|
|
964
|
-
typeof schema.parameters === "object" &&
|
|
965
|
-
schema.parameters != null) {
|
|
966
|
-
openAIFunctionDefinition = schema;
|
|
967
|
-
functionName = schema.name;
|
|
968
|
-
}
|
|
969
|
-
else {
|
|
970
|
-
functionName = schema.title ?? functionName;
|
|
971
|
-
openAIFunctionDefinition = {
|
|
972
|
-
name: functionName,
|
|
973
|
-
description: schema.description ?? "",
|
|
974
|
-
parameters: schema,
|
|
975
|
-
};
|
|
976
|
-
}
|
|
977
|
-
const asJsonSchema = (0, json_schema_1.toJsonSchema)(schema);
|
|
978
|
-
llm = this.withConfig({
|
|
979
|
-
tools: [
|
|
980
|
-
{
|
|
981
|
-
type: "function",
|
|
982
|
-
function: openAIFunctionDefinition,
|
|
983
|
-
},
|
|
984
|
-
],
|
|
985
|
-
tool_choice: {
|
|
986
|
-
type: "function",
|
|
987
|
-
function: {
|
|
988
|
-
name: functionName,
|
|
989
|
-
},
|
|
990
|
-
},
|
|
991
|
-
ls_structured_output_format: {
|
|
992
|
-
kwargs: { method: "function_calling" },
|
|
993
|
-
schema: { title: functionName, ...asJsonSchema },
|
|
994
|
-
},
|
|
995
|
-
// Do not pass `strict` argument to OpenAI if `config.strict` is undefined
|
|
996
|
-
...(config?.strict !== undefined ? { strict: config.strict } : {}),
|
|
997
|
-
});
|
|
998
|
-
outputParser = new openai_tools_1.JsonOutputKeyToolsParser({
|
|
999
|
-
returnSingle: true,
|
|
1000
|
-
keyName: functionName,
|
|
1001
|
-
});
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
if (!includeRaw) {
|
|
1005
|
-
return llm.pipe(outputParser);
|
|
1006
|
-
}
|
|
1007
|
-
const parserAssign = runnables_1.RunnablePassthrough.assign({
|
|
1008
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1009
|
-
parsed: (input, config) => outputParser.invoke(input.raw, config),
|
|
1010
|
-
});
|
|
1011
|
-
const parserNone = runnables_1.RunnablePassthrough.assign({
|
|
1012
|
-
parsed: () => null,
|
|
1013
|
-
});
|
|
1014
|
-
const parsedWithFallback = parserAssign.withFallbacks({
|
|
1015
|
-
fallbacks: [parserNone],
|
|
1016
|
-
});
|
|
1017
|
-
return runnables_1.RunnableSequence.from([{ raw: llm }, parsedWithFallback]);
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
exports.BaseChatOpenAI = BaseChatOpenAI;
|
|
24
|
+
var BaseChatOpenAI = class extends __langchain_core_language_models_chat_models.BaseChatModel {
|
|
25
|
+
temperature;
|
|
26
|
+
topP;
|
|
27
|
+
frequencyPenalty;
|
|
28
|
+
presencePenalty;
|
|
29
|
+
n;
|
|
30
|
+
logitBias;
|
|
31
|
+
model = "gpt-3.5-turbo";
|
|
32
|
+
modelKwargs;
|
|
33
|
+
stop;
|
|
34
|
+
stopSequences;
|
|
35
|
+
user;
|
|
36
|
+
timeout;
|
|
37
|
+
streaming = false;
|
|
38
|
+
streamUsage = true;
|
|
39
|
+
maxTokens;
|
|
40
|
+
logprobs;
|
|
41
|
+
topLogprobs;
|
|
42
|
+
apiKey;
|
|
43
|
+
organization;
|
|
44
|
+
__includeRawResponse;
|
|
45
|
+
/** @internal */
|
|
46
|
+
client;
|
|
47
|
+
/** @internal */
|
|
48
|
+
clientConfig;
|
|
49
|
+
/**
|
|
50
|
+
* Whether the model supports the `strict` argument when passing in tools.
|
|
51
|
+
* If `undefined` the `strict` argument will not be passed to OpenAI.
|
|
52
|
+
*/
|
|
53
|
+
supportsStrictToolCalling;
|
|
54
|
+
audio;
|
|
55
|
+
modalities;
|
|
56
|
+
reasoning;
|
|
57
|
+
/**
|
|
58
|
+
* Must be set to `true` in tenancies with Zero Data Retention. Setting to `true` will disable
|
|
59
|
+
* output storage in the Responses API, but this DOES NOT enable Zero Data Retention in your
|
|
60
|
+
* OpenAI organization or project. This must be configured directly with OpenAI.
|
|
61
|
+
*
|
|
62
|
+
* See:
|
|
63
|
+
* https://help.openai.com/en/articles/10503543-data-residency-for-the-openai-api
|
|
64
|
+
* https://platform.openai.com/docs/api-reference/responses/create#responses-create-store
|
|
65
|
+
*
|
|
66
|
+
* @default false
|
|
67
|
+
*/
|
|
68
|
+
zdrEnabled;
|
|
69
|
+
/**
|
|
70
|
+
* Service tier to use for this request. Can be "auto", "default", or "flex" or "priority".
|
|
71
|
+
* Specifies the service tier for prioritization and latency optimization.
|
|
72
|
+
*/
|
|
73
|
+
service_tier;
|
|
74
|
+
/**
|
|
75
|
+
* Used by OpenAI to cache responses for similar requests to optimize your cache
|
|
76
|
+
* hit rates.
|
|
77
|
+
* [Learn more](https://platform.openai.com/docs/guides/prompt-caching).
|
|
78
|
+
*/
|
|
79
|
+
promptCacheKey;
|
|
80
|
+
/**
|
|
81
|
+
* The verbosity of the model's response.
|
|
82
|
+
*/
|
|
83
|
+
verbosity;
|
|
84
|
+
defaultOptions;
|
|
85
|
+
_llmType() {
|
|
86
|
+
return "openai";
|
|
87
|
+
}
|
|
88
|
+
static lc_name() {
|
|
89
|
+
return "ChatOpenAI";
|
|
90
|
+
}
|
|
91
|
+
get callKeys() {
|
|
92
|
+
return [
|
|
93
|
+
...super.callKeys,
|
|
94
|
+
"options",
|
|
95
|
+
"function_call",
|
|
96
|
+
"functions",
|
|
97
|
+
"tools",
|
|
98
|
+
"tool_choice",
|
|
99
|
+
"promptIndex",
|
|
100
|
+
"response_format",
|
|
101
|
+
"seed",
|
|
102
|
+
"reasoning",
|
|
103
|
+
"service_tier"
|
|
104
|
+
];
|
|
105
|
+
}
|
|
106
|
+
lc_serializable = true;
|
|
107
|
+
get lc_secrets() {
|
|
108
|
+
return {
|
|
109
|
+
apiKey: "OPENAI_API_KEY",
|
|
110
|
+
organization: "OPENAI_ORGANIZATION"
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
get lc_aliases() {
|
|
114
|
+
return {
|
|
115
|
+
apiKey: "openai_api_key",
|
|
116
|
+
modelName: "model"
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
get lc_serializable_keys() {
|
|
120
|
+
return [
|
|
121
|
+
"configuration",
|
|
122
|
+
"logprobs",
|
|
123
|
+
"topLogprobs",
|
|
124
|
+
"prefixMessages",
|
|
125
|
+
"supportsStrictToolCalling",
|
|
126
|
+
"modalities",
|
|
127
|
+
"audio",
|
|
128
|
+
"temperature",
|
|
129
|
+
"maxTokens",
|
|
130
|
+
"topP",
|
|
131
|
+
"frequencyPenalty",
|
|
132
|
+
"presencePenalty",
|
|
133
|
+
"n",
|
|
134
|
+
"logitBias",
|
|
135
|
+
"user",
|
|
136
|
+
"streaming",
|
|
137
|
+
"streamUsage",
|
|
138
|
+
"model",
|
|
139
|
+
"modelName",
|
|
140
|
+
"modelKwargs",
|
|
141
|
+
"stop",
|
|
142
|
+
"stopSequences",
|
|
143
|
+
"timeout",
|
|
144
|
+
"apiKey",
|
|
145
|
+
"cache",
|
|
146
|
+
"maxConcurrency",
|
|
147
|
+
"maxRetries",
|
|
148
|
+
"verbose",
|
|
149
|
+
"callbacks",
|
|
150
|
+
"tags",
|
|
151
|
+
"metadata",
|
|
152
|
+
"disableStreaming",
|
|
153
|
+
"zdrEnabled",
|
|
154
|
+
"reasoning",
|
|
155
|
+
"promptCacheKey",
|
|
156
|
+
"verbosity"
|
|
157
|
+
];
|
|
158
|
+
}
|
|
159
|
+
getLsParams(options) {
|
|
160
|
+
const params = this.invocationParams(options);
|
|
161
|
+
return {
|
|
162
|
+
ls_provider: "openai",
|
|
163
|
+
ls_model_name: this.model,
|
|
164
|
+
ls_model_type: "chat",
|
|
165
|
+
ls_temperature: params.temperature ?? void 0,
|
|
166
|
+
ls_max_tokens: params.max_tokens ?? void 0,
|
|
167
|
+
ls_stop: options.stop
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/** @ignore */
|
|
171
|
+
_identifyingParams() {
|
|
172
|
+
return {
|
|
173
|
+
model_name: this.model,
|
|
174
|
+
...this.invocationParams(),
|
|
175
|
+
...this.clientConfig
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Get the identifying parameters for the model
|
|
180
|
+
*/
|
|
181
|
+
identifyingParams() {
|
|
182
|
+
return this._identifyingParams();
|
|
183
|
+
}
|
|
184
|
+
constructor(fields) {
|
|
185
|
+
super(fields ?? {});
|
|
186
|
+
this.apiKey = fields?.apiKey ?? fields?.configuration?.apiKey ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("OPENAI_API_KEY");
|
|
187
|
+
this.organization = fields?.configuration?.organization ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("OPENAI_ORGANIZATION");
|
|
188
|
+
this.model = fields?.model ?? fields?.modelName ?? this.model;
|
|
189
|
+
this.modelKwargs = fields?.modelKwargs ?? {};
|
|
190
|
+
this.timeout = fields?.timeout;
|
|
191
|
+
this.temperature = fields?.temperature ?? this.temperature;
|
|
192
|
+
this.topP = fields?.topP ?? this.topP;
|
|
193
|
+
this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;
|
|
194
|
+
this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;
|
|
195
|
+
this.logprobs = fields?.logprobs;
|
|
196
|
+
this.topLogprobs = fields?.topLogprobs;
|
|
197
|
+
this.n = fields?.n ?? this.n;
|
|
198
|
+
this.logitBias = fields?.logitBias;
|
|
199
|
+
this.stop = fields?.stopSequences ?? fields?.stop;
|
|
200
|
+
this.stopSequences = this.stop;
|
|
201
|
+
this.user = fields?.user;
|
|
202
|
+
this.__includeRawResponse = fields?.__includeRawResponse;
|
|
203
|
+
this.audio = fields?.audio;
|
|
204
|
+
this.modalities = fields?.modalities;
|
|
205
|
+
this.reasoning = fields?.reasoning;
|
|
206
|
+
this.maxTokens = fields?.maxCompletionTokens ?? fields?.maxTokens;
|
|
207
|
+
this.disableStreaming = fields?.disableStreaming ?? this.disableStreaming;
|
|
208
|
+
this.promptCacheKey = fields?.promptCacheKey ?? this.promptCacheKey;
|
|
209
|
+
this.verbosity = fields?.verbosity ?? this.verbosity;
|
|
210
|
+
this.streaming = fields?.streaming ?? false;
|
|
211
|
+
if (this.disableStreaming) this.streaming = false;
|
|
212
|
+
this.streamUsage = fields?.streamUsage ?? this.streamUsage;
|
|
213
|
+
if (this.disableStreaming) this.streamUsage = false;
|
|
214
|
+
this.clientConfig = {
|
|
215
|
+
apiKey: this.apiKey,
|
|
216
|
+
organization: this.organization,
|
|
217
|
+
dangerouslyAllowBrowser: true,
|
|
218
|
+
...fields?.configuration
|
|
219
|
+
};
|
|
220
|
+
if (fields?.supportsStrictToolCalling !== void 0) this.supportsStrictToolCalling = fields.supportsStrictToolCalling;
|
|
221
|
+
if (fields?.service_tier !== void 0) this.service_tier = fields.service_tier;
|
|
222
|
+
this.zdrEnabled = fields?.zdrEnabled ?? false;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Returns backwards compatible reasoning parameters from constructor params and call options
|
|
226
|
+
* @internal
|
|
227
|
+
*/
|
|
228
|
+
_getReasoningParams(options) {
|
|
229
|
+
if (!require_misc.isReasoningModel(this.model)) return;
|
|
230
|
+
let reasoning;
|
|
231
|
+
if (this.reasoning !== void 0) reasoning = {
|
|
232
|
+
...reasoning,
|
|
233
|
+
...this.reasoning
|
|
234
|
+
};
|
|
235
|
+
if (options?.reasoning !== void 0) reasoning = {
|
|
236
|
+
...reasoning,
|
|
237
|
+
...options.reasoning
|
|
238
|
+
};
|
|
239
|
+
return reasoning;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Returns an openai compatible response format from a set of options
|
|
243
|
+
* @internal
|
|
244
|
+
*/
|
|
245
|
+
_getResponseFormat(resFormat) {
|
|
246
|
+
if (resFormat && resFormat.type === "json_schema" && resFormat.json_schema.schema && (0, __langchain_core_utils_types.isInteropZodSchema)(resFormat.json_schema.schema)) return require_output.interopZodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, { description: resFormat.json_schema.description });
|
|
247
|
+
return resFormat;
|
|
248
|
+
}
|
|
249
|
+
_combineCallOptions(additionalOptions) {
|
|
250
|
+
return {
|
|
251
|
+
...this.defaultOptions,
|
|
252
|
+
...additionalOptions ?? {}
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
/** @internal */
|
|
256
|
+
_getClientOptions(options) {
|
|
257
|
+
if (!this.client) {
|
|
258
|
+
const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL };
|
|
259
|
+
const endpoint = require_azure.getEndpoint(openAIEndpointConfig);
|
|
260
|
+
const params = {
|
|
261
|
+
...this.clientConfig,
|
|
262
|
+
baseURL: endpoint,
|
|
263
|
+
timeout: this.timeout,
|
|
264
|
+
maxRetries: 0
|
|
265
|
+
};
|
|
266
|
+
if (!params.baseURL) delete params.baseURL;
|
|
267
|
+
this.client = new openai.OpenAI(params);
|
|
268
|
+
}
|
|
269
|
+
const requestOptions = {
|
|
270
|
+
...this.clientConfig,
|
|
271
|
+
...options
|
|
272
|
+
};
|
|
273
|
+
return requestOptions;
|
|
274
|
+
}
|
|
275
|
+
_convertChatOpenAIToolToCompletionsTool(tool, fields) {
|
|
276
|
+
if (require_tools.isCustomTool(tool)) return require_tools.convertResponsesCustomTool(tool.metadata.customTool);
|
|
277
|
+
if ((0, __langchain_core_language_models_base.isOpenAITool)(tool)) {
|
|
278
|
+
if (fields?.strict !== void 0) return {
|
|
279
|
+
...tool,
|
|
280
|
+
function: {
|
|
281
|
+
...tool.function,
|
|
282
|
+
strict: fields.strict
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
return tool;
|
|
286
|
+
}
|
|
287
|
+
return require_tools._convertToOpenAITool(tool, fields);
|
|
288
|
+
}
|
|
289
|
+
bindTools(tools, kwargs) {
|
|
290
|
+
let strict;
|
|
291
|
+
if (kwargs?.strict !== void 0) strict = kwargs.strict;
|
|
292
|
+
else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;
|
|
293
|
+
return this.withConfig({
|
|
294
|
+
tools: tools.map((tool) => require_tools.isBuiltInTool(tool) ? tool : this._convertChatOpenAIToolToCompletionsTool(tool, { strict })),
|
|
295
|
+
...kwargs
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
async stream(input, options) {
|
|
299
|
+
return super.stream(input, this._combineCallOptions(options));
|
|
300
|
+
}
|
|
301
|
+
async invoke(input, options) {
|
|
302
|
+
return super.invoke(input, this._combineCallOptions(options));
|
|
303
|
+
}
|
|
304
|
+
/** @ignore */
|
|
305
|
+
_combineLLMOutput(...llmOutputs) {
|
|
306
|
+
return llmOutputs.reduce((acc, llmOutput) => {
|
|
307
|
+
if (llmOutput && llmOutput.tokenUsage) {
|
|
308
|
+
acc.tokenUsage.completionTokens += llmOutput.tokenUsage.completionTokens ?? 0;
|
|
309
|
+
acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0;
|
|
310
|
+
acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0;
|
|
311
|
+
}
|
|
312
|
+
return acc;
|
|
313
|
+
}, { tokenUsage: {
|
|
314
|
+
completionTokens: 0,
|
|
315
|
+
promptTokens: 0,
|
|
316
|
+
totalTokens: 0
|
|
317
|
+
} });
|
|
318
|
+
}
|
|
319
|
+
async getNumTokensFromMessages(messages) {
|
|
320
|
+
let totalCount = 0;
|
|
321
|
+
let tokensPerMessage = 0;
|
|
322
|
+
let tokensPerName = 0;
|
|
323
|
+
if (this.model === "gpt-3.5-turbo-0301") {
|
|
324
|
+
tokensPerMessage = 4;
|
|
325
|
+
tokensPerName = -1;
|
|
326
|
+
} else {
|
|
327
|
+
tokensPerMessage = 3;
|
|
328
|
+
tokensPerName = 1;
|
|
329
|
+
}
|
|
330
|
+
const countPerMessage = await Promise.all(messages.map(async (message) => {
|
|
331
|
+
const textCount = await this.getNumTokens(message.content);
|
|
332
|
+
const roleCount = await this.getNumTokens(require_misc.messageToOpenAIRole(message));
|
|
333
|
+
const nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0;
|
|
334
|
+
let count = textCount + tokensPerMessage + roleCount + nameCount;
|
|
335
|
+
const openAIMessage = message;
|
|
336
|
+
if (openAIMessage._getType() === "function") count -= 2;
|
|
337
|
+
if (openAIMessage.additional_kwargs?.function_call) count += 3;
|
|
338
|
+
if (openAIMessage?.additional_kwargs.function_call?.name) count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name);
|
|
339
|
+
if (openAIMessage.additional_kwargs.function_call?.arguments) try {
|
|
340
|
+
count += await this.getNumTokens(JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments)));
|
|
341
|
+
} catch (error) {
|
|
342
|
+
console.error("Error parsing function arguments", error, JSON.stringify(openAIMessage.additional_kwargs.function_call));
|
|
343
|
+
count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments);
|
|
344
|
+
}
|
|
345
|
+
totalCount += count;
|
|
346
|
+
return count;
|
|
347
|
+
}));
|
|
348
|
+
totalCount += 3;
|
|
349
|
+
return {
|
|
350
|
+
totalCount,
|
|
351
|
+
countPerMessage
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
/** @internal */
|
|
355
|
+
async _getNumTokensFromGenerations(generations) {
|
|
356
|
+
const generationUsages = await Promise.all(generations.map(async (generation) => {
|
|
357
|
+
if (generation.message.additional_kwargs?.function_call) return (await this.getNumTokensFromMessages([generation.message])).countPerMessage[0];
|
|
358
|
+
else return await this.getNumTokens(generation.message.content);
|
|
359
|
+
}));
|
|
360
|
+
return generationUsages.reduce((a, b) => a + b, 0);
|
|
361
|
+
}
|
|
362
|
+
/** @internal */
|
|
363
|
+
async _getEstimatedTokenCountFromPrompt(messages, functions, function_call) {
|
|
364
|
+
let tokens = (await this.getNumTokensFromMessages(messages)).totalCount;
|
|
365
|
+
if (functions && function_call !== "auto") {
|
|
366
|
+
const promptDefinitions = require_tools.formatFunctionDefinitions(functions);
|
|
367
|
+
tokens += await this.getNumTokens(promptDefinitions);
|
|
368
|
+
tokens += 9;
|
|
369
|
+
}
|
|
370
|
+
if (functions && messages.find((m) => m._getType() === "system")) tokens -= 4;
|
|
371
|
+
if (function_call === "none") tokens += 1;
|
|
372
|
+
else if (typeof function_call === "object") tokens += await this.getNumTokens(function_call.name) + 4;
|
|
373
|
+
return tokens;
|
|
374
|
+
}
|
|
375
|
+
/** @internal */
|
|
376
|
+
_getStructuredOutputMethod(config) {
|
|
377
|
+
const ensuredConfig = { ...config };
|
|
378
|
+
if (!this.model.startsWith("gpt-3") && !this.model.startsWith("gpt-4-") && this.model !== "gpt-4") {
|
|
379
|
+
if (ensuredConfig?.method === void 0) return "jsonSchema";
|
|
380
|
+
} else if (ensuredConfig.method === "jsonSchema") console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);
|
|
381
|
+
return ensuredConfig.method;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Add structured output to the model.
|
|
385
|
+
*
|
|
386
|
+
* The OpenAI model family supports the following structured output methods:
|
|
387
|
+
* - `jsonSchema`: Use the `response_format` field in the response to return a JSON schema. Only supported with the `gpt-4o-mini`,
|
|
388
|
+
* `gpt-4o-mini-2024-07-18`, and `gpt-4o-2024-08-06` model snapshots and later.
|
|
389
|
+
* - `functionCalling`: Function calling is useful when you are building an application that bridges the models and functionality
|
|
390
|
+
* of your application.
|
|
391
|
+
* - `jsonMode`: JSON mode is a more basic version of the Structured Outputs feature. While JSON mode ensures that model
|
|
392
|
+
* output is valid JSON, Structured Outputs reliably matches the model's output to the schema you specify.
|
|
393
|
+
* We recommend you use `functionCalling` or `jsonSchema` if it is supported for your use case.
|
|
394
|
+
*
|
|
395
|
+
* The default method is `functionCalling`.
|
|
396
|
+
*
|
|
397
|
+
* @see https://platform.openai.com/docs/guides/structured-outputs
|
|
398
|
+
* @param outputSchema - The schema to use for structured output.
|
|
399
|
+
* @param config - The structured output method options.
|
|
400
|
+
* @returns The model with structured output.
|
|
401
|
+
*/
|
|
402
|
+
withStructuredOutput(outputSchema, config) {
|
|
403
|
+
let llm;
|
|
404
|
+
let outputParser;
|
|
405
|
+
const { schema, name, includeRaw } = {
|
|
406
|
+
...config,
|
|
407
|
+
schema: outputSchema
|
|
408
|
+
};
|
|
409
|
+
if (config?.strict !== void 0 && config.method === "jsonMode") throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");
|
|
410
|
+
const method = require_output.getStructuredOutputMethod(this.model, config?.method);
|
|
411
|
+
if (method === "jsonMode") {
|
|
412
|
+
if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) outputParser = __langchain_core_output_parsers.StructuredOutputParser.fromZodSchema(schema);
|
|
413
|
+
else outputParser = new __langchain_core_output_parsers.JsonOutputParser();
|
|
414
|
+
const asJsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(schema);
|
|
415
|
+
llm = this.withConfig({
|
|
416
|
+
response_format: { type: "json_object" },
|
|
417
|
+
ls_structured_output_format: {
|
|
418
|
+
kwargs: { method: "json_mode" },
|
|
419
|
+
schema: {
|
|
420
|
+
title: name ?? "extract",
|
|
421
|
+
...asJsonSchema
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
});
|
|
425
|
+
} else if (method === "jsonSchema") {
|
|
426
|
+
const openaiJsonSchemaParams = {
|
|
427
|
+
name: name ?? "extract",
|
|
428
|
+
description: (0, __langchain_core_utils_types.getSchemaDescription)(schema),
|
|
429
|
+
schema,
|
|
430
|
+
strict: config?.strict
|
|
431
|
+
};
|
|
432
|
+
const asJsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(openaiJsonSchemaParams.schema);
|
|
433
|
+
llm = this.withConfig({
|
|
434
|
+
response_format: {
|
|
435
|
+
type: "json_schema",
|
|
436
|
+
json_schema: openaiJsonSchemaParams
|
|
437
|
+
},
|
|
438
|
+
ls_structured_output_format: {
|
|
439
|
+
kwargs: { method: "json_schema" },
|
|
440
|
+
schema: {
|
|
441
|
+
title: openaiJsonSchemaParams.name,
|
|
442
|
+
description: openaiJsonSchemaParams.description,
|
|
443
|
+
...asJsonSchema
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
});
|
|
447
|
+
if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) {
|
|
448
|
+
const altParser = __langchain_core_output_parsers.StructuredOutputParser.fromZodSchema(schema);
|
|
449
|
+
outputParser = __langchain_core_runnables.RunnableLambda.from((aiMessage) => {
|
|
450
|
+
if ("parsed" in aiMessage.additional_kwargs) return aiMessage.additional_kwargs.parsed;
|
|
451
|
+
return altParser;
|
|
452
|
+
});
|
|
453
|
+
} else outputParser = new __langchain_core_output_parsers.JsonOutputParser();
|
|
454
|
+
} else {
|
|
455
|
+
let functionName = name ?? "extract";
|
|
456
|
+
if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) {
|
|
457
|
+
const asJsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(schema);
|
|
458
|
+
llm = this.withConfig({
|
|
459
|
+
tools: [{
|
|
460
|
+
type: "function",
|
|
461
|
+
function: {
|
|
462
|
+
name: functionName,
|
|
463
|
+
description: asJsonSchema.description,
|
|
464
|
+
parameters: asJsonSchema
|
|
465
|
+
}
|
|
466
|
+
}],
|
|
467
|
+
tool_choice: {
|
|
468
|
+
type: "function",
|
|
469
|
+
function: { name: functionName }
|
|
470
|
+
},
|
|
471
|
+
ls_structured_output_format: {
|
|
472
|
+
kwargs: { method: "function_calling" },
|
|
473
|
+
schema: {
|
|
474
|
+
title: functionName,
|
|
475
|
+
...asJsonSchema
|
|
476
|
+
}
|
|
477
|
+
},
|
|
478
|
+
...config?.strict !== void 0 ? { strict: config.strict } : {}
|
|
479
|
+
});
|
|
480
|
+
outputParser = new __langchain_core_output_parsers_openai_tools.JsonOutputKeyToolsParser({
|
|
481
|
+
returnSingle: true,
|
|
482
|
+
keyName: functionName,
|
|
483
|
+
zodSchema: schema
|
|
484
|
+
});
|
|
485
|
+
} else {
|
|
486
|
+
let openAIFunctionDefinition;
|
|
487
|
+
if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) {
|
|
488
|
+
openAIFunctionDefinition = schema;
|
|
489
|
+
functionName = schema.name;
|
|
490
|
+
} else {
|
|
491
|
+
functionName = schema.title ?? functionName;
|
|
492
|
+
openAIFunctionDefinition = {
|
|
493
|
+
name: functionName,
|
|
494
|
+
description: schema.description ?? "",
|
|
495
|
+
parameters: schema
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
const asJsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(schema);
|
|
499
|
+
llm = this.withConfig({
|
|
500
|
+
tools: [{
|
|
501
|
+
type: "function",
|
|
502
|
+
function: openAIFunctionDefinition
|
|
503
|
+
}],
|
|
504
|
+
tool_choice: {
|
|
505
|
+
type: "function",
|
|
506
|
+
function: { name: functionName }
|
|
507
|
+
},
|
|
508
|
+
ls_structured_output_format: {
|
|
509
|
+
kwargs: { method: "function_calling" },
|
|
510
|
+
schema: {
|
|
511
|
+
title: functionName,
|
|
512
|
+
...asJsonSchema
|
|
513
|
+
}
|
|
514
|
+
},
|
|
515
|
+
...config?.strict !== void 0 ? { strict: config.strict } : {}
|
|
516
|
+
});
|
|
517
|
+
outputParser = new __langchain_core_output_parsers_openai_tools.JsonOutputKeyToolsParser({
|
|
518
|
+
returnSingle: true,
|
|
519
|
+
keyName: functionName
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (!includeRaw) return llm.pipe(outputParser);
|
|
524
|
+
const parserAssign = __langchain_core_runnables.RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });
|
|
525
|
+
const parserNone = __langchain_core_runnables.RunnablePassthrough.assign({ parsed: () => null });
|
|
526
|
+
const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });
|
|
527
|
+
return __langchain_core_runnables.RunnableSequence.from([{ raw: llm }, parsedWithFallback]);
|
|
528
|
+
}
|
|
529
|
+
};
|
|
1021
530
|
/**
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
text: item.text,
|
|
1539
|
-
// @ts-expect-error TODO: add types for `annotations`
|
|
1540
|
-
annotations: item.annotations ?? [],
|
|
1541
|
-
};
|
|
1542
|
-
}
|
|
1543
|
-
if (item.type === "output_text" ||
|
|
1544
|
-
item.type === "refusal") {
|
|
1545
|
-
return item;
|
|
1546
|
-
}
|
|
1547
|
-
return [];
|
|
1548
|
-
}),
|
|
1549
|
-
});
|
|
1550
|
-
}
|
|
1551
|
-
const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];
|
|
1552
|
-
if ((0, messages_1.isAIMessage)(lcMsg) && !!lcMsg.tool_calls?.length) {
|
|
1553
|
-
input.push(...lcMsg.tool_calls.map((toolCall) => {
|
|
1554
|
-
if ((0, tools_js_1.isCustomToolCall)(toolCall)) {
|
|
1555
|
-
return {
|
|
1556
|
-
type: "custom_tool_call",
|
|
1557
|
-
id: toolCall.call_id,
|
|
1558
|
-
call_id: toolCall.id ?? "",
|
|
1559
|
-
input: toolCall.args.input,
|
|
1560
|
-
name: toolCall.name,
|
|
1561
|
-
};
|
|
1562
|
-
}
|
|
1563
|
-
return {
|
|
1564
|
-
type: "function_call",
|
|
1565
|
-
name: toolCall.name,
|
|
1566
|
-
arguments: JSON.stringify(toolCall.args),
|
|
1567
|
-
call_id: toolCall.id,
|
|
1568
|
-
...(this.zdrEnabled
|
|
1569
|
-
? { id: functionCallIds?.[toolCall.id] }
|
|
1570
|
-
: {}),
|
|
1571
|
-
};
|
|
1572
|
-
}));
|
|
1573
|
-
}
|
|
1574
|
-
else if (additional_kwargs?.tool_calls) {
|
|
1575
|
-
input.push(...additional_kwargs.tool_calls.map((toolCall) => ({
|
|
1576
|
-
type: "function_call",
|
|
1577
|
-
name: toolCall.function.name,
|
|
1578
|
-
call_id: toolCall.id,
|
|
1579
|
-
arguments: toolCall.function.arguments,
|
|
1580
|
-
...(this.zdrEnabled
|
|
1581
|
-
? { id: functionCallIds?.[toolCall.id] }
|
|
1582
|
-
: {}),
|
|
1583
|
-
})));
|
|
1584
|
-
}
|
|
1585
|
-
const toolOutputs = lcMsg.response_metadata.output?.length
|
|
1586
|
-
? lcMsg.response_metadata.output
|
|
1587
|
-
: additional_kwargs.tool_outputs;
|
|
1588
|
-
const fallthroughCallTypes = [
|
|
1589
|
-
"computer_call",
|
|
1590
|
-
"mcp_call",
|
|
1591
|
-
"code_interpreter_call",
|
|
1592
|
-
"image_generation_call",
|
|
1593
|
-
];
|
|
1594
|
-
if (toolOutputs != null) {
|
|
1595
|
-
const castToolOutputs = toolOutputs;
|
|
1596
|
-
const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type));
|
|
1597
|
-
if (fallthroughCalls.length > 0)
|
|
1598
|
-
input.push(...fallthroughCalls);
|
|
1599
|
-
}
|
|
1600
|
-
return input;
|
|
1601
|
-
}
|
|
1602
|
-
if (role === "user" || role === "system" || role === "developer") {
|
|
1603
|
-
if (typeof lcMsg.content === "string") {
|
|
1604
|
-
return { type: "message", role, content: lcMsg.content };
|
|
1605
|
-
}
|
|
1606
|
-
const messages = [];
|
|
1607
|
-
const content = lcMsg.content.flatMap((item) => {
|
|
1608
|
-
if (item.type === "mcp_approval_response") {
|
|
1609
|
-
messages.push({
|
|
1610
|
-
type: "mcp_approval_response",
|
|
1611
|
-
approval_request_id: item.approval_request_id,
|
|
1612
|
-
approve: item.approve,
|
|
1613
|
-
});
|
|
1614
|
-
}
|
|
1615
|
-
if ((0, messages_1.isDataContentBlock)(item)) {
|
|
1616
|
-
return (0, messages_1.convertToProviderContentBlock)(item, completionsApiContentBlockConverter);
|
|
1617
|
-
}
|
|
1618
|
-
if (item.type === "text") {
|
|
1619
|
-
return {
|
|
1620
|
-
type: "input_text",
|
|
1621
|
-
text: item.text,
|
|
1622
|
-
};
|
|
1623
|
-
}
|
|
1624
|
-
if (item.type === "image_url") {
|
|
1625
|
-
return {
|
|
1626
|
-
type: "input_image",
|
|
1627
|
-
image_url: typeof item.image_url === "string"
|
|
1628
|
-
? item.image_url
|
|
1629
|
-
: item.image_url.url,
|
|
1630
|
-
detail: typeof item.image_url === "string"
|
|
1631
|
-
? "auto"
|
|
1632
|
-
: item.image_url.detail,
|
|
1633
|
-
};
|
|
1634
|
-
}
|
|
1635
|
-
if (item.type === "input_text" ||
|
|
1636
|
-
item.type === "input_image" ||
|
|
1637
|
-
item.type === "input_file") {
|
|
1638
|
-
return item;
|
|
1639
|
-
}
|
|
1640
|
-
return [];
|
|
1641
|
-
});
|
|
1642
|
-
if (content.length > 0) {
|
|
1643
|
-
messages.push({ type: "message", role, content });
|
|
1644
|
-
}
|
|
1645
|
-
return messages;
|
|
1646
|
-
}
|
|
1647
|
-
console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`);
|
|
1648
|
-
return [];
|
|
1649
|
-
});
|
|
1650
|
-
}
|
|
1651
|
-
/** @internal */
|
|
1652
|
-
_convertReasoningSummary(reasoning) {
|
|
1653
|
-
// combine summary parts that have the the same index and then remove the indexes
|
|
1654
|
-
const summary = (reasoning.summary.length > 1
|
|
1655
|
-
? reasoning.summary.reduce((acc, curr) => {
|
|
1656
|
-
const last = acc.at(-1);
|
|
1657
|
-
if (last.index === curr.index) {
|
|
1658
|
-
last.text += curr.text;
|
|
1659
|
-
}
|
|
1660
|
-
else {
|
|
1661
|
-
acc.push(curr);
|
|
1662
|
-
}
|
|
1663
|
-
return acc;
|
|
1664
|
-
}, [{ ...reasoning.summary[0] }])
|
|
1665
|
-
: reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index")));
|
|
1666
|
-
return {
|
|
1667
|
-
...reasoning,
|
|
1668
|
-
summary,
|
|
1669
|
-
};
|
|
1670
|
-
}
|
|
1671
|
-
/** @internal */
|
|
1672
|
-
_reduceChatOpenAITools(tools, fields) {
|
|
1673
|
-
const reducedTools = [];
|
|
1674
|
-
for (const tool of tools) {
|
|
1675
|
-
if ((0, tools_js_1.isBuiltInTool)(tool)) {
|
|
1676
|
-
if (tool.type === "image_generation" && fields?.stream) {
|
|
1677
|
-
// OpenAI sends a 400 error if partial_images is not set and we want to stream.
|
|
1678
|
-
// We also set it to 1 since we don't support partial images yet.
|
|
1679
|
-
tool.partial_images = 1;
|
|
1680
|
-
}
|
|
1681
|
-
reducedTools.push(tool);
|
|
1682
|
-
}
|
|
1683
|
-
else if ((0, base_1.isOpenAITool)(tool)) {
|
|
1684
|
-
reducedTools.push({
|
|
1685
|
-
type: "function",
|
|
1686
|
-
name: tool.function.name,
|
|
1687
|
-
parameters: tool.function.parameters,
|
|
1688
|
-
description: tool.function.description,
|
|
1689
|
-
strict: fields?.strict ?? null,
|
|
1690
|
-
});
|
|
1691
|
-
}
|
|
1692
|
-
else if ((0, tools_js_1.isOpenAICustomTool)(tool)) {
|
|
1693
|
-
reducedTools.push((0, tools_js_1.convertCompletionsCustomTool)(tool));
|
|
1694
|
-
}
|
|
1695
|
-
}
|
|
1696
|
-
return reducedTools;
|
|
1697
|
-
}
|
|
1698
|
-
}
|
|
1699
|
-
exports.ChatOpenAIResponses = ChatOpenAIResponses;
|
|
531
|
+
* OpenAI Responses API implementation.
|
|
532
|
+
*
|
|
533
|
+
* Will be exported in a later version of @langchain/openai.
|
|
534
|
+
*
|
|
535
|
+
* @internal
|
|
536
|
+
*/
|
|
537
|
+
var ChatOpenAIResponses = class extends BaseChatOpenAI {
|
|
538
|
+
invocationParams(options) {
|
|
539
|
+
let strict;
|
|
540
|
+
if (options?.strict !== void 0) strict = options.strict;
|
|
541
|
+
else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;
|
|
542
|
+
const params = {
|
|
543
|
+
model: this.model,
|
|
544
|
+
temperature: this.temperature,
|
|
545
|
+
top_p: this.topP,
|
|
546
|
+
user: this.user,
|
|
547
|
+
stream: this.streaming,
|
|
548
|
+
previous_response_id: options?.previous_response_id,
|
|
549
|
+
truncation: options?.truncation,
|
|
550
|
+
include: options?.include,
|
|
551
|
+
tools: options?.tools?.length ? this._reduceChatOpenAITools(options.tools, {
|
|
552
|
+
stream: this.streaming,
|
|
553
|
+
strict
|
|
554
|
+
}) : void 0,
|
|
555
|
+
tool_choice: require_tools.isBuiltInToolChoice(options?.tool_choice) ? options?.tool_choice : (() => {
|
|
556
|
+
const formatted = require_tools.formatToOpenAIToolChoice(options?.tool_choice);
|
|
557
|
+
if (typeof formatted === "object" && "type" in formatted) {
|
|
558
|
+
if (formatted.type === "function") return {
|
|
559
|
+
type: "function",
|
|
560
|
+
name: formatted.function.name
|
|
561
|
+
};
|
|
562
|
+
else if (formatted.type === "allowed_tools") return {
|
|
563
|
+
type: "allowed_tools",
|
|
564
|
+
mode: formatted.allowed_tools.mode,
|
|
565
|
+
tools: formatted.allowed_tools.tools
|
|
566
|
+
};
|
|
567
|
+
else if (formatted.type === "custom") return {
|
|
568
|
+
type: "custom",
|
|
569
|
+
name: formatted.custom.name
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
return void 0;
|
|
573
|
+
})(),
|
|
574
|
+
text: (() => {
|
|
575
|
+
if (options?.text) return options.text;
|
|
576
|
+
const format = this._getResponseFormat(options?.response_format);
|
|
577
|
+
if (format?.type === "json_schema") {
|
|
578
|
+
if (format.json_schema.schema != null) return {
|
|
579
|
+
format: {
|
|
580
|
+
type: "json_schema",
|
|
581
|
+
schema: format.json_schema.schema,
|
|
582
|
+
description: format.json_schema.description,
|
|
583
|
+
name: format.json_schema.name,
|
|
584
|
+
strict: format.json_schema.strict
|
|
585
|
+
},
|
|
586
|
+
verbosity: options?.verbosity
|
|
587
|
+
};
|
|
588
|
+
return void 0;
|
|
589
|
+
}
|
|
590
|
+
return {
|
|
591
|
+
format,
|
|
592
|
+
verbosity: options?.verbosity
|
|
593
|
+
};
|
|
594
|
+
})(),
|
|
595
|
+
parallel_tool_calls: options?.parallel_tool_calls,
|
|
596
|
+
max_output_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens,
|
|
597
|
+
prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,
|
|
598
|
+
...this.zdrEnabled ? { store: false } : {},
|
|
599
|
+
...this.modelKwargs
|
|
600
|
+
};
|
|
601
|
+
const reasoning = this._getReasoningParams(options);
|
|
602
|
+
if (reasoning !== void 0) params.reasoning = reasoning;
|
|
603
|
+
return params;
|
|
604
|
+
}
|
|
605
|
+
async _generate(messages, options) {
|
|
606
|
+
const invocationParams = this.invocationParams(options);
|
|
607
|
+
if (invocationParams.stream) {
|
|
608
|
+
const stream = this._streamResponseChunks(messages, options);
|
|
609
|
+
let finalChunk;
|
|
610
|
+
for await (const chunk of stream) {
|
|
611
|
+
chunk.message.response_metadata = {
|
|
612
|
+
...chunk.generationInfo,
|
|
613
|
+
...chunk.message.response_metadata
|
|
614
|
+
};
|
|
615
|
+
finalChunk = finalChunk?.concat(chunk) ?? chunk;
|
|
616
|
+
}
|
|
617
|
+
return {
|
|
618
|
+
generations: finalChunk ? [finalChunk] : [],
|
|
619
|
+
llmOutput: { estimatedTokenUsage: (finalChunk?.message)?.usage_metadata }
|
|
620
|
+
};
|
|
621
|
+
} else {
|
|
622
|
+
const input = this._convertMessagesToResponsesParams(messages);
|
|
623
|
+
const data = await this.completionWithRetry({
|
|
624
|
+
input,
|
|
625
|
+
...invocationParams,
|
|
626
|
+
stream: false
|
|
627
|
+
}, {
|
|
628
|
+
signal: options?.signal,
|
|
629
|
+
...options?.options
|
|
630
|
+
});
|
|
631
|
+
return {
|
|
632
|
+
generations: [{
|
|
633
|
+
text: data.output_text,
|
|
634
|
+
message: this._convertResponsesMessageToBaseMessage(data)
|
|
635
|
+
}],
|
|
636
|
+
llmOutput: {
|
|
637
|
+
id: data.id,
|
|
638
|
+
estimatedTokenUsage: data.usage ? {
|
|
639
|
+
promptTokens: data.usage.input_tokens,
|
|
640
|
+
completionTokens: data.usage.output_tokens,
|
|
641
|
+
totalTokens: data.usage.total_tokens
|
|
642
|
+
} : void 0
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
async *_streamResponseChunks(messages, options, runManager) {
|
|
648
|
+
const streamIterable = await this.completionWithRetry({
|
|
649
|
+
...this.invocationParams(options),
|
|
650
|
+
input: this._convertMessagesToResponsesParams(messages),
|
|
651
|
+
stream: true
|
|
652
|
+
}, options);
|
|
653
|
+
for await (const data of streamIterable) {
|
|
654
|
+
const chunk = this._convertResponsesDeltaToBaseMessageChunk(data);
|
|
655
|
+
if (chunk == null) continue;
|
|
656
|
+
yield chunk;
|
|
657
|
+
await runManager?.handleLLMNewToken(chunk.text || "", {
|
|
658
|
+
prompt: options.promptIndex ?? 0,
|
|
659
|
+
completion: 0
|
|
660
|
+
}, void 0, void 0, void 0, { chunk });
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
async completionWithRetry(request, requestOptions) {
|
|
664
|
+
return this.caller.call(async () => {
|
|
665
|
+
const clientOptions = this._getClientOptions(requestOptions);
|
|
666
|
+
try {
|
|
667
|
+
if (request.text?.format?.type === "json_schema" && !request.stream) return await this.client.responses.parse(request, clientOptions);
|
|
668
|
+
return await this.client.responses.create(request, clientOptions);
|
|
669
|
+
} catch (e) {
|
|
670
|
+
const error = require_client.wrapOpenAIClientError(e);
|
|
671
|
+
throw error;
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
/** @internal */
|
|
676
|
+
_convertResponsesMessageToBaseMessage(response) {
|
|
677
|
+
if (response.error) {
|
|
678
|
+
const error = new Error(response.error.message);
|
|
679
|
+
error.name = response.error.code;
|
|
680
|
+
throw error;
|
|
681
|
+
}
|
|
682
|
+
let messageId;
|
|
683
|
+
const content = [];
|
|
684
|
+
const tool_calls = [];
|
|
685
|
+
const invalid_tool_calls = [];
|
|
686
|
+
const response_metadata = {
|
|
687
|
+
model_provider: "openai",
|
|
688
|
+
model: response.model,
|
|
689
|
+
created_at: response.created_at,
|
|
690
|
+
id: response.id,
|
|
691
|
+
incomplete_details: response.incomplete_details,
|
|
692
|
+
metadata: response.metadata,
|
|
693
|
+
object: response.object,
|
|
694
|
+
status: response.status,
|
|
695
|
+
user: response.user,
|
|
696
|
+
service_tier: response.service_tier,
|
|
697
|
+
model_name: response.model
|
|
698
|
+
};
|
|
699
|
+
const additional_kwargs = {};
|
|
700
|
+
for (const item of response.output) if (item.type === "message") {
|
|
701
|
+
messageId = item.id;
|
|
702
|
+
content.push(...item.content.flatMap((part) => {
|
|
703
|
+
if (part.type === "output_text") {
|
|
704
|
+
if ("parsed" in part && part.parsed != null) additional_kwargs.parsed = part.parsed;
|
|
705
|
+
return {
|
|
706
|
+
type: "text",
|
|
707
|
+
text: part.text,
|
|
708
|
+
annotations: part.annotations
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
if (part.type === "refusal") {
|
|
712
|
+
additional_kwargs.refusal = part.refusal;
|
|
713
|
+
return [];
|
|
714
|
+
}
|
|
715
|
+
return part;
|
|
716
|
+
}));
|
|
717
|
+
} else if (item.type === "function_call") {
|
|
718
|
+
const fnAdapter = {
|
|
719
|
+
function: {
|
|
720
|
+
name: item.name,
|
|
721
|
+
arguments: item.arguments
|
|
722
|
+
},
|
|
723
|
+
id: item.call_id
|
|
724
|
+
};
|
|
725
|
+
try {
|
|
726
|
+
tool_calls.push((0, __langchain_core_output_parsers_openai_tools.parseToolCall)(fnAdapter, { returnId: true }));
|
|
727
|
+
} catch (e) {
|
|
728
|
+
let errMessage;
|
|
729
|
+
if (typeof e === "object" && e != null && "message" in e && typeof e.message === "string") errMessage = e.message;
|
|
730
|
+
invalid_tool_calls.push((0, __langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(fnAdapter, errMessage));
|
|
731
|
+
}
|
|
732
|
+
additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {};
|
|
733
|
+
if (item.id) additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id;
|
|
734
|
+
} else if (item.type === "reasoning") additional_kwargs.reasoning = item;
|
|
735
|
+
else if (item.type === "custom_tool_call") {
|
|
736
|
+
const parsed = require_tools.parseCustomToolCall(item);
|
|
737
|
+
if (parsed) tool_calls.push(parsed);
|
|
738
|
+
else invalid_tool_calls.push((0, __langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(item, "Malformed custom tool call"));
|
|
739
|
+
} else {
|
|
740
|
+
additional_kwargs.tool_outputs ??= [];
|
|
741
|
+
additional_kwargs.tool_outputs.push(item);
|
|
742
|
+
}
|
|
743
|
+
return new __langchain_core_messages.AIMessage({
|
|
744
|
+
id: messageId,
|
|
745
|
+
content,
|
|
746
|
+
tool_calls,
|
|
747
|
+
invalid_tool_calls,
|
|
748
|
+
usage_metadata: response.usage,
|
|
749
|
+
additional_kwargs,
|
|
750
|
+
response_metadata
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
/** @internal */
|
|
754
|
+
_convertResponsesDeltaToBaseMessageChunk(chunk) {
|
|
755
|
+
const content = [];
|
|
756
|
+
let generationInfo = {};
|
|
757
|
+
let usage_metadata;
|
|
758
|
+
const tool_call_chunks = [];
|
|
759
|
+
const response_metadata = { model_provider: "openai" };
|
|
760
|
+
const additional_kwargs = {};
|
|
761
|
+
let id;
|
|
762
|
+
if (chunk.type === "response.output_text.delta") content.push({
|
|
763
|
+
type: "text",
|
|
764
|
+
text: chunk.delta,
|
|
765
|
+
index: chunk.content_index
|
|
766
|
+
});
|
|
767
|
+
else if (chunk.type === "response.output_text.annotation.added") content.push({
|
|
768
|
+
type: "text",
|
|
769
|
+
text: "",
|
|
770
|
+
annotations: [chunk.annotation],
|
|
771
|
+
index: chunk.content_index
|
|
772
|
+
});
|
|
773
|
+
else if (chunk.type === "response.output_item.added" && chunk.item.type === "message") id = chunk.item.id;
|
|
774
|
+
else if (chunk.type === "response.output_item.added" && chunk.item.type === "function_call") {
|
|
775
|
+
tool_call_chunks.push({
|
|
776
|
+
type: "tool_call_chunk",
|
|
777
|
+
name: chunk.item.name,
|
|
778
|
+
args: chunk.item.arguments,
|
|
779
|
+
id: chunk.item.call_id,
|
|
780
|
+
index: chunk.output_index
|
|
781
|
+
});
|
|
782
|
+
additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = { [chunk.item.call_id]: chunk.item.id };
|
|
783
|
+
} else if (chunk.type === "response.output_item.done" && [
|
|
784
|
+
"web_search_call",
|
|
785
|
+
"file_search_call",
|
|
786
|
+
"computer_call",
|
|
787
|
+
"code_interpreter_call",
|
|
788
|
+
"mcp_call",
|
|
789
|
+
"mcp_list_tools",
|
|
790
|
+
"mcp_approval_request",
|
|
791
|
+
"image_generation_call",
|
|
792
|
+
"custom_tool_call"
|
|
793
|
+
].includes(chunk.item.type)) additional_kwargs.tool_outputs = [chunk.item];
|
|
794
|
+
else if (chunk.type === "response.created") {
|
|
795
|
+
response_metadata.id = chunk.response.id;
|
|
796
|
+
response_metadata.model_name = chunk.response.model;
|
|
797
|
+
response_metadata.model = chunk.response.model;
|
|
798
|
+
} else if (chunk.type === "response.completed") {
|
|
799
|
+
const msg = this._convertResponsesMessageToBaseMessage(chunk.response);
|
|
800
|
+
usage_metadata = chunk.response.usage;
|
|
801
|
+
if (chunk.response.text?.format?.type === "json_schema") additional_kwargs.parsed ??= JSON.parse(msg.text);
|
|
802
|
+
for (const [key, value] of Object.entries(chunk.response)) if (key !== "id") response_metadata[key] = value;
|
|
803
|
+
} else if (chunk.type === "response.function_call_arguments.delta") tool_call_chunks.push({
|
|
804
|
+
type: "tool_call_chunk",
|
|
805
|
+
args: chunk.delta,
|
|
806
|
+
index: chunk.output_index
|
|
807
|
+
});
|
|
808
|
+
else if (chunk.type === "response.web_search_call.completed" || chunk.type === "response.file_search_call.completed") generationInfo = { tool_outputs: {
|
|
809
|
+
id: chunk.item_id,
|
|
810
|
+
type: chunk.type.replace("response.", "").replace(".completed", ""),
|
|
811
|
+
status: "completed"
|
|
812
|
+
} };
|
|
813
|
+
else if (chunk.type === "response.refusal.done") additional_kwargs.refusal = chunk.refusal;
|
|
814
|
+
else if (chunk.type === "response.output_item.added" && "item" in chunk && chunk.item.type === "reasoning") {
|
|
815
|
+
const summary = chunk.item.summary ? chunk.item.summary.map((s, index) => ({
|
|
816
|
+
...s,
|
|
817
|
+
index
|
|
818
|
+
})) : void 0;
|
|
819
|
+
additional_kwargs.reasoning = {
|
|
820
|
+
id: chunk.item.id,
|
|
821
|
+
type: chunk.item.type,
|
|
822
|
+
...summary ? { summary } : {}
|
|
823
|
+
};
|
|
824
|
+
} else if (chunk.type === "response.reasoning_summary_part.added") additional_kwargs.reasoning = {
|
|
825
|
+
type: "reasoning",
|
|
826
|
+
summary: [{
|
|
827
|
+
...chunk.part,
|
|
828
|
+
index: chunk.summary_index
|
|
829
|
+
}]
|
|
830
|
+
};
|
|
831
|
+
else if (chunk.type === "response.reasoning_summary_text.delta") additional_kwargs.reasoning = {
|
|
832
|
+
type: "reasoning",
|
|
833
|
+
summary: [{
|
|
834
|
+
text: chunk.delta,
|
|
835
|
+
type: "summary_text",
|
|
836
|
+
index: chunk.summary_index
|
|
837
|
+
}]
|
|
838
|
+
};
|
|
839
|
+
else if (chunk.type === "response.image_generation_call.partial_image") return null;
|
|
840
|
+
else return null;
|
|
841
|
+
return new __langchain_core_outputs.ChatGenerationChunk({
|
|
842
|
+
text: content.map((part) => part.text).join(""),
|
|
843
|
+
message: new __langchain_core_messages.AIMessageChunk({
|
|
844
|
+
id,
|
|
845
|
+
content,
|
|
846
|
+
tool_call_chunks,
|
|
847
|
+
usage_metadata,
|
|
848
|
+
additional_kwargs,
|
|
849
|
+
response_metadata
|
|
850
|
+
}),
|
|
851
|
+
generationInfo
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
/** @internal */
|
|
855
|
+
_convertMessagesToResponsesParams(messages) {
|
|
856
|
+
return messages.flatMap((lcMsg) => {
|
|
857
|
+
if ((0, __langchain_core_messages.isAIMessage)(lcMsg) && lcMsg.response_metadata?.output_version === "v1") return require_standard._convertToResponsesMessageFromV1(lcMsg);
|
|
858
|
+
const additional_kwargs = lcMsg.additional_kwargs;
|
|
859
|
+
let role = require_misc.messageToOpenAIRole(lcMsg);
|
|
860
|
+
if (role === "system" && require_misc.isReasoningModel(this.model)) role = "developer";
|
|
861
|
+
if (role === "function") throw new Error("Function messages are not supported in Responses API");
|
|
862
|
+
if (role === "tool") {
|
|
863
|
+
const toolMessage = lcMsg;
|
|
864
|
+
if (additional_kwargs?.type === "computer_call_output") {
|
|
865
|
+
const output = (() => {
|
|
866
|
+
if (typeof toolMessage.content === "string") return {
|
|
867
|
+
type: "computer_screenshot",
|
|
868
|
+
image_url: toolMessage.content
|
|
869
|
+
};
|
|
870
|
+
if (Array.isArray(toolMessage.content)) {
|
|
871
|
+
const oaiScreenshot = toolMessage.content.find((i) => i.type === "computer_screenshot");
|
|
872
|
+
if (oaiScreenshot) return oaiScreenshot;
|
|
873
|
+
const lcImage = toolMessage.content.find((i) => i.type === "image_url");
|
|
874
|
+
if (lcImage) return {
|
|
875
|
+
type: "computer_screenshot",
|
|
876
|
+
image_url: typeof lcImage.image_url === "string" ? lcImage.image_url : lcImage.image_url.url
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
throw new Error("Invalid computer call output");
|
|
880
|
+
})();
|
|
881
|
+
return {
|
|
882
|
+
type: "computer_call_output",
|
|
883
|
+
output,
|
|
884
|
+
call_id: toolMessage.tool_call_id
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
return {
|
|
888
|
+
type: "function_call_output",
|
|
889
|
+
call_id: toolMessage.tool_call_id,
|
|
890
|
+
id: toolMessage.id?.startsWith("fc_") ? toolMessage.id : void 0,
|
|
891
|
+
output: typeof toolMessage.content !== "string" ? JSON.stringify(toolMessage.content) : toolMessage.content
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
if (role === "assistant") {
|
|
895
|
+
if (!this.zdrEnabled && lcMsg.response_metadata.output != null && Array.isArray(lcMsg.response_metadata.output) && lcMsg.response_metadata.output.length > 0 && lcMsg.response_metadata.output.every((item) => "type" in item)) return lcMsg.response_metadata.output;
|
|
896
|
+
const input = [];
|
|
897
|
+
if (additional_kwargs?.reasoning && !this.zdrEnabled) {
|
|
898
|
+
const reasoningItem = this._convertReasoningSummary(additional_kwargs.reasoning);
|
|
899
|
+
input.push(reasoningItem);
|
|
900
|
+
}
|
|
901
|
+
let { content } = lcMsg;
|
|
902
|
+
if (additional_kwargs?.refusal) {
|
|
903
|
+
if (typeof content === "string") content = [{
|
|
904
|
+
type: "output_text",
|
|
905
|
+
text: content,
|
|
906
|
+
annotations: []
|
|
907
|
+
}];
|
|
908
|
+
content = [...content, {
|
|
909
|
+
type: "refusal",
|
|
910
|
+
refusal: additional_kwargs.refusal
|
|
911
|
+
}];
|
|
912
|
+
}
|
|
913
|
+
if (typeof content === "string" || content.length > 0) input.push({
|
|
914
|
+
type: "message",
|
|
915
|
+
role: "assistant",
|
|
916
|
+
...lcMsg.id && !this.zdrEnabled && lcMsg.id.startsWith("msg_") ? { id: lcMsg.id } : {},
|
|
917
|
+
content: require_misc.iife(() => {
|
|
918
|
+
if (typeof content === "string") return content;
|
|
919
|
+
return content.flatMap((item) => {
|
|
920
|
+
if (item.type === "text") return {
|
|
921
|
+
type: "output_text",
|
|
922
|
+
text: item.text,
|
|
923
|
+
annotations: item.annotations ?? []
|
|
924
|
+
};
|
|
925
|
+
if (item.type === "output_text" || item.type === "refusal") return item;
|
|
926
|
+
return [];
|
|
927
|
+
});
|
|
928
|
+
})
|
|
929
|
+
});
|
|
930
|
+
const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];
|
|
931
|
+
if ((0, __langchain_core_messages.isAIMessage)(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => {
|
|
932
|
+
if (require_tools.isCustomToolCall(toolCall)) return {
|
|
933
|
+
type: "custom_tool_call",
|
|
934
|
+
id: toolCall.call_id,
|
|
935
|
+
call_id: toolCall.id ?? "",
|
|
936
|
+
input: toolCall.args.input,
|
|
937
|
+
name: toolCall.name
|
|
938
|
+
};
|
|
939
|
+
return {
|
|
940
|
+
type: "function_call",
|
|
941
|
+
name: toolCall.name,
|
|
942
|
+
arguments: JSON.stringify(toolCall.args),
|
|
943
|
+
call_id: toolCall.id,
|
|
944
|
+
...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}
|
|
945
|
+
};
|
|
946
|
+
}));
|
|
947
|
+
else if (additional_kwargs?.tool_calls) input.push(...additional_kwargs.tool_calls.map((toolCall) => ({
|
|
948
|
+
type: "function_call",
|
|
949
|
+
name: toolCall.function.name,
|
|
950
|
+
call_id: toolCall.id,
|
|
951
|
+
arguments: toolCall.function.arguments,
|
|
952
|
+
...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}
|
|
953
|
+
})));
|
|
954
|
+
const toolOutputs = lcMsg.response_metadata.output?.length ? lcMsg.response_metadata.output : additional_kwargs.tool_outputs;
|
|
955
|
+
const fallthroughCallTypes = [
|
|
956
|
+
"computer_call",
|
|
957
|
+
"mcp_call",
|
|
958
|
+
"code_interpreter_call",
|
|
959
|
+
"image_generation_call"
|
|
960
|
+
];
|
|
961
|
+
if (toolOutputs != null) {
|
|
962
|
+
const castToolOutputs = toolOutputs;
|
|
963
|
+
const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type));
|
|
964
|
+
if (fallthroughCalls.length > 0) input.push(...fallthroughCalls);
|
|
965
|
+
}
|
|
966
|
+
return input;
|
|
967
|
+
}
|
|
968
|
+
if (role === "user" || role === "system" || role === "developer") {
|
|
969
|
+
if (typeof lcMsg.content === "string") return {
|
|
970
|
+
type: "message",
|
|
971
|
+
role,
|
|
972
|
+
content: lcMsg.content
|
|
973
|
+
};
|
|
974
|
+
const messages$1 = [];
|
|
975
|
+
const content = lcMsg.content.flatMap((item) => {
|
|
976
|
+
if (item.type === "mcp_approval_response") messages$1.push({
|
|
977
|
+
type: "mcp_approval_response",
|
|
978
|
+
approval_request_id: item.approval_request_id,
|
|
979
|
+
approve: item.approve
|
|
980
|
+
});
|
|
981
|
+
if ((0, __langchain_core_messages.isDataContentBlock)(item)) return (0, __langchain_core_messages.convertToProviderContentBlock)(item, require_message_inputs.completionsApiContentBlockConverter);
|
|
982
|
+
if (item.type === "text") return {
|
|
983
|
+
type: "input_text",
|
|
984
|
+
text: item.text
|
|
985
|
+
};
|
|
986
|
+
if (item.type === "image_url") {
|
|
987
|
+
const imageUrl = require_misc.iife(() => {
|
|
988
|
+
if (typeof item.image_url === "string") return item.image_url;
|
|
989
|
+
else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) return item.image_url.url;
|
|
990
|
+
return void 0;
|
|
991
|
+
});
|
|
992
|
+
const detail = require_misc.iife(() => {
|
|
993
|
+
if (typeof item.image_url === "string") return "auto";
|
|
994
|
+
else if (typeof item.image_url === "object" && item.image_url !== null && "detail" in item.image_url) return item.image_url.detail;
|
|
995
|
+
return void 0;
|
|
996
|
+
});
|
|
997
|
+
return {
|
|
998
|
+
type: "input_image",
|
|
999
|
+
image_url: imageUrl,
|
|
1000
|
+
detail
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
if (item.type === "input_text" || item.type === "input_image" || item.type === "input_file") return item;
|
|
1004
|
+
return [];
|
|
1005
|
+
});
|
|
1006
|
+
if (content.length > 0) messages$1.push({
|
|
1007
|
+
type: "message",
|
|
1008
|
+
role,
|
|
1009
|
+
content
|
|
1010
|
+
});
|
|
1011
|
+
return messages$1;
|
|
1012
|
+
}
|
|
1013
|
+
console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`);
|
|
1014
|
+
return [];
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
/** @internal */
|
|
1018
|
+
_convertReasoningSummary(reasoning) {
|
|
1019
|
+
const summary = (reasoning.summary.length > 1 ? reasoning.summary.reduce((acc, curr) => {
|
|
1020
|
+
const last = acc.at(-1);
|
|
1021
|
+
if (last.index === curr.index) last.text += curr.text;
|
|
1022
|
+
else acc.push(curr);
|
|
1023
|
+
return acc;
|
|
1024
|
+
}, [{ ...reasoning.summary[0] }]) : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index")));
|
|
1025
|
+
return {
|
|
1026
|
+
...reasoning,
|
|
1027
|
+
summary
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
/** @internal */
|
|
1031
|
+
_reduceChatOpenAITools(tools, fields) {
|
|
1032
|
+
const reducedTools = [];
|
|
1033
|
+
for (const tool of tools) if (require_tools.isBuiltInTool(tool)) {
|
|
1034
|
+
if (tool.type === "image_generation" && fields?.stream) tool.partial_images = 1;
|
|
1035
|
+
reducedTools.push(tool);
|
|
1036
|
+
} else if ((0, __langchain_core_language_models_base.isOpenAITool)(tool)) reducedTools.push({
|
|
1037
|
+
type: "function",
|
|
1038
|
+
name: tool.function.name,
|
|
1039
|
+
parameters: tool.function.parameters,
|
|
1040
|
+
description: tool.function.description,
|
|
1041
|
+
strict: fields?.strict ?? null
|
|
1042
|
+
});
|
|
1043
|
+
else if (require_tools.isOpenAICustomTool(tool)) reducedTools.push(require_tools.convertCompletionsCustomTool(tool));
|
|
1044
|
+
return reducedTools;
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1700
1047
|
/**
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
const rawToolCalls = message.tool_calls;
|
|
2012
|
-
switch (message.role) {
|
|
2013
|
-
case "assistant": {
|
|
2014
|
-
const toolCalls = [];
|
|
2015
|
-
const invalidToolCalls = [];
|
|
2016
|
-
for (const rawToolCall of rawToolCalls ?? []) {
|
|
2017
|
-
try {
|
|
2018
|
-
toolCalls.push((0, openai_tools_1.parseToolCall)(rawToolCall, { returnId: true }));
|
|
2019
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2020
|
-
}
|
|
2021
|
-
catch (e) {
|
|
2022
|
-
invalidToolCalls.push((0, openai_tools_1.makeInvalidToolCall)(rawToolCall, e.message));
|
|
2023
|
-
}
|
|
2024
|
-
}
|
|
2025
|
-
const additional_kwargs = {
|
|
2026
|
-
function_call: message.function_call,
|
|
2027
|
-
tool_calls: rawToolCalls,
|
|
2028
|
-
};
|
|
2029
|
-
if (this.__includeRawResponse !== undefined) {
|
|
2030
|
-
additional_kwargs.__raw_response = rawResponse;
|
|
2031
|
-
}
|
|
2032
|
-
const response_metadata = {
|
|
2033
|
-
model_name: rawResponse.model,
|
|
2034
|
-
...(rawResponse.system_fingerprint
|
|
2035
|
-
? {
|
|
2036
|
-
usage: { ...rawResponse.usage },
|
|
2037
|
-
system_fingerprint: rawResponse.system_fingerprint,
|
|
2038
|
-
}
|
|
2039
|
-
: {}),
|
|
2040
|
-
};
|
|
2041
|
-
if (message.audio) {
|
|
2042
|
-
additional_kwargs.audio = message.audio;
|
|
2043
|
-
}
|
|
2044
|
-
return new messages_1.AIMessage({
|
|
2045
|
-
content: message.content || "",
|
|
2046
|
-
tool_calls: toolCalls,
|
|
2047
|
-
invalid_tool_calls: invalidToolCalls,
|
|
2048
|
-
additional_kwargs,
|
|
2049
|
-
response_metadata,
|
|
2050
|
-
id: rawResponse.id,
|
|
2051
|
-
});
|
|
2052
|
-
}
|
|
2053
|
-
default:
|
|
2054
|
-
return new messages_1.ChatMessage(message.content || "", message.role ?? "unknown");
|
|
2055
|
-
}
|
|
2056
|
-
}
|
|
2057
|
-
/** @internal */
|
|
2058
|
-
_convertCompletionsDeltaToBaseMessageChunk(
|
|
2059
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
2060
|
-
delta, rawResponse, defaultRole) {
|
|
2061
|
-
const role = delta.role ?? defaultRole;
|
|
2062
|
-
const content = delta.content ?? "";
|
|
2063
|
-
let additional_kwargs;
|
|
2064
|
-
if (delta.function_call) {
|
|
2065
|
-
additional_kwargs = {
|
|
2066
|
-
function_call: delta.function_call,
|
|
2067
|
-
};
|
|
2068
|
-
}
|
|
2069
|
-
else if (delta.tool_calls) {
|
|
2070
|
-
additional_kwargs = {
|
|
2071
|
-
tool_calls: delta.tool_calls,
|
|
2072
|
-
};
|
|
2073
|
-
}
|
|
2074
|
-
else {
|
|
2075
|
-
additional_kwargs = {};
|
|
2076
|
-
}
|
|
2077
|
-
if (this.__includeRawResponse) {
|
|
2078
|
-
additional_kwargs.__raw_response = rawResponse;
|
|
2079
|
-
}
|
|
2080
|
-
if (delta.audio) {
|
|
2081
|
-
additional_kwargs.audio = {
|
|
2082
|
-
...delta.audio,
|
|
2083
|
-
index: rawResponse.choices[0].index,
|
|
2084
|
-
};
|
|
2085
|
-
}
|
|
2086
|
-
const response_metadata = { usage: { ...rawResponse.usage } };
|
|
2087
|
-
if (role === "user") {
|
|
2088
|
-
return new messages_1.HumanMessageChunk({ content, response_metadata });
|
|
2089
|
-
}
|
|
2090
|
-
else if (role === "assistant") {
|
|
2091
|
-
const toolCallChunks = [];
|
|
2092
|
-
if (Array.isArray(delta.tool_calls)) {
|
|
2093
|
-
for (const rawToolCall of delta.tool_calls) {
|
|
2094
|
-
toolCallChunks.push({
|
|
2095
|
-
name: rawToolCall.function?.name,
|
|
2096
|
-
args: rawToolCall.function?.arguments,
|
|
2097
|
-
id: rawToolCall.id,
|
|
2098
|
-
index: rawToolCall.index,
|
|
2099
|
-
type: "tool_call_chunk",
|
|
2100
|
-
});
|
|
2101
|
-
}
|
|
2102
|
-
}
|
|
2103
|
-
return new messages_1.AIMessageChunk({
|
|
2104
|
-
content,
|
|
2105
|
-
tool_call_chunks: toolCallChunks,
|
|
2106
|
-
additional_kwargs,
|
|
2107
|
-
id: rawResponse.id,
|
|
2108
|
-
response_metadata,
|
|
2109
|
-
});
|
|
2110
|
-
}
|
|
2111
|
-
else if (role === "system") {
|
|
2112
|
-
return new messages_1.SystemMessageChunk({ content, response_metadata });
|
|
2113
|
-
}
|
|
2114
|
-
else if (role === "developer") {
|
|
2115
|
-
return new messages_1.SystemMessageChunk({
|
|
2116
|
-
content,
|
|
2117
|
-
response_metadata,
|
|
2118
|
-
additional_kwargs: {
|
|
2119
|
-
__openai_role__: "developer",
|
|
2120
|
-
},
|
|
2121
|
-
});
|
|
2122
|
-
}
|
|
2123
|
-
else if (role === "function") {
|
|
2124
|
-
return new messages_1.FunctionMessageChunk({
|
|
2125
|
-
content,
|
|
2126
|
-
additional_kwargs,
|
|
2127
|
-
name: delta.name,
|
|
2128
|
-
response_metadata,
|
|
2129
|
-
});
|
|
2130
|
-
}
|
|
2131
|
-
else if (role === "tool") {
|
|
2132
|
-
return new messages_1.ToolMessageChunk({
|
|
2133
|
-
content,
|
|
2134
|
-
additional_kwargs,
|
|
2135
|
-
tool_call_id: delta.tool_call_id,
|
|
2136
|
-
response_metadata,
|
|
2137
|
-
});
|
|
2138
|
-
}
|
|
2139
|
-
else {
|
|
2140
|
-
return new messages_1.ChatMessageChunk({ content, role, response_metadata });
|
|
2141
|
-
}
|
|
2142
|
-
}
|
|
2143
|
-
}
|
|
2144
|
-
exports.ChatOpenAICompletions = ChatOpenAICompletions;
|
|
1048
|
+
* OpenAI Completions API implementation.
|
|
1049
|
+
* @internal
|
|
1050
|
+
*/
|
|
1051
|
+
var ChatOpenAICompletions = class extends BaseChatOpenAI {
|
|
1052
|
+
/** @internal */
|
|
1053
|
+
invocationParams(options, extra) {
|
|
1054
|
+
let strict;
|
|
1055
|
+
if (options?.strict !== void 0) strict = options.strict;
|
|
1056
|
+
else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;
|
|
1057
|
+
let streamOptionsConfig = {};
|
|
1058
|
+
if (options?.stream_options !== void 0) streamOptionsConfig = { stream_options: options.stream_options };
|
|
1059
|
+
else if (this.streamUsage && (this.streaming || extra?.streaming)) streamOptionsConfig = { stream_options: { include_usage: true } };
|
|
1060
|
+
const params = {
|
|
1061
|
+
model: this.model,
|
|
1062
|
+
temperature: this.temperature,
|
|
1063
|
+
top_p: this.topP,
|
|
1064
|
+
frequency_penalty: this.frequencyPenalty,
|
|
1065
|
+
presence_penalty: this.presencePenalty,
|
|
1066
|
+
logprobs: this.logprobs,
|
|
1067
|
+
top_logprobs: this.topLogprobs,
|
|
1068
|
+
n: this.n,
|
|
1069
|
+
logit_bias: this.logitBias,
|
|
1070
|
+
stop: options?.stop ?? this.stopSequences,
|
|
1071
|
+
user: this.user,
|
|
1072
|
+
stream: this.streaming,
|
|
1073
|
+
functions: options?.functions,
|
|
1074
|
+
function_call: options?.function_call,
|
|
1075
|
+
tools: options?.tools?.length ? options.tools.map((tool) => this._convertChatOpenAIToolToCompletionsTool(tool, { strict })) : void 0,
|
|
1076
|
+
tool_choice: require_tools.formatToOpenAIToolChoice(options?.tool_choice),
|
|
1077
|
+
response_format: this._getResponseFormat(options?.response_format),
|
|
1078
|
+
seed: options?.seed,
|
|
1079
|
+
...streamOptionsConfig,
|
|
1080
|
+
parallel_tool_calls: options?.parallel_tool_calls,
|
|
1081
|
+
...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {},
|
|
1082
|
+
...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {},
|
|
1083
|
+
...this.modelKwargs,
|
|
1084
|
+
prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,
|
|
1085
|
+
verbosity: options?.verbosity ?? this.verbosity
|
|
1086
|
+
};
|
|
1087
|
+
if (options?.prediction !== void 0) params.prediction = options.prediction;
|
|
1088
|
+
if (this.service_tier !== void 0) params.service_tier = this.service_tier;
|
|
1089
|
+
if (options?.service_tier !== void 0) params.service_tier = options.service_tier;
|
|
1090
|
+
const reasoning = this._getReasoningParams(options);
|
|
1091
|
+
if (reasoning !== void 0 && reasoning.effort !== void 0) params.reasoning_effort = reasoning.effort;
|
|
1092
|
+
if (require_misc.isReasoningModel(params.model)) params.max_completion_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens;
|
|
1093
|
+
else params.max_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens;
|
|
1094
|
+
return params;
|
|
1095
|
+
}
|
|
1096
|
+
async _generate(messages, options, runManager) {
|
|
1097
|
+
const usageMetadata = {};
|
|
1098
|
+
const params = this.invocationParams(options);
|
|
1099
|
+
const messagesMapped = require_message_inputs._convertMessagesToOpenAIParams(messages, this.model);
|
|
1100
|
+
if (params.stream) {
|
|
1101
|
+
const stream = this._streamResponseChunks(messages, options, runManager);
|
|
1102
|
+
const finalChunks = {};
|
|
1103
|
+
for await (const chunk of stream) {
|
|
1104
|
+
chunk.message.response_metadata = {
|
|
1105
|
+
...chunk.generationInfo,
|
|
1106
|
+
...chunk.message.response_metadata
|
|
1107
|
+
};
|
|
1108
|
+
const index = chunk.generationInfo?.completion ?? 0;
|
|
1109
|
+
if (finalChunks[index] === void 0) finalChunks[index] = chunk;
|
|
1110
|
+
else finalChunks[index] = finalChunks[index].concat(chunk);
|
|
1111
|
+
}
|
|
1112
|
+
const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value);
|
|
1113
|
+
const { functions, function_call } = this.invocationParams(options);
|
|
1114
|
+
const promptTokenUsage = await this._getEstimatedTokenCountFromPrompt(messages, functions, function_call);
|
|
1115
|
+
const completionTokenUsage = await this._getNumTokensFromGenerations(generations);
|
|
1116
|
+
usageMetadata.input_tokens = promptTokenUsage;
|
|
1117
|
+
usageMetadata.output_tokens = completionTokenUsage;
|
|
1118
|
+
usageMetadata.total_tokens = promptTokenUsage + completionTokenUsage;
|
|
1119
|
+
return {
|
|
1120
|
+
generations,
|
|
1121
|
+
llmOutput: { estimatedTokenUsage: {
|
|
1122
|
+
promptTokens: usageMetadata.input_tokens,
|
|
1123
|
+
completionTokens: usageMetadata.output_tokens,
|
|
1124
|
+
totalTokens: usageMetadata.total_tokens
|
|
1125
|
+
} }
|
|
1126
|
+
};
|
|
1127
|
+
} else {
|
|
1128
|
+
const data = await this.completionWithRetry({
|
|
1129
|
+
...params,
|
|
1130
|
+
stream: false,
|
|
1131
|
+
messages: messagesMapped
|
|
1132
|
+
}, {
|
|
1133
|
+
signal: options?.signal,
|
|
1134
|
+
...options?.options
|
|
1135
|
+
});
|
|
1136
|
+
const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {};
|
|
1137
|
+
if (completionTokens) usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens;
|
|
1138
|
+
if (promptTokens) usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens;
|
|
1139
|
+
if (totalTokens) usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens;
|
|
1140
|
+
if (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) usageMetadata.input_token_details = {
|
|
1141
|
+
...promptTokensDetails?.audio_tokens !== null && { audio: promptTokensDetails?.audio_tokens },
|
|
1142
|
+
...promptTokensDetails?.cached_tokens !== null && { cache_read: promptTokensDetails?.cached_tokens }
|
|
1143
|
+
};
|
|
1144
|
+
if (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) usageMetadata.output_token_details = {
|
|
1145
|
+
...completionTokensDetails?.audio_tokens !== null && { audio: completionTokensDetails?.audio_tokens },
|
|
1146
|
+
...completionTokensDetails?.reasoning_tokens !== null && { reasoning: completionTokensDetails?.reasoning_tokens }
|
|
1147
|
+
};
|
|
1148
|
+
const generations = [];
|
|
1149
|
+
for (const part of data?.choices ?? []) {
|
|
1150
|
+
const text = part.message?.content ?? "";
|
|
1151
|
+
const generation = {
|
|
1152
|
+
text,
|
|
1153
|
+
message: this._convertCompletionsMessageToBaseMessage(part.message ?? { role: "assistant" }, data)
|
|
1154
|
+
};
|
|
1155
|
+
generation.generationInfo = {
|
|
1156
|
+
...part.finish_reason ? { finish_reason: part.finish_reason } : {},
|
|
1157
|
+
...part.logprobs ? { logprobs: part.logprobs } : {}
|
|
1158
|
+
};
|
|
1159
|
+
if ((0, __langchain_core_messages.isAIMessage)(generation.message)) generation.message.usage_metadata = usageMetadata;
|
|
1160
|
+
generation.message = new __langchain_core_messages.AIMessage(Object.fromEntries(Object.entries(generation.message).filter(([key]) => !key.startsWith("lc_"))));
|
|
1161
|
+
generations.push(generation);
|
|
1162
|
+
}
|
|
1163
|
+
return {
|
|
1164
|
+
generations,
|
|
1165
|
+
llmOutput: { tokenUsage: {
|
|
1166
|
+
promptTokens: usageMetadata.input_tokens,
|
|
1167
|
+
completionTokens: usageMetadata.output_tokens,
|
|
1168
|
+
totalTokens: usageMetadata.total_tokens
|
|
1169
|
+
} }
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
async *_streamResponseChunks(messages, options, runManager) {
|
|
1174
|
+
const messagesMapped = require_message_inputs._convertMessagesToOpenAIParams(messages, this.model);
|
|
1175
|
+
const params = {
|
|
1176
|
+
...this.invocationParams(options, { streaming: true }),
|
|
1177
|
+
messages: messagesMapped,
|
|
1178
|
+
stream: true
|
|
1179
|
+
};
|
|
1180
|
+
let defaultRole;
|
|
1181
|
+
const streamIterable = await this.completionWithRetry(params, options);
|
|
1182
|
+
let usage;
|
|
1183
|
+
for await (const data of streamIterable) {
|
|
1184
|
+
const choice = data?.choices?.[0];
|
|
1185
|
+
if (data.usage) usage = data.usage;
|
|
1186
|
+
if (!choice) continue;
|
|
1187
|
+
const { delta } = choice;
|
|
1188
|
+
if (!delta) continue;
|
|
1189
|
+
const chunk = this._convertCompletionsDeltaToBaseMessageChunk(delta, data, defaultRole);
|
|
1190
|
+
defaultRole = delta.role ?? defaultRole;
|
|
1191
|
+
const newTokenIndices = {
|
|
1192
|
+
prompt: options.promptIndex ?? 0,
|
|
1193
|
+
completion: choice.index ?? 0
|
|
1194
|
+
};
|
|
1195
|
+
if (typeof chunk.content !== "string") {
|
|
1196
|
+
console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");
|
|
1197
|
+
continue;
|
|
1198
|
+
}
|
|
1199
|
+
const generationInfo = { ...newTokenIndices };
|
|
1200
|
+
if (choice.finish_reason != null) {
|
|
1201
|
+
generationInfo.finish_reason = choice.finish_reason;
|
|
1202
|
+
generationInfo.system_fingerprint = data.system_fingerprint;
|
|
1203
|
+
generationInfo.model_name = data.model;
|
|
1204
|
+
generationInfo.service_tier = data.service_tier;
|
|
1205
|
+
}
|
|
1206
|
+
if (this.logprobs) generationInfo.logprobs = choice.logprobs;
|
|
1207
|
+
const generationChunk = new __langchain_core_outputs.ChatGenerationChunk({
|
|
1208
|
+
message: chunk,
|
|
1209
|
+
text: chunk.content,
|
|
1210
|
+
generationInfo
|
|
1211
|
+
});
|
|
1212
|
+
yield generationChunk;
|
|
1213
|
+
await runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk });
|
|
1214
|
+
}
|
|
1215
|
+
if (usage) {
|
|
1216
|
+
const inputTokenDetails = {
|
|
1217
|
+
...usage.prompt_tokens_details?.audio_tokens !== null && { audio: usage.prompt_tokens_details?.audio_tokens },
|
|
1218
|
+
...usage.prompt_tokens_details?.cached_tokens !== null && { cache_read: usage.prompt_tokens_details?.cached_tokens }
|
|
1219
|
+
};
|
|
1220
|
+
const outputTokenDetails = {
|
|
1221
|
+
...usage.completion_tokens_details?.audio_tokens !== null && { audio: usage.completion_tokens_details?.audio_tokens },
|
|
1222
|
+
...usage.completion_tokens_details?.reasoning_tokens !== null && { reasoning: usage.completion_tokens_details?.reasoning_tokens }
|
|
1223
|
+
};
|
|
1224
|
+
const generationChunk = new __langchain_core_outputs.ChatGenerationChunk({
|
|
1225
|
+
message: new __langchain_core_messages.AIMessageChunk({
|
|
1226
|
+
content: "",
|
|
1227
|
+
response_metadata: { usage: { ...usage } },
|
|
1228
|
+
usage_metadata: {
|
|
1229
|
+
input_tokens: usage.prompt_tokens,
|
|
1230
|
+
output_tokens: usage.completion_tokens,
|
|
1231
|
+
total_tokens: usage.total_tokens,
|
|
1232
|
+
...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails },
|
|
1233
|
+
...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails }
|
|
1234
|
+
}
|
|
1235
|
+
}),
|
|
1236
|
+
text: ""
|
|
1237
|
+
});
|
|
1238
|
+
yield generationChunk;
|
|
1239
|
+
}
|
|
1240
|
+
if (options.signal?.aborted) throw new Error("AbortError");
|
|
1241
|
+
}
|
|
1242
|
+
async completionWithRetry(request, requestOptions) {
|
|
1243
|
+
const clientOptions = this._getClientOptions(requestOptions);
|
|
1244
|
+
const isParseableFormat = request.response_format && request.response_format.type === "json_schema";
|
|
1245
|
+
return this.caller.call(async () => {
|
|
1246
|
+
try {
|
|
1247
|
+
if (isParseableFormat && !request.stream) return await this.client.chat.completions.parse(request, clientOptions);
|
|
1248
|
+
else return await this.client.chat.completions.create(request, clientOptions);
|
|
1249
|
+
} catch (e) {
|
|
1250
|
+
const error = require_client.wrapOpenAIClientError(e);
|
|
1251
|
+
throw error;
|
|
1252
|
+
}
|
|
1253
|
+
});
|
|
1254
|
+
}
|
|
1255
|
+
/** @internal */
|
|
1256
|
+
_convertCompletionsMessageToBaseMessage(message, rawResponse) {
|
|
1257
|
+
const rawToolCalls = message.tool_calls;
|
|
1258
|
+
switch (message.role) {
|
|
1259
|
+
case "assistant": {
|
|
1260
|
+
const toolCalls = [];
|
|
1261
|
+
const invalidToolCalls = [];
|
|
1262
|
+
for (const rawToolCall of rawToolCalls ?? []) try {
|
|
1263
|
+
toolCalls.push((0, __langchain_core_output_parsers_openai_tools.parseToolCall)(rawToolCall, { returnId: true }));
|
|
1264
|
+
} catch (e) {
|
|
1265
|
+
invalidToolCalls.push((0, __langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(rawToolCall, e.message));
|
|
1266
|
+
}
|
|
1267
|
+
const additional_kwargs = {
|
|
1268
|
+
function_call: message.function_call,
|
|
1269
|
+
tool_calls: rawToolCalls
|
|
1270
|
+
};
|
|
1271
|
+
if (this.__includeRawResponse !== void 0) additional_kwargs.__raw_response = rawResponse;
|
|
1272
|
+
const response_metadata = {
|
|
1273
|
+
model_provider: "openai",
|
|
1274
|
+
model_name: rawResponse.model,
|
|
1275
|
+
...rawResponse.system_fingerprint ? {
|
|
1276
|
+
usage: { ...rawResponse.usage },
|
|
1277
|
+
system_fingerprint: rawResponse.system_fingerprint
|
|
1278
|
+
} : {}
|
|
1279
|
+
};
|
|
1280
|
+
if (message.audio) additional_kwargs.audio = message.audio;
|
|
1281
|
+
return new __langchain_core_messages.AIMessage({
|
|
1282
|
+
content: message.content || "",
|
|
1283
|
+
tool_calls: toolCalls,
|
|
1284
|
+
invalid_tool_calls: invalidToolCalls,
|
|
1285
|
+
additional_kwargs,
|
|
1286
|
+
response_metadata,
|
|
1287
|
+
id: rawResponse.id
|
|
1288
|
+
});
|
|
1289
|
+
}
|
|
1290
|
+
default: return new __langchain_core_messages.ChatMessage(message.content || "", message.role ?? "unknown");
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
/** @internal */
|
|
1294
|
+
_convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) {
|
|
1295
|
+
const role = delta.role ?? defaultRole;
|
|
1296
|
+
const content = delta.content ?? "";
|
|
1297
|
+
let additional_kwargs;
|
|
1298
|
+
if (delta.function_call) additional_kwargs = { function_call: delta.function_call };
|
|
1299
|
+
else if (delta.tool_calls) additional_kwargs = { tool_calls: delta.tool_calls };
|
|
1300
|
+
else additional_kwargs = {};
|
|
1301
|
+
if (this.__includeRawResponse) additional_kwargs.__raw_response = rawResponse;
|
|
1302
|
+
if (delta.audio) additional_kwargs.audio = {
|
|
1303
|
+
...delta.audio,
|
|
1304
|
+
index: rawResponse.choices[0].index
|
|
1305
|
+
};
|
|
1306
|
+
const response_metadata = {
|
|
1307
|
+
model_provider: "openai",
|
|
1308
|
+
usage: { ...rawResponse.usage }
|
|
1309
|
+
};
|
|
1310
|
+
if (role === "user") return new __langchain_core_messages.HumanMessageChunk({
|
|
1311
|
+
content,
|
|
1312
|
+
response_metadata
|
|
1313
|
+
});
|
|
1314
|
+
else if (role === "assistant") {
|
|
1315
|
+
const toolCallChunks = [];
|
|
1316
|
+
if (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) toolCallChunks.push({
|
|
1317
|
+
name: rawToolCall.function?.name,
|
|
1318
|
+
args: rawToolCall.function?.arguments,
|
|
1319
|
+
id: rawToolCall.id,
|
|
1320
|
+
index: rawToolCall.index,
|
|
1321
|
+
type: "tool_call_chunk"
|
|
1322
|
+
});
|
|
1323
|
+
return new __langchain_core_messages.AIMessageChunk({
|
|
1324
|
+
content,
|
|
1325
|
+
tool_call_chunks: toolCallChunks,
|
|
1326
|
+
additional_kwargs,
|
|
1327
|
+
id: rawResponse.id,
|
|
1328
|
+
response_metadata
|
|
1329
|
+
});
|
|
1330
|
+
} else if (role === "system") return new __langchain_core_messages.SystemMessageChunk({
|
|
1331
|
+
content,
|
|
1332
|
+
response_metadata
|
|
1333
|
+
});
|
|
1334
|
+
else if (role === "developer") return new __langchain_core_messages.SystemMessageChunk({
|
|
1335
|
+
content,
|
|
1336
|
+
response_metadata,
|
|
1337
|
+
additional_kwargs: { __openai_role__: "developer" }
|
|
1338
|
+
});
|
|
1339
|
+
else if (role === "function") return new __langchain_core_messages.FunctionMessageChunk({
|
|
1340
|
+
content,
|
|
1341
|
+
additional_kwargs,
|
|
1342
|
+
name: delta.name,
|
|
1343
|
+
response_metadata
|
|
1344
|
+
});
|
|
1345
|
+
else if (role === "tool") return new __langchain_core_messages.ToolMessageChunk({
|
|
1346
|
+
content,
|
|
1347
|
+
additional_kwargs,
|
|
1348
|
+
tool_call_id: delta.tool_call_id,
|
|
1349
|
+
response_metadata
|
|
1350
|
+
});
|
|
1351
|
+
else return new __langchain_core_messages.ChatMessageChunk({
|
|
1352
|
+
content,
|
|
1353
|
+
role,
|
|
1354
|
+
response_metadata
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
};
|
|
2145
1358
|
/**
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
|
|
2293
|
-
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
|
|
2405
|
-
|
|
2406
|
-
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
|
|
2442
|
-
|
|
2443
|
-
|
|
2444
|
-
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
|
|
2478
|
-
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
|
|
2521
|
-
|
|
2522
|
-
|
|
2523
|
-
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2532
|
-
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
|
|
2635
|
-
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2669
|
-
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
class ChatOpenAI extends BaseChatOpenAI {
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2689
|
-
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
|
|
2718
|
-
|
|
2719
|
-
|
|
2720
|
-
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
}
|
|
2742
|
-
invocationParams(options) {
|
|
2743
|
-
const optionsWithDefaults = this._combineCallOptions(options);
|
|
2744
|
-
if (this._useResponsesApi(options)) {
|
|
2745
|
-
return this.responses.invocationParams(optionsWithDefaults);
|
|
2746
|
-
}
|
|
2747
|
-
return this.completions.invocationParams(optionsWithDefaults);
|
|
2748
|
-
}
|
|
2749
|
-
/** @ignore */
|
|
2750
|
-
async _generate(messages, options, runManager) {
|
|
2751
|
-
if (this._useResponsesApi(options)) {
|
|
2752
|
-
return this.responses._generate(messages, options);
|
|
2753
|
-
}
|
|
2754
|
-
return this.completions._generate(messages, options, runManager);
|
|
2755
|
-
}
|
|
2756
|
-
async *_streamResponseChunks(messages, options, runManager) {
|
|
2757
|
-
if (this._useResponsesApi(options)) {
|
|
2758
|
-
yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
|
|
2759
|
-
return;
|
|
2760
|
-
}
|
|
2761
|
-
yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
|
|
2762
|
-
}
|
|
2763
|
-
withConfig(config) {
|
|
2764
|
-
const newModel = new ChatOpenAI(this.fields);
|
|
2765
|
-
newModel.defaultOptions = { ...this.defaultOptions, ...config };
|
|
2766
|
-
return newModel;
|
|
2767
|
-
}
|
|
2768
|
-
}
|
|
1359
|
+
* OpenAI chat model integration.
|
|
1360
|
+
*
|
|
1361
|
+
* To use with Azure, import the `AzureChatOpenAI` class.
|
|
1362
|
+
*
|
|
1363
|
+
* Setup:
|
|
1364
|
+
* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
|
|
1365
|
+
*
|
|
1366
|
+
* ```bash
|
|
1367
|
+
* npm install @langchain/openai
|
|
1368
|
+
* export OPENAI_API_KEY="your-api-key"
|
|
1369
|
+
* ```
|
|
1370
|
+
*
|
|
1371
|
+
* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
|
|
1372
|
+
*
|
|
1373
|
+
* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
|
|
1374
|
+
*
|
|
1375
|
+
* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
|
|
1376
|
+
* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:
|
|
1377
|
+
*
|
|
1378
|
+
* ```typescript
|
|
1379
|
+
* // When calling `.withConfig`, call options should be passed via the first argument
|
|
1380
|
+
* const llmWithArgsBound = llm.withConfig({
|
|
1381
|
+
* stop: ["\n"],
|
|
1382
|
+
* tools: [...],
|
|
1383
|
+
* });
|
|
1384
|
+
*
|
|
1385
|
+
* // When calling `.bindTools`, call options should be passed via the second argument
|
|
1386
|
+
* const llmWithTools = llm.bindTools(
|
|
1387
|
+
* [...],
|
|
1388
|
+
* {
|
|
1389
|
+
* tool_choice: "auto",
|
|
1390
|
+
* }
|
|
1391
|
+
* );
|
|
1392
|
+
* ```
|
|
1393
|
+
*
|
|
1394
|
+
* ## Examples
|
|
1395
|
+
*
|
|
1396
|
+
* <details open>
|
|
1397
|
+
* <summary><strong>Instantiate</strong></summary>
|
|
1398
|
+
*
|
|
1399
|
+
* ```typescript
|
|
1400
|
+
* import { ChatOpenAI } from '@langchain/openai';
|
|
1401
|
+
*
|
|
1402
|
+
* const llm = new ChatOpenAI({
|
|
1403
|
+
* model: "gpt-4o-mini",
|
|
1404
|
+
* temperature: 0,
|
|
1405
|
+
* maxTokens: undefined,
|
|
1406
|
+
* timeout: undefined,
|
|
1407
|
+
* maxRetries: 2,
|
|
1408
|
+
* // apiKey: "...",
|
|
1409
|
+
* // baseUrl: "...",
|
|
1410
|
+
* // organization: "...",
|
|
1411
|
+
* // other params...
|
|
1412
|
+
* });
|
|
1413
|
+
* ```
|
|
1414
|
+
* </details>
|
|
1415
|
+
*
|
|
1416
|
+
* <br />
|
|
1417
|
+
*
|
|
1418
|
+
* <details>
|
|
1419
|
+
* <summary><strong>Invoking</strong></summary>
|
|
1420
|
+
*
|
|
1421
|
+
* ```typescript
|
|
1422
|
+
* const input = `Translate "I love programming" into French.`;
|
|
1423
|
+
*
|
|
1424
|
+
* // Models also accept a list of chat messages or a formatted prompt
|
|
1425
|
+
* const result = await llm.invoke(input);
|
|
1426
|
+
* console.log(result);
|
|
1427
|
+
* ```
|
|
1428
|
+
*
|
|
1429
|
+
* ```txt
|
|
1430
|
+
* AIMessage {
|
|
1431
|
+
* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
|
|
1432
|
+
* "content": "J'adore la programmation.",
|
|
1433
|
+
* "response_metadata": {
|
|
1434
|
+
* "tokenUsage": {
|
|
1435
|
+
* "completionTokens": 5,
|
|
1436
|
+
* "promptTokens": 28,
|
|
1437
|
+
* "totalTokens": 33
|
|
1438
|
+
* },
|
|
1439
|
+
* "finish_reason": "stop",
|
|
1440
|
+
* "system_fingerprint": "fp_3aa7262c27"
|
|
1441
|
+
* },
|
|
1442
|
+
* "usage_metadata": {
|
|
1443
|
+
* "input_tokens": 28,
|
|
1444
|
+
* "output_tokens": 5,
|
|
1445
|
+
* "total_tokens": 33
|
|
1446
|
+
* }
|
|
1447
|
+
* }
|
|
1448
|
+
* ```
|
|
1449
|
+
* </details>
|
|
1450
|
+
*
|
|
1451
|
+
* <br />
|
|
1452
|
+
*
|
|
1453
|
+
* <details>
|
|
1454
|
+
* <summary><strong>Streaming Chunks</strong></summary>
|
|
1455
|
+
*
|
|
1456
|
+
* ```typescript
|
|
1457
|
+
* for await (const chunk of await llm.stream(input)) {
|
|
1458
|
+
* console.log(chunk);
|
|
1459
|
+
* }
|
|
1460
|
+
* ```
|
|
1461
|
+
*
|
|
1462
|
+
* ```txt
|
|
1463
|
+
* AIMessageChunk {
|
|
1464
|
+
* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
|
|
1465
|
+
* "content": ""
|
|
1466
|
+
* }
|
|
1467
|
+
* AIMessageChunk {
|
|
1468
|
+
* "content": "J"
|
|
1469
|
+
* }
|
|
1470
|
+
* AIMessageChunk {
|
|
1471
|
+
* "content": "'adore"
|
|
1472
|
+
* }
|
|
1473
|
+
* AIMessageChunk {
|
|
1474
|
+
* "content": " la"
|
|
1475
|
+
* }
|
|
1476
|
+
* AIMessageChunk {
|
|
1477
|
+
* "content": " programmation",,
|
|
1478
|
+
* }
|
|
1479
|
+
* AIMessageChunk {
|
|
1480
|
+
* "content": ".",,
|
|
1481
|
+
* }
|
|
1482
|
+
* AIMessageChunk {
|
|
1483
|
+
* "content": "",
|
|
1484
|
+
* "response_metadata": {
|
|
1485
|
+
* "finish_reason": "stop",
|
|
1486
|
+
* "system_fingerprint": "fp_c9aa9c0491"
|
|
1487
|
+
* },
|
|
1488
|
+
* }
|
|
1489
|
+
* AIMessageChunk {
|
|
1490
|
+
* "content": "",
|
|
1491
|
+
* "usage_metadata": {
|
|
1492
|
+
* "input_tokens": 28,
|
|
1493
|
+
* "output_tokens": 5,
|
|
1494
|
+
* "total_tokens": 33
|
|
1495
|
+
* }
|
|
1496
|
+
* }
|
|
1497
|
+
* ```
|
|
1498
|
+
* </details>
|
|
1499
|
+
*
|
|
1500
|
+
* <br />
|
|
1501
|
+
*
|
|
1502
|
+
* <details>
|
|
1503
|
+
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
|
|
1504
|
+
*
|
|
1505
|
+
* ```typescript
|
|
1506
|
+
* import { AIMessageChunk } from '@langchain/core/messages';
|
|
1507
|
+
* import { concat } from '@langchain/core/utils/stream';
|
|
1508
|
+
*
|
|
1509
|
+
* const stream = await llm.stream(input);
|
|
1510
|
+
* let full: AIMessageChunk | undefined;
|
|
1511
|
+
* for await (const chunk of stream) {
|
|
1512
|
+
* full = !full ? chunk : concat(full, chunk);
|
|
1513
|
+
* }
|
|
1514
|
+
* console.log(full);
|
|
1515
|
+
* ```
|
|
1516
|
+
*
|
|
1517
|
+
* ```txt
|
|
1518
|
+
* AIMessageChunk {
|
|
1519
|
+
* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
|
|
1520
|
+
* "content": "J'adore la programmation.",
|
|
1521
|
+
* "response_metadata": {
|
|
1522
|
+
* "prompt": 0,
|
|
1523
|
+
* "completion": 0,
|
|
1524
|
+
* "finish_reason": "stop",
|
|
1525
|
+
* },
|
|
1526
|
+
* "usage_metadata": {
|
|
1527
|
+
* "input_tokens": 28,
|
|
1528
|
+
* "output_tokens": 5,
|
|
1529
|
+
* "total_tokens": 33
|
|
1530
|
+
* }
|
|
1531
|
+
* }
|
|
1532
|
+
* ```
|
|
1533
|
+
* </details>
|
|
1534
|
+
*
|
|
1535
|
+
* <br />
|
|
1536
|
+
*
|
|
1537
|
+
* <details>
|
|
1538
|
+
* <summary><strong>Bind tools</strong></summary>
|
|
1539
|
+
*
|
|
1540
|
+
* ```typescript
|
|
1541
|
+
* import { z } from 'zod';
|
|
1542
|
+
*
|
|
1543
|
+
* const GetWeather = {
|
|
1544
|
+
* name: "GetWeather",
|
|
1545
|
+
* description: "Get the current weather in a given location",
|
|
1546
|
+
* schema: z.object({
|
|
1547
|
+
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
1548
|
+
* }),
|
|
1549
|
+
* }
|
|
1550
|
+
*
|
|
1551
|
+
* const GetPopulation = {
|
|
1552
|
+
* name: "GetPopulation",
|
|
1553
|
+
* description: "Get the current population in a given location",
|
|
1554
|
+
* schema: z.object({
|
|
1555
|
+
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
1556
|
+
* }),
|
|
1557
|
+
* }
|
|
1558
|
+
*
|
|
1559
|
+
* const llmWithTools = llm.bindTools(
|
|
1560
|
+
* [GetWeather, GetPopulation],
|
|
1561
|
+
* {
|
|
1562
|
+
* // strict: true // enforce tool args schema is respected
|
|
1563
|
+
* }
|
|
1564
|
+
* );
|
|
1565
|
+
* const aiMsg = await llmWithTools.invoke(
|
|
1566
|
+
* "Which city is hotter today and which is bigger: LA or NY?"
|
|
1567
|
+
* );
|
|
1568
|
+
* console.log(aiMsg.tool_calls);
|
|
1569
|
+
* ```
|
|
1570
|
+
*
|
|
1571
|
+
* ```txt
|
|
1572
|
+
* [
|
|
1573
|
+
* {
|
|
1574
|
+
* name: 'GetWeather',
|
|
1575
|
+
* args: { location: 'Los Angeles, CA' },
|
|
1576
|
+
* type: 'tool_call',
|
|
1577
|
+
* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
|
|
1578
|
+
* },
|
|
1579
|
+
* {
|
|
1580
|
+
* name: 'GetWeather',
|
|
1581
|
+
* args: { location: 'New York, NY' },
|
|
1582
|
+
* type: 'tool_call',
|
|
1583
|
+
* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
|
|
1584
|
+
* },
|
|
1585
|
+
* {
|
|
1586
|
+
* name: 'GetPopulation',
|
|
1587
|
+
* args: { location: 'Los Angeles, CA' },
|
|
1588
|
+
* type: 'tool_call',
|
|
1589
|
+
* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
|
|
1590
|
+
* },
|
|
1591
|
+
* {
|
|
1592
|
+
* name: 'GetPopulation',
|
|
1593
|
+
* args: { location: 'New York, NY' },
|
|
1594
|
+
* type: 'tool_call',
|
|
1595
|
+
* id: 'call_s9KQB1UWj45LLGaEnjz0179q'
|
|
1596
|
+
* }
|
|
1597
|
+
* ]
|
|
1598
|
+
* ```
|
|
1599
|
+
* </details>
|
|
1600
|
+
*
|
|
1601
|
+
* <br />
|
|
1602
|
+
*
|
|
1603
|
+
* <details>
|
|
1604
|
+
* <summary><strong>Structured Output</strong></summary>
|
|
1605
|
+
*
|
|
1606
|
+
* ```typescript
|
|
1607
|
+
* import { z } from 'zod';
|
|
1608
|
+
*
|
|
1609
|
+
* const Joke = z.object({
|
|
1610
|
+
* setup: z.string().describe("The setup of the joke"),
|
|
1611
|
+
* punchline: z.string().describe("The punchline to the joke"),
|
|
1612
|
+
* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10")
|
|
1613
|
+
* }).describe('Joke to tell user.');
|
|
1614
|
+
*
|
|
1615
|
+
* const structuredLlm = llm.withStructuredOutput(Joke, {
|
|
1616
|
+
* name: "Joke",
|
|
1617
|
+
* strict: true, // Optionally enable OpenAI structured outputs
|
|
1618
|
+
* });
|
|
1619
|
+
* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
|
|
1620
|
+
* console.log(jokeResult);
|
|
1621
|
+
* ```
|
|
1622
|
+
*
|
|
1623
|
+
* ```txt
|
|
1624
|
+
* {
|
|
1625
|
+
* setup: 'Why was the cat sitting on the computer?',
|
|
1626
|
+
* punchline: 'Because it wanted to keep an eye on the mouse!',
|
|
1627
|
+
* rating: 7
|
|
1628
|
+
* }
|
|
1629
|
+
* ```
|
|
1630
|
+
* </details>
|
|
1631
|
+
*
|
|
1632
|
+
* <br />
|
|
1633
|
+
*
|
|
1634
|
+
* <details>
|
|
1635
|
+
* <summary><strong>JSON Object Response Format</strong></summary>
|
|
1636
|
+
*
|
|
1637
|
+
* ```typescript
|
|
1638
|
+
* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } });
|
|
1639
|
+
* const jsonLlmAiMsg = await jsonLlm.invoke(
|
|
1640
|
+
* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
|
|
1641
|
+
* );
|
|
1642
|
+
* console.log(jsonLlmAiMsg.content);
|
|
1643
|
+
* ```
|
|
1644
|
+
*
|
|
1645
|
+
* ```txt
|
|
1646
|
+
* {
|
|
1647
|
+
* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
|
|
1648
|
+
* }
|
|
1649
|
+
* ```
|
|
1650
|
+
* </details>
|
|
1651
|
+
*
|
|
1652
|
+
* <br />
|
|
1653
|
+
*
|
|
1654
|
+
* <details>
|
|
1655
|
+
* <summary><strong>Multimodal</strong></summary>
|
|
1656
|
+
*
|
|
1657
|
+
* ```typescript
|
|
1658
|
+
* import { HumanMessage } from '@langchain/core/messages';
|
|
1659
|
+
*
|
|
1660
|
+
* const imageUrl = "https://example.com/image.jpg";
|
|
1661
|
+
* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
|
|
1662
|
+
* const base64Image = Buffer.from(imageData).toString('base64');
|
|
1663
|
+
*
|
|
1664
|
+
* const message = new HumanMessage({
|
|
1665
|
+
* content: [
|
|
1666
|
+
* { type: "text", text: "describe the weather in this image" },
|
|
1667
|
+
* {
|
|
1668
|
+
* type: "image_url",
|
|
1669
|
+
* image_url: { url: `data:image/jpeg;base64,${base64Image}` },
|
|
1670
|
+
* },
|
|
1671
|
+
* ]
|
|
1672
|
+
* });
|
|
1673
|
+
*
|
|
1674
|
+
* const imageDescriptionAiMsg = await llm.invoke([message]);
|
|
1675
|
+
* console.log(imageDescriptionAiMsg.content);
|
|
1676
|
+
* ```
|
|
1677
|
+
*
|
|
1678
|
+
* ```txt
|
|
1679
|
+
* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.
|
|
1680
|
+
* ```
|
|
1681
|
+
* </details>
|
|
1682
|
+
*
|
|
1683
|
+
* <br />
|
|
1684
|
+
*
|
|
1685
|
+
* <details>
|
|
1686
|
+
* <summary><strong>Usage Metadata</strong></summary>
|
|
1687
|
+
*
|
|
1688
|
+
* ```typescript
|
|
1689
|
+
* const aiMsgForMetadata = await llm.invoke(input);
|
|
1690
|
+
* console.log(aiMsgForMetadata.usage_metadata);
|
|
1691
|
+
* ```
|
|
1692
|
+
*
|
|
1693
|
+
* ```txt
|
|
1694
|
+
* { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
|
|
1695
|
+
* ```
|
|
1696
|
+
* </details>
|
|
1697
|
+
*
|
|
1698
|
+
* <br />
|
|
1699
|
+
*
|
|
1700
|
+
* <details>
|
|
1701
|
+
* <summary><strong>Logprobs</strong></summary>
|
|
1702
|
+
*
|
|
1703
|
+
* ```typescript
|
|
1704
|
+
* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true });
|
|
1705
|
+
* const aiMsgForLogprobs = await logprobsLlm.invoke(input);
|
|
1706
|
+
* console.log(aiMsgForLogprobs.response_metadata.logprobs);
|
|
1707
|
+
* ```
|
|
1708
|
+
*
|
|
1709
|
+
* ```txt
|
|
1710
|
+
* {
|
|
1711
|
+
* content: [
|
|
1712
|
+
* {
|
|
1713
|
+
* token: 'J',
|
|
1714
|
+
* logprob: -0.000050616763,
|
|
1715
|
+
* bytes: [Array],
|
|
1716
|
+
* top_logprobs: []
|
|
1717
|
+
* },
|
|
1718
|
+
* {
|
|
1719
|
+
* token: "'",
|
|
1720
|
+
* logprob: -0.01868736,
|
|
1721
|
+
* bytes: [Array],
|
|
1722
|
+
* top_logprobs: []
|
|
1723
|
+
* },
|
|
1724
|
+
* {
|
|
1725
|
+
* token: 'ad',
|
|
1726
|
+
* logprob: -0.0000030545007,
|
|
1727
|
+
* bytes: [Array],
|
|
1728
|
+
* top_logprobs: []
|
|
1729
|
+
* },
|
|
1730
|
+
* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
1731
|
+
* {
|
|
1732
|
+
* token: ' la',
|
|
1733
|
+
* logprob: -0.515404,
|
|
1734
|
+
* bytes: [Array],
|
|
1735
|
+
* top_logprobs: []
|
|
1736
|
+
* },
|
|
1737
|
+
* {
|
|
1738
|
+
* token: ' programm',
|
|
1739
|
+
* logprob: -0.0000118755715,
|
|
1740
|
+
* bytes: [Array],
|
|
1741
|
+
* top_logprobs: []
|
|
1742
|
+
* },
|
|
1743
|
+
* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
1744
|
+
* {
|
|
1745
|
+
* token: '.',
|
|
1746
|
+
* logprob: -0.0000037697225,
|
|
1747
|
+
* bytes: [Array],
|
|
1748
|
+
* top_logprobs: []
|
|
1749
|
+
* }
|
|
1750
|
+
* ],
|
|
1751
|
+
* refusal: null
|
|
1752
|
+
* }
|
|
1753
|
+
* ```
|
|
1754
|
+
* </details>
|
|
1755
|
+
*
|
|
1756
|
+
* <br />
|
|
1757
|
+
*
|
|
1758
|
+
* <details>
|
|
1759
|
+
* <summary><strong>Response Metadata</strong></summary>
|
|
1760
|
+
*
|
|
1761
|
+
* ```typescript
|
|
1762
|
+
* const aiMsgForResponseMetadata = await llm.invoke(input);
|
|
1763
|
+
* console.log(aiMsgForResponseMetadata.response_metadata);
|
|
1764
|
+
* ```
|
|
1765
|
+
*
|
|
1766
|
+
* ```txt
|
|
1767
|
+
* {
|
|
1768
|
+
* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
|
|
1769
|
+
* finish_reason: 'stop',
|
|
1770
|
+
* system_fingerprint: 'fp_3aa7262c27'
|
|
1771
|
+
* }
|
|
1772
|
+
* ```
|
|
1773
|
+
* </details>
|
|
1774
|
+
*
|
|
1775
|
+
* <br />
|
|
1776
|
+
*
|
|
1777
|
+
* <details>
|
|
1778
|
+
* <summary><strong>JSON Schema Structured Output</strong></summary>
|
|
1779
|
+
*
|
|
1780
|
+
* ```typescript
|
|
1781
|
+
* const llmForJsonSchema = new ChatOpenAI({
|
|
1782
|
+
* model: "gpt-4o-2024-08-06",
|
|
1783
|
+
* }).withStructuredOutput(
|
|
1784
|
+
* z.object({
|
|
1785
|
+
* command: z.string().describe("The command to execute"),
|
|
1786
|
+
* expectedOutput: z.string().describe("The expected output of the command"),
|
|
1787
|
+
* options: z
|
|
1788
|
+
* .array(z.string())
|
|
1789
|
+
* .describe("The options you can pass to the command"),
|
|
1790
|
+
* }),
|
|
1791
|
+
* {
|
|
1792
|
+
* method: "jsonSchema",
|
|
1793
|
+
* strict: true, // Optional when using the `jsonSchema` method
|
|
1794
|
+
* }
|
|
1795
|
+
* );
|
|
1796
|
+
*
|
|
1797
|
+
* const jsonSchemaRes = await llmForJsonSchema.invoke(
|
|
1798
|
+
* "What is the command to list files in a directory?"
|
|
1799
|
+
* );
|
|
1800
|
+
* console.log(jsonSchemaRes);
|
|
1801
|
+
* ```
|
|
1802
|
+
*
|
|
1803
|
+
* ```txt
|
|
1804
|
+
* {
|
|
1805
|
+
* command: 'ls',
|
|
1806
|
+
* expectedOutput: 'A list of files and subdirectories within the specified directory.',
|
|
1807
|
+
* options: [
|
|
1808
|
+
* '-a: include directory entries whose names begin with a dot (.).',
|
|
1809
|
+
* '-l: use a long listing format.',
|
|
1810
|
+
* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).',
|
|
1811
|
+
* '-t: sort by time, newest first.',
|
|
1812
|
+
* '-r: reverse order while sorting.',
|
|
1813
|
+
* '-S: sort by file size, largest first.',
|
|
1814
|
+
* '-R: list subdirectories recursively.'
|
|
1815
|
+
* ]
|
|
1816
|
+
* }
|
|
1817
|
+
* ```
|
|
1818
|
+
* </details>
|
|
1819
|
+
*
|
|
1820
|
+
* <br />
|
|
1821
|
+
*
|
|
1822
|
+
* <details>
|
|
1823
|
+
* <summary><strong>Audio Outputs</strong></summary>
|
|
1824
|
+
*
|
|
1825
|
+
* ```typescript
|
|
1826
|
+
* import { ChatOpenAI } from "@langchain/openai";
|
|
1827
|
+
*
|
|
1828
|
+
* const modelWithAudioOutput = new ChatOpenAI({
|
|
1829
|
+
* model: "gpt-4o-audio-preview",
|
|
1830
|
+
* // You may also pass these fields to `.withConfig` as a call argument.
|
|
1831
|
+
* modalities: ["text", "audio"], // Specifies that the model should output audio.
|
|
1832
|
+
* audio: {
|
|
1833
|
+
* voice: "alloy",
|
|
1834
|
+
* format: "wav",
|
|
1835
|
+
* },
|
|
1836
|
+
* });
|
|
1837
|
+
*
|
|
1838
|
+
* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats.");
|
|
1839
|
+
* const castMessageContent = audioOutputResult.content[0] as Record<string, any>;
|
|
1840
|
+
*
|
|
1841
|
+
* console.log({
|
|
1842
|
+
* ...castMessageContent,
|
|
1843
|
+
* data: castMessageContent.data.slice(0, 100) // Sliced for brevity
|
|
1844
|
+
* })
|
|
1845
|
+
* ```
|
|
1846
|
+
*
|
|
1847
|
+
* ```txt
|
|
1848
|
+
* {
|
|
1849
|
+
* id: 'audio_67117718c6008190a3afad3e3054b9b6',
|
|
1850
|
+
* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',
|
|
1851
|
+
* expires_at: 1729201448,
|
|
1852
|
+
* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'
|
|
1853
|
+
* }
|
|
1854
|
+
* ```
|
|
1855
|
+
* </details>
|
|
1856
|
+
*
|
|
1857
|
+
* <br />
|
|
1858
|
+
*
|
|
1859
|
+
* <details>
|
|
1860
|
+
* <summary><strong>Audio Outputs</strong></summary>
|
|
1861
|
+
*
|
|
1862
|
+
* ```typescript
|
|
1863
|
+
* import { ChatOpenAI } from "@langchain/openai";
|
|
1864
|
+
*
|
|
1865
|
+
* const modelWithAudioOutput = new ChatOpenAI({
|
|
1866
|
+
* model: "gpt-4o-audio-preview",
|
|
1867
|
+
* // You may also pass these fields to `.withConfig` as a call argument.
|
|
1868
|
+
* modalities: ["text", "audio"], // Specifies that the model should output audio.
|
|
1869
|
+
* audio: {
|
|
1870
|
+
* voice: "alloy",
|
|
1871
|
+
* format: "wav",
|
|
1872
|
+
* },
|
|
1873
|
+
* });
|
|
1874
|
+
*
|
|
1875
|
+
* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats.");
|
|
1876
|
+
* const castAudioContent = audioOutputResult.additional_kwargs.audio as Record<string, any>;
|
|
1877
|
+
*
|
|
1878
|
+
* console.log({
|
|
1879
|
+
* ...castAudioContent,
|
|
1880
|
+
* data: castAudioContent.data.slice(0, 100) // Sliced for brevity
|
|
1881
|
+
* })
|
|
1882
|
+
* ```
|
|
1883
|
+
*
|
|
1884
|
+
* ```txt
|
|
1885
|
+
* {
|
|
1886
|
+
* id: 'audio_67117718c6008190a3afad3e3054b9b6',
|
|
1887
|
+
* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',
|
|
1888
|
+
* expires_at: 1729201448,
|
|
1889
|
+
* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'
|
|
1890
|
+
* }
|
|
1891
|
+
* ```
|
|
1892
|
+
* </details>
|
|
1893
|
+
*
|
|
1894
|
+
* <br />
|
|
1895
|
+
*/
|
|
1896
|
+
var ChatOpenAI = class ChatOpenAI extends BaseChatOpenAI {
|
|
1897
|
+
/**
|
|
1898
|
+
* Whether to use the responses API for all requests. If `false` the responses API will be used
|
|
1899
|
+
* only when required in order to fulfill the request.
|
|
1900
|
+
*/
|
|
1901
|
+
useResponsesApi = false;
|
|
1902
|
+
responses;
|
|
1903
|
+
completions;
|
|
1904
|
+
get lc_serializable_keys() {
|
|
1905
|
+
return [...super.lc_serializable_keys, "useResponsesApi"];
|
|
1906
|
+
}
|
|
1907
|
+
constructor(fields) {
|
|
1908
|
+
super(fields);
|
|
1909
|
+
this.fields = fields;
|
|
1910
|
+
this.useResponsesApi = fields?.useResponsesApi ?? false;
|
|
1911
|
+
this.responses = fields?.responses ?? new ChatOpenAIResponses(fields);
|
|
1912
|
+
this.completions = fields?.completions ?? new ChatOpenAICompletions(fields);
|
|
1913
|
+
}
|
|
1914
|
+
_useResponsesApi(options) {
|
|
1915
|
+
const usesBuiltInTools = options?.tools?.some(require_tools.isBuiltInTool);
|
|
1916
|
+
const hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null;
|
|
1917
|
+
const hasCustomTools = options?.tools?.some(require_tools.isOpenAICustomTool);
|
|
1918
|
+
return this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools;
|
|
1919
|
+
}
|
|
1920
|
+
getLsParams(options) {
|
|
1921
|
+
const optionsWithDefaults = this._combineCallOptions(options);
|
|
1922
|
+
if (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults);
|
|
1923
|
+
return this.completions.getLsParams(optionsWithDefaults);
|
|
1924
|
+
}
|
|
1925
|
+
invocationParams(options) {
|
|
1926
|
+
const optionsWithDefaults = this._combineCallOptions(options);
|
|
1927
|
+
if (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults);
|
|
1928
|
+
return this.completions.invocationParams(optionsWithDefaults);
|
|
1929
|
+
}
|
|
1930
|
+
/** @ignore */
|
|
1931
|
+
async _generate(messages, options, runManager) {
|
|
1932
|
+
if (this._useResponsesApi(options)) return this.responses._generate(messages, options);
|
|
1933
|
+
return this.completions._generate(messages, options, runManager);
|
|
1934
|
+
}
|
|
1935
|
+
async *_streamResponseChunks(messages, options, runManager) {
|
|
1936
|
+
if (this._useResponsesApi(options)) {
|
|
1937
|
+
yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
|
|
1938
|
+
return;
|
|
1939
|
+
}
|
|
1940
|
+
yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
|
|
1941
|
+
}
|
|
1942
|
+
withConfig(config) {
|
|
1943
|
+
const newModel = new ChatOpenAI(this.fields);
|
|
1944
|
+
newModel.defaultOptions = {
|
|
1945
|
+
...this.defaultOptions,
|
|
1946
|
+
...config
|
|
1947
|
+
};
|
|
1948
|
+
return newModel;
|
|
1949
|
+
}
|
|
1950
|
+
};
|
|
1951
|
+
|
|
1952
|
+
//#endregion
|
|
1953
|
+
exports.BaseChatOpenAI = BaseChatOpenAI;
|
|
2769
1954
|
exports.ChatOpenAI = ChatOpenAI;
|
|
1955
|
+
exports.ChatOpenAICompletions = ChatOpenAICompletions;
|
|
1956
|
+
exports.ChatOpenAIResponses = ChatOpenAIResponses;
|
|
1957
|
+
//# sourceMappingURL=chat_models.cjs.map
|