@langchain/openai 1.0.0-alpha.2 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/LICENSE +6 -6
- package/dist/azure/chat_models/common.cjs +130 -0
- package/dist/azure/chat_models/common.cjs.map +1 -0
- package/dist/azure/chat_models/common.d.cts +16 -0
- package/dist/azure/chat_models/common.d.cts.map +1 -0
- package/dist/azure/chat_models/common.d.ts +16 -0
- package/dist/azure/chat_models/common.d.ts.map +1 -0
- package/dist/azure/chat_models/common.js +124 -0
- package/dist/azure/chat_models/common.js.map +1 -0
- package/dist/azure/chat_models/completions.cjs +50 -0
- package/dist/azure/chat_models/completions.cjs.map +1 -0
- package/dist/azure/chat_models/completions.d.cts +29 -0
- package/dist/azure/chat_models/completions.d.cts.map +1 -0
- package/dist/azure/chat_models/completions.d.ts +29 -0
- package/dist/azure/chat_models/completions.d.ts.map +1 -0
- package/dist/azure/chat_models/completions.js +50 -0
- package/dist/azure/chat_models/completions.js.map +1 -0
- package/dist/azure/{chat_models.cjs → chat_models/index.cjs} +14 -214
- package/dist/azure/chat_models/index.cjs.map +1 -0
- package/dist/azure/{chat_models.d.ts → chat_models/index.d.cts} +6 -11
- package/dist/azure/chat_models/index.d.cts.map +1 -0
- package/dist/azure/{chat_models.d.cts → chat_models/index.d.ts} +6 -11
- package/dist/azure/chat_models/index.d.ts.map +1 -0
- package/dist/azure/{chat_models.js → chat_models/index.js} +6 -205
- package/dist/azure/chat_models/index.js.map +1 -0
- package/dist/azure/chat_models/responses.cjs +50 -0
- package/dist/azure/chat_models/responses.cjs.map +1 -0
- package/dist/azure/chat_models/responses.d.cts +29 -0
- package/dist/azure/chat_models/responses.d.cts.map +1 -0
- package/dist/azure/chat_models/responses.d.ts +29 -0
- package/dist/azure/chat_models/responses.d.ts.map +1 -0
- package/dist/azure/chat_models/responses.js +50 -0
- package/dist/azure/chat_models/responses.js.map +1 -0
- package/dist/chat_models/base.cjs +533 -0
- package/dist/chat_models/base.cjs.map +1 -0
- package/dist/chat_models/base.d.cts +272 -0
- package/dist/chat_models/base.d.cts.map +1 -0
- package/dist/chat_models/base.d.ts +272 -0
- package/dist/chat_models/base.d.ts.map +1 -0
- package/dist/chat_models/base.js +532 -0
- package/dist/chat_models/base.js.map +1 -0
- package/dist/chat_models/completions.cjs +328 -0
- package/dist/chat_models/completions.cjs.map +1 -0
- package/dist/chat_models/completions.d.cts +33 -0
- package/dist/chat_models/completions.d.cts.map +1 -0
- package/dist/chat_models/completions.d.ts +33 -0
- package/dist/chat_models/completions.d.ts.map +1 -0
- package/dist/chat_models/completions.js +327 -0
- package/dist/chat_models/completions.js.map +1 -0
- package/dist/chat_models/index.cjs +608 -0
- package/dist/chat_models/index.cjs.map +1 -0
- package/dist/chat_models/index.d.cts +593 -0
- package/dist/chat_models/index.d.cts.map +1 -0
- package/dist/chat_models/index.d.ts +593 -0
- package/dist/chat_models/index.d.ts.map +1 -0
- package/dist/chat_models/index.js +608 -0
- package/dist/chat_models/index.js.map +1 -0
- package/dist/chat_models/responses.cjs +550 -0
- package/dist/chat_models/responses.cjs.map +1 -0
- package/dist/chat_models/responses.d.cts +77 -0
- package/dist/chat_models/responses.d.cts.map +1 -0
- package/dist/chat_models/responses.d.ts +77 -0
- package/dist/chat_models/responses.d.ts.map +1 -0
- package/dist/chat_models/responses.js +549 -0
- package/dist/chat_models/responses.js.map +1 -0
- package/dist/index.cjs +14 -7
- package/dist/index.d.cts +9 -3
- package/dist/index.d.ts +9 -3
- package/dist/index.js +8 -3
- package/dist/langchain-core/dist/callbacks/base.d.ts +1 -0
- package/dist/langchain-core/dist/callbacks/manager.d.ts +2 -0
- package/dist/langchain-core/dist/language_models/base.d.ts +5 -0
- package/dist/langchain-core/dist/language_models/chat_models.d.cts +13 -0
- package/dist/langchain-core/dist/language_models/chat_models.d.cts.map +1 -0
- package/dist/langchain-core/dist/language_models/chat_models.d.ts +20 -0
- package/dist/langchain-core/dist/language_models/chat_models.d.ts.map +1 -0
- package/dist/langchain-core/dist/runnables/base.d.ts +7 -0
- package/dist/langchain-core/dist/runnables/graph.d.ts +1 -0
- package/dist/langchain-core/dist/runnables/types.d.ts +2 -0
- package/dist/langchain-core/dist/tools/types.d.ts +5 -0
- package/dist/langchain-core/dist/tracers/base.d.ts +2 -0
- package/dist/langchain-core/dist/tracers/event_stream.d.ts +1 -0
- package/dist/langchain-core/dist/tracers/log_stream.d.ts +3 -0
- package/dist/langchain-core/dist/utils/types/index.d.ts +1 -0
- package/dist/langchain-core/dist/utils/types/zod.d.ts +1 -0
- package/dist/llms.cjs +1 -1
- package/dist/llms.d.cts +1 -1
- package/dist/llms.js +1 -1
- package/dist/utils/message_inputs.cjs +1 -1
- package/dist/utils/message_inputs.js +1 -1
- package/dist/utils/misc.cjs +4 -1
- package/dist/utils/misc.cjs.map +1 -1
- package/dist/utils/misc.d.cts.map +1 -1
- package/dist/utils/misc.d.ts.map +1 -1
- package/dist/utils/misc.js +4 -1
- package/dist/utils/misc.js.map +1 -1
- package/package.json +11 -10
- package/dist/azure/chat_models.cjs.map +0 -1
- package/dist/azure/chat_models.d.cts.map +0 -1
- package/dist/azure/chat_models.d.ts.map +0 -1
- package/dist/azure/chat_models.js.map +0 -1
- package/dist/chat_models.cjs +0 -1965
- package/dist/chat_models.cjs.map +0 -1
- package/dist/chat_models.d.cts +0 -931
- package/dist/chat_models.d.cts.map +0 -1
- package/dist/chat_models.d.ts +0 -931
- package/dist/chat_models.d.ts.map +0 -1
- package/dist/chat_models.js +0 -1961
- package/dist/chat_models.js.map +0 -1
package/dist/chat_models.js
DELETED
|
@@ -1,1961 +0,0 @@
|
|
|
1
|
-
import { iife, isReasoningModel, messageToOpenAIRole } from "./utils/misc.js";
|
|
2
|
-
import { getEndpoint } from "./utils/azure.js";
|
|
3
|
-
import { wrapOpenAIClientError } from "./utils/client.js";
|
|
4
|
-
import { _convertToOpenAITool, convertCompletionsCustomTool, convertResponsesCustomTool, formatFunctionDefinitions, formatToOpenAIToolChoice, isBuiltInTool, isBuiltInToolChoice, isCustomTool, isCustomToolCall, isOpenAICustomTool, parseCustomToolCall } from "./utils/tools.js";
|
|
5
|
-
import { _convertOpenAIResponsesUsageToLangChainUsage, getStructuredOutputMethod, handleMultiModalOutput, interopZodResponseFormat } from "./utils/output.js";
|
|
6
|
-
import { _convertToResponsesMessageFromV1 } from "./utils/standard.js";
|
|
7
|
-
import { _convertMessagesToOpenAIParams, completionsApiContentBlockConverter } from "./utils/message_inputs.js";
|
|
8
|
-
import { OpenAI as OpenAI$1 } from "openai";
|
|
9
|
-
import { AIMessage, AIMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessageChunk, HumanMessageChunk, SystemMessageChunk, ToolMessageChunk, convertToProviderContentBlock, isAIMessage, isDataContentBlock } from "@langchain/core/messages";
|
|
10
|
-
import { ChatGenerationChunk } from "@langchain/core/outputs";
|
|
11
|
-
import { getEnvironmentVariable } from "@langchain/core/utils/env";
|
|
12
|
-
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
|
|
13
|
-
import { isOpenAITool } from "@langchain/core/language_models/base";
|
|
14
|
-
import { RunnableLambda, RunnablePassthrough, RunnableSequence } from "@langchain/core/runnables";
|
|
15
|
-
import { JsonOutputParser, StructuredOutputParser } from "@langchain/core/output_parsers";
|
|
16
|
-
import { JsonOutputKeyToolsParser, makeInvalidToolCall, parseToolCall } from "@langchain/core/output_parsers/openai_tools";
|
|
17
|
-
import { getSchemaDescription, isInteropZodSchema } from "@langchain/core/utils/types";
|
|
18
|
-
import { toJsonSchema } from "@langchain/core/utils/json_schema";
|
|
19
|
-
|
|
20
|
-
//#region src/chat_models.ts
|
|
21
|
-
const _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__";
|
|
22
|
-
/** @internal */
|
|
23
|
-
var BaseChatOpenAI = class extends BaseChatModel {
|
|
24
|
-
temperature;
|
|
25
|
-
topP;
|
|
26
|
-
frequencyPenalty;
|
|
27
|
-
presencePenalty;
|
|
28
|
-
n;
|
|
29
|
-
logitBias;
|
|
30
|
-
model = "gpt-3.5-turbo";
|
|
31
|
-
modelKwargs;
|
|
32
|
-
stop;
|
|
33
|
-
stopSequences;
|
|
34
|
-
user;
|
|
35
|
-
timeout;
|
|
36
|
-
streaming = false;
|
|
37
|
-
streamUsage = true;
|
|
38
|
-
maxTokens;
|
|
39
|
-
logprobs;
|
|
40
|
-
topLogprobs;
|
|
41
|
-
apiKey;
|
|
42
|
-
organization;
|
|
43
|
-
__includeRawResponse;
|
|
44
|
-
/** @internal */
|
|
45
|
-
client;
|
|
46
|
-
/** @internal */
|
|
47
|
-
clientConfig;
|
|
48
|
-
/**
|
|
49
|
-
* Whether the model supports the `strict` argument when passing in tools.
|
|
50
|
-
* If `undefined` the `strict` argument will not be passed to OpenAI.
|
|
51
|
-
*/
|
|
52
|
-
supportsStrictToolCalling;
|
|
53
|
-
audio;
|
|
54
|
-
modalities;
|
|
55
|
-
reasoning;
|
|
56
|
-
/**
|
|
57
|
-
* Must be set to `true` in tenancies with Zero Data Retention. Setting to `true` will disable
|
|
58
|
-
* output storage in the Responses API, but this DOES NOT enable Zero Data Retention in your
|
|
59
|
-
* OpenAI organization or project. This must be configured directly with OpenAI.
|
|
60
|
-
*
|
|
61
|
-
* See:
|
|
62
|
-
* https://platform.openai.com/docs/guides/your-data
|
|
63
|
-
* https://platform.openai.com/docs/api-reference/responses/create#responses-create-store
|
|
64
|
-
*
|
|
65
|
-
* @default false
|
|
66
|
-
*/
|
|
67
|
-
zdrEnabled;
|
|
68
|
-
/**
|
|
69
|
-
* Service tier to use for this request. Can be "auto", "default", or "flex" or "priority".
|
|
70
|
-
* Specifies the service tier for prioritization and latency optimization.
|
|
71
|
-
*/
|
|
72
|
-
service_tier;
|
|
73
|
-
/**
|
|
74
|
-
* Used by OpenAI to cache responses for similar requests to optimize your cache
|
|
75
|
-
* hit rates.
|
|
76
|
-
* [Learn more](https://platform.openai.com/docs/guides/prompt-caching).
|
|
77
|
-
*/
|
|
78
|
-
promptCacheKey;
|
|
79
|
-
/**
|
|
80
|
-
* The verbosity of the model's response.
|
|
81
|
-
*/
|
|
82
|
-
verbosity;
|
|
83
|
-
defaultOptions;
|
|
84
|
-
_llmType() {
|
|
85
|
-
return "openai";
|
|
86
|
-
}
|
|
87
|
-
static lc_name() {
|
|
88
|
-
return "ChatOpenAI";
|
|
89
|
-
}
|
|
90
|
-
get callKeys() {
|
|
91
|
-
return [
|
|
92
|
-
...super.callKeys,
|
|
93
|
-
"options",
|
|
94
|
-
"function_call",
|
|
95
|
-
"functions",
|
|
96
|
-
"tools",
|
|
97
|
-
"tool_choice",
|
|
98
|
-
"promptIndex",
|
|
99
|
-
"response_format",
|
|
100
|
-
"seed",
|
|
101
|
-
"reasoning",
|
|
102
|
-
"service_tier"
|
|
103
|
-
];
|
|
104
|
-
}
|
|
105
|
-
lc_serializable = true;
|
|
106
|
-
get lc_secrets() {
|
|
107
|
-
return {
|
|
108
|
-
apiKey: "OPENAI_API_KEY",
|
|
109
|
-
organization: "OPENAI_ORGANIZATION"
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
get lc_aliases() {
|
|
113
|
-
return {
|
|
114
|
-
apiKey: "openai_api_key",
|
|
115
|
-
modelName: "model"
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
get lc_serializable_keys() {
|
|
119
|
-
return [
|
|
120
|
-
"configuration",
|
|
121
|
-
"logprobs",
|
|
122
|
-
"topLogprobs",
|
|
123
|
-
"prefixMessages",
|
|
124
|
-
"supportsStrictToolCalling",
|
|
125
|
-
"modalities",
|
|
126
|
-
"audio",
|
|
127
|
-
"temperature",
|
|
128
|
-
"maxTokens",
|
|
129
|
-
"topP",
|
|
130
|
-
"frequencyPenalty",
|
|
131
|
-
"presencePenalty",
|
|
132
|
-
"n",
|
|
133
|
-
"logitBias",
|
|
134
|
-
"user",
|
|
135
|
-
"streaming",
|
|
136
|
-
"streamUsage",
|
|
137
|
-
"model",
|
|
138
|
-
"modelName",
|
|
139
|
-
"modelKwargs",
|
|
140
|
-
"stop",
|
|
141
|
-
"stopSequences",
|
|
142
|
-
"timeout",
|
|
143
|
-
"apiKey",
|
|
144
|
-
"cache",
|
|
145
|
-
"maxConcurrency",
|
|
146
|
-
"maxRetries",
|
|
147
|
-
"verbose",
|
|
148
|
-
"callbacks",
|
|
149
|
-
"tags",
|
|
150
|
-
"metadata",
|
|
151
|
-
"disableStreaming",
|
|
152
|
-
"zdrEnabled",
|
|
153
|
-
"reasoning",
|
|
154
|
-
"promptCacheKey",
|
|
155
|
-
"verbosity"
|
|
156
|
-
];
|
|
157
|
-
}
|
|
158
|
-
getLsParams(options) {
|
|
159
|
-
const params = this.invocationParams(options);
|
|
160
|
-
return {
|
|
161
|
-
ls_provider: "openai",
|
|
162
|
-
ls_model_name: this.model,
|
|
163
|
-
ls_model_type: "chat",
|
|
164
|
-
ls_temperature: params.temperature ?? void 0,
|
|
165
|
-
ls_max_tokens: params.max_tokens ?? void 0,
|
|
166
|
-
ls_stop: options.stop
|
|
167
|
-
};
|
|
168
|
-
}
|
|
169
|
-
/** @ignore */
|
|
170
|
-
_identifyingParams() {
|
|
171
|
-
return {
|
|
172
|
-
model_name: this.model,
|
|
173
|
-
...this.invocationParams(),
|
|
174
|
-
...this.clientConfig
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
/**
|
|
178
|
-
* Get the identifying parameters for the model
|
|
179
|
-
*/
|
|
180
|
-
identifyingParams() {
|
|
181
|
-
return this._identifyingParams();
|
|
182
|
-
}
|
|
183
|
-
constructor(fields) {
|
|
184
|
-
super(fields ?? {});
|
|
185
|
-
this.apiKey = fields?.apiKey ?? fields?.configuration?.apiKey ?? getEnvironmentVariable("OPENAI_API_KEY");
|
|
186
|
-
this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION");
|
|
187
|
-
this.model = fields?.model ?? fields?.modelName ?? this.model;
|
|
188
|
-
this.modelKwargs = fields?.modelKwargs ?? {};
|
|
189
|
-
this.timeout = fields?.timeout;
|
|
190
|
-
this.temperature = fields?.temperature ?? this.temperature;
|
|
191
|
-
this.topP = fields?.topP ?? this.topP;
|
|
192
|
-
this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;
|
|
193
|
-
this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;
|
|
194
|
-
this.logprobs = fields?.logprobs;
|
|
195
|
-
this.topLogprobs = fields?.topLogprobs;
|
|
196
|
-
this.n = fields?.n ?? this.n;
|
|
197
|
-
this.logitBias = fields?.logitBias;
|
|
198
|
-
this.stop = fields?.stopSequences ?? fields?.stop;
|
|
199
|
-
this.stopSequences = this.stop;
|
|
200
|
-
this.user = fields?.user;
|
|
201
|
-
this.__includeRawResponse = fields?.__includeRawResponse;
|
|
202
|
-
this.audio = fields?.audio;
|
|
203
|
-
this.modalities = fields?.modalities;
|
|
204
|
-
this.reasoning = fields?.reasoning;
|
|
205
|
-
this.maxTokens = fields?.maxCompletionTokens ?? fields?.maxTokens;
|
|
206
|
-
this.promptCacheKey = fields?.promptCacheKey ?? this.promptCacheKey;
|
|
207
|
-
this.verbosity = fields?.verbosity ?? this.verbosity;
|
|
208
|
-
this.disableStreaming = fields?.disableStreaming === true;
|
|
209
|
-
this.streaming = fields?.streaming === true;
|
|
210
|
-
if (this.disableStreaming) this.streaming = false;
|
|
211
|
-
if (fields?.streaming === false) this.disableStreaming = true;
|
|
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 (!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 && isInteropZodSchema(resFormat.json_schema.schema)) return 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 = 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$1(params);
|
|
268
|
-
}
|
|
269
|
-
const requestOptions = {
|
|
270
|
-
...this.clientConfig,
|
|
271
|
-
...options
|
|
272
|
-
};
|
|
273
|
-
return requestOptions;
|
|
274
|
-
}
|
|
275
|
-
_convertChatOpenAIToolToCompletionsTool(tool, fields) {
|
|
276
|
-
if (isCustomTool(tool)) return convertResponsesCustomTool(tool.metadata.customTool);
|
|
277
|
-
if (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 _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) => 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(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 = 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 = getStructuredOutputMethod(this.model, config?.method);
|
|
411
|
-
if (method === "jsonMode") {
|
|
412
|
-
if (isInteropZodSchema(schema)) outputParser = StructuredOutputParser.fromZodSchema(schema);
|
|
413
|
-
else outputParser = new JsonOutputParser();
|
|
414
|
-
const asJsonSchema = 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: getSchemaDescription(schema),
|
|
429
|
-
schema,
|
|
430
|
-
strict: config?.strict
|
|
431
|
-
};
|
|
432
|
-
const asJsonSchema = 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 (isInteropZodSchema(schema)) {
|
|
448
|
-
const altParser = StructuredOutputParser.fromZodSchema(schema);
|
|
449
|
-
outputParser = RunnableLambda.from((aiMessage) => {
|
|
450
|
-
if ("parsed" in aiMessage.additional_kwargs) return aiMessage.additional_kwargs.parsed;
|
|
451
|
-
return altParser;
|
|
452
|
-
});
|
|
453
|
-
} else outputParser = new JsonOutputParser();
|
|
454
|
-
} else {
|
|
455
|
-
let functionName = name ?? "extract";
|
|
456
|
-
if (isInteropZodSchema(schema)) {
|
|
457
|
-
const asJsonSchema = 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 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 = 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 JsonOutputKeyToolsParser({
|
|
518
|
-
returnSingle: true,
|
|
519
|
-
keyName: functionName
|
|
520
|
-
});
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
if (!includeRaw) return llm.pipe(outputParser);
|
|
524
|
-
const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });
|
|
525
|
-
const parserNone = RunnablePassthrough.assign({ parsed: () => null });
|
|
526
|
-
const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });
|
|
527
|
-
return RunnableSequence.from([{ raw: llm }, parsedWithFallback]);
|
|
528
|
-
}
|
|
529
|
-
};
|
|
530
|
-
/**
|
|
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: isBuiltInToolChoice(options?.tool_choice) ? options?.tool_choice : (() => {
|
|
556
|
-
const formatted = 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 = 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(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(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 = parseCustomToolCall(item);
|
|
737
|
-
if (parsed) tool_calls.push(parsed);
|
|
738
|
-
else invalid_tool_calls.push(makeInvalidToolCall(item, "Malformed custom tool call"));
|
|
739
|
-
} else {
|
|
740
|
-
additional_kwargs.tool_outputs ??= [];
|
|
741
|
-
additional_kwargs.tool_outputs.push(item);
|
|
742
|
-
}
|
|
743
|
-
return new AIMessage({
|
|
744
|
-
id: messageId,
|
|
745
|
-
content,
|
|
746
|
-
tool_calls,
|
|
747
|
-
invalid_tool_calls,
|
|
748
|
-
usage_metadata: _convertOpenAIResponsesUsageToLangChainUsage(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 = _convertOpenAIResponsesUsageToLangChainUsage(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" || chunk.type === "response.custom_tool_call_input.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 ChatGenerationChunk({
|
|
842
|
-
text: content.map((part) => part.text).join(""),
|
|
843
|
-
message: new 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
|
-
const responseMetadata = lcMsg.response_metadata;
|
|
858
|
-
if (responseMetadata?.output_version === "v1") return _convertToResponsesMessageFromV1(lcMsg);
|
|
859
|
-
const additional_kwargs = lcMsg.additional_kwargs;
|
|
860
|
-
let role = messageToOpenAIRole(lcMsg);
|
|
861
|
-
if (role === "system" && isReasoningModel(this.model)) role = "developer";
|
|
862
|
-
if (role === "function") throw new Error("Function messages are not supported in Responses API");
|
|
863
|
-
if (role === "tool") {
|
|
864
|
-
const toolMessage = lcMsg;
|
|
865
|
-
if (additional_kwargs?.type === "computer_call_output") {
|
|
866
|
-
const output = (() => {
|
|
867
|
-
if (typeof toolMessage.content === "string") return {
|
|
868
|
-
type: "computer_screenshot",
|
|
869
|
-
image_url: toolMessage.content
|
|
870
|
-
};
|
|
871
|
-
if (Array.isArray(toolMessage.content)) {
|
|
872
|
-
const oaiScreenshot = toolMessage.content.find((i) => i.type === "computer_screenshot");
|
|
873
|
-
if (oaiScreenshot) return oaiScreenshot;
|
|
874
|
-
const lcImage = toolMessage.content.find((i) => i.type === "image_url");
|
|
875
|
-
if (lcImage) return {
|
|
876
|
-
type: "computer_screenshot",
|
|
877
|
-
image_url: typeof lcImage.image_url === "string" ? lcImage.image_url : lcImage.image_url.url
|
|
878
|
-
};
|
|
879
|
-
}
|
|
880
|
-
throw new Error("Invalid computer call output");
|
|
881
|
-
})();
|
|
882
|
-
return {
|
|
883
|
-
type: "computer_call_output",
|
|
884
|
-
output,
|
|
885
|
-
call_id: toolMessage.tool_call_id
|
|
886
|
-
};
|
|
887
|
-
}
|
|
888
|
-
if (toolMessage.additional_kwargs?.customTool) return {
|
|
889
|
-
type: "custom_tool_call_output",
|
|
890
|
-
call_id: toolMessage.tool_call_id,
|
|
891
|
-
output: toolMessage.content
|
|
892
|
-
};
|
|
893
|
-
return {
|
|
894
|
-
type: "function_call_output",
|
|
895
|
-
call_id: toolMessage.tool_call_id,
|
|
896
|
-
id: toolMessage.id?.startsWith("fc_") ? toolMessage.id : void 0,
|
|
897
|
-
output: typeof toolMessage.content !== "string" ? JSON.stringify(toolMessage.content) : toolMessage.content
|
|
898
|
-
};
|
|
899
|
-
}
|
|
900
|
-
if (role === "assistant") {
|
|
901
|
-
if (!this.zdrEnabled && responseMetadata?.output != null && Array.isArray(responseMetadata?.output) && responseMetadata?.output.length > 0 && responseMetadata?.output.every((item) => "type" in item)) return responseMetadata?.output;
|
|
902
|
-
const input = [];
|
|
903
|
-
if (additional_kwargs?.reasoning && !this.zdrEnabled) {
|
|
904
|
-
const reasoningItem = this._convertReasoningSummary(additional_kwargs.reasoning);
|
|
905
|
-
input.push(reasoningItem);
|
|
906
|
-
}
|
|
907
|
-
let { content } = lcMsg;
|
|
908
|
-
if (additional_kwargs?.refusal) {
|
|
909
|
-
if (typeof content === "string") content = [{
|
|
910
|
-
type: "output_text",
|
|
911
|
-
text: content,
|
|
912
|
-
annotations: []
|
|
913
|
-
}];
|
|
914
|
-
content = [...content, {
|
|
915
|
-
type: "refusal",
|
|
916
|
-
refusal: additional_kwargs.refusal
|
|
917
|
-
}];
|
|
918
|
-
}
|
|
919
|
-
if (typeof content === "string" || content.length > 0) input.push({
|
|
920
|
-
type: "message",
|
|
921
|
-
role: "assistant",
|
|
922
|
-
...lcMsg.id && !this.zdrEnabled && lcMsg.id.startsWith("msg_") ? { id: lcMsg.id } : {},
|
|
923
|
-
content: iife(() => {
|
|
924
|
-
if (typeof content === "string") return content;
|
|
925
|
-
return content.flatMap((item) => {
|
|
926
|
-
if (item.type === "text") return {
|
|
927
|
-
type: "output_text",
|
|
928
|
-
text: item.text,
|
|
929
|
-
annotations: item.annotations ?? []
|
|
930
|
-
};
|
|
931
|
-
if (item.type === "output_text" || item.type === "refusal") return item;
|
|
932
|
-
return [];
|
|
933
|
-
});
|
|
934
|
-
})
|
|
935
|
-
});
|
|
936
|
-
const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];
|
|
937
|
-
if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => {
|
|
938
|
-
if (isCustomToolCall(toolCall)) return {
|
|
939
|
-
type: "custom_tool_call",
|
|
940
|
-
id: toolCall.call_id,
|
|
941
|
-
call_id: toolCall.id ?? "",
|
|
942
|
-
input: toolCall.args.input,
|
|
943
|
-
name: toolCall.name
|
|
944
|
-
};
|
|
945
|
-
return {
|
|
946
|
-
type: "function_call",
|
|
947
|
-
name: toolCall.name,
|
|
948
|
-
arguments: JSON.stringify(toolCall.args),
|
|
949
|
-
call_id: toolCall.id,
|
|
950
|
-
...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}
|
|
951
|
-
};
|
|
952
|
-
}));
|
|
953
|
-
else if (additional_kwargs?.tool_calls) input.push(...additional_kwargs.tool_calls.map((toolCall) => ({
|
|
954
|
-
type: "function_call",
|
|
955
|
-
name: toolCall.function.name,
|
|
956
|
-
call_id: toolCall.id,
|
|
957
|
-
arguments: toolCall.function.arguments,
|
|
958
|
-
...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}
|
|
959
|
-
})));
|
|
960
|
-
const toolOutputs = (responseMetadata?.output)?.length ? responseMetadata?.output : additional_kwargs.tool_outputs;
|
|
961
|
-
const fallthroughCallTypes = [
|
|
962
|
-
"computer_call",
|
|
963
|
-
"mcp_call",
|
|
964
|
-
"code_interpreter_call",
|
|
965
|
-
"image_generation_call"
|
|
966
|
-
];
|
|
967
|
-
if (toolOutputs != null) {
|
|
968
|
-
const castToolOutputs = toolOutputs;
|
|
969
|
-
const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type));
|
|
970
|
-
if (fallthroughCalls.length > 0) input.push(...fallthroughCalls);
|
|
971
|
-
}
|
|
972
|
-
return input;
|
|
973
|
-
}
|
|
974
|
-
if (role === "user" || role === "system" || role === "developer") {
|
|
975
|
-
if (typeof lcMsg.content === "string") return {
|
|
976
|
-
type: "message",
|
|
977
|
-
role,
|
|
978
|
-
content: lcMsg.content
|
|
979
|
-
};
|
|
980
|
-
const messages$1 = [];
|
|
981
|
-
const content = lcMsg.content.flatMap((item) => {
|
|
982
|
-
if (item.type === "mcp_approval_response") messages$1.push({
|
|
983
|
-
type: "mcp_approval_response",
|
|
984
|
-
approval_request_id: item.approval_request_id,
|
|
985
|
-
approve: item.approve
|
|
986
|
-
});
|
|
987
|
-
if (isDataContentBlock(item)) return convertToProviderContentBlock(item, completionsApiContentBlockConverter);
|
|
988
|
-
if (item.type === "text") return {
|
|
989
|
-
type: "input_text",
|
|
990
|
-
text: item.text
|
|
991
|
-
};
|
|
992
|
-
if (item.type === "image_url") {
|
|
993
|
-
const imageUrl = iife(() => {
|
|
994
|
-
if (typeof item.image_url === "string") return item.image_url;
|
|
995
|
-
else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) return item.image_url.url;
|
|
996
|
-
return void 0;
|
|
997
|
-
});
|
|
998
|
-
const detail = iife(() => {
|
|
999
|
-
if (typeof item.image_url === "string") return "auto";
|
|
1000
|
-
else if (typeof item.image_url === "object" && item.image_url !== null && "detail" in item.image_url) return item.image_url.detail;
|
|
1001
|
-
return void 0;
|
|
1002
|
-
});
|
|
1003
|
-
return {
|
|
1004
|
-
type: "input_image",
|
|
1005
|
-
image_url: imageUrl,
|
|
1006
|
-
detail
|
|
1007
|
-
};
|
|
1008
|
-
}
|
|
1009
|
-
if (item.type === "input_text" || item.type === "input_image" || item.type === "input_file") return item;
|
|
1010
|
-
return [];
|
|
1011
|
-
});
|
|
1012
|
-
if (content.length > 0) messages$1.push({
|
|
1013
|
-
type: "message",
|
|
1014
|
-
role,
|
|
1015
|
-
content
|
|
1016
|
-
});
|
|
1017
|
-
return messages$1;
|
|
1018
|
-
}
|
|
1019
|
-
console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`);
|
|
1020
|
-
return [];
|
|
1021
|
-
});
|
|
1022
|
-
}
|
|
1023
|
-
/** @internal */
|
|
1024
|
-
_convertReasoningSummary(reasoning) {
|
|
1025
|
-
const summary = (reasoning.summary.length > 1 ? reasoning.summary.reduce((acc, curr) => {
|
|
1026
|
-
const last = acc.at(-1);
|
|
1027
|
-
if (last.index === curr.index) last.text += curr.text;
|
|
1028
|
-
else acc.push(curr);
|
|
1029
|
-
return acc;
|
|
1030
|
-
}, [{ ...reasoning.summary[0] }]) : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index")));
|
|
1031
|
-
return {
|
|
1032
|
-
...reasoning,
|
|
1033
|
-
summary
|
|
1034
|
-
};
|
|
1035
|
-
}
|
|
1036
|
-
/** @internal */
|
|
1037
|
-
_reduceChatOpenAITools(tools, fields) {
|
|
1038
|
-
const reducedTools = [];
|
|
1039
|
-
for (const tool of tools) if (isBuiltInTool(tool)) {
|
|
1040
|
-
if (tool.type === "image_generation" && fields?.stream) tool.partial_images = 1;
|
|
1041
|
-
reducedTools.push(tool);
|
|
1042
|
-
} else if (isOpenAITool(tool)) reducedTools.push({
|
|
1043
|
-
type: "function",
|
|
1044
|
-
name: tool.function.name,
|
|
1045
|
-
parameters: tool.function.parameters,
|
|
1046
|
-
description: tool.function.description,
|
|
1047
|
-
strict: fields?.strict ?? null
|
|
1048
|
-
});
|
|
1049
|
-
else if (isOpenAICustomTool(tool)) reducedTools.push(convertCompletionsCustomTool(tool));
|
|
1050
|
-
return reducedTools;
|
|
1051
|
-
}
|
|
1052
|
-
};
|
|
1053
|
-
/**
|
|
1054
|
-
* OpenAI Completions API implementation.
|
|
1055
|
-
* @internal
|
|
1056
|
-
*/
|
|
1057
|
-
var ChatOpenAICompletions = class extends BaseChatOpenAI {
|
|
1058
|
-
/** @internal */
|
|
1059
|
-
invocationParams(options, extra) {
|
|
1060
|
-
let strict;
|
|
1061
|
-
if (options?.strict !== void 0) strict = options.strict;
|
|
1062
|
-
else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;
|
|
1063
|
-
let streamOptionsConfig = {};
|
|
1064
|
-
if (options?.stream_options !== void 0) streamOptionsConfig = { stream_options: options.stream_options };
|
|
1065
|
-
else if (this.streamUsage && (this.streaming || extra?.streaming)) streamOptionsConfig = { stream_options: { include_usage: true } };
|
|
1066
|
-
const params = {
|
|
1067
|
-
model: this.model,
|
|
1068
|
-
temperature: this.temperature,
|
|
1069
|
-
top_p: this.topP,
|
|
1070
|
-
frequency_penalty: this.frequencyPenalty,
|
|
1071
|
-
presence_penalty: this.presencePenalty,
|
|
1072
|
-
logprobs: this.logprobs,
|
|
1073
|
-
top_logprobs: this.topLogprobs,
|
|
1074
|
-
n: this.n,
|
|
1075
|
-
logit_bias: this.logitBias,
|
|
1076
|
-
stop: options?.stop ?? this.stopSequences,
|
|
1077
|
-
user: this.user,
|
|
1078
|
-
stream: this.streaming,
|
|
1079
|
-
functions: options?.functions,
|
|
1080
|
-
function_call: options?.function_call,
|
|
1081
|
-
tools: options?.tools?.length ? options.tools.map((tool) => this._convertChatOpenAIToolToCompletionsTool(tool, { strict })) : void 0,
|
|
1082
|
-
tool_choice: formatToOpenAIToolChoice(options?.tool_choice),
|
|
1083
|
-
response_format: this._getResponseFormat(options?.response_format),
|
|
1084
|
-
seed: options?.seed,
|
|
1085
|
-
...streamOptionsConfig,
|
|
1086
|
-
parallel_tool_calls: options?.parallel_tool_calls,
|
|
1087
|
-
...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {},
|
|
1088
|
-
...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {},
|
|
1089
|
-
...this.modelKwargs,
|
|
1090
|
-
prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,
|
|
1091
|
-
verbosity: options?.verbosity ?? this.verbosity
|
|
1092
|
-
};
|
|
1093
|
-
if (options?.prediction !== void 0) params.prediction = options.prediction;
|
|
1094
|
-
if (this.service_tier !== void 0) params.service_tier = this.service_tier;
|
|
1095
|
-
if (options?.service_tier !== void 0) params.service_tier = options.service_tier;
|
|
1096
|
-
const reasoning = this._getReasoningParams(options);
|
|
1097
|
-
if (reasoning !== void 0 && reasoning.effort !== void 0) params.reasoning_effort = reasoning.effort;
|
|
1098
|
-
if (isReasoningModel(params.model)) params.max_completion_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens;
|
|
1099
|
-
else params.max_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens;
|
|
1100
|
-
return params;
|
|
1101
|
-
}
|
|
1102
|
-
async _generate(messages, options, runManager) {
|
|
1103
|
-
const usageMetadata = {};
|
|
1104
|
-
const params = this.invocationParams(options);
|
|
1105
|
-
const messagesMapped = _convertMessagesToOpenAIParams(messages, this.model);
|
|
1106
|
-
if (params.stream) {
|
|
1107
|
-
const stream = this._streamResponseChunks(messages, options, runManager);
|
|
1108
|
-
const finalChunks = {};
|
|
1109
|
-
for await (const chunk of stream) {
|
|
1110
|
-
chunk.message.response_metadata = {
|
|
1111
|
-
...chunk.generationInfo,
|
|
1112
|
-
...chunk.message.response_metadata
|
|
1113
|
-
};
|
|
1114
|
-
const index = chunk.generationInfo?.completion ?? 0;
|
|
1115
|
-
if (finalChunks[index] === void 0) finalChunks[index] = chunk;
|
|
1116
|
-
else finalChunks[index] = finalChunks[index].concat(chunk);
|
|
1117
|
-
}
|
|
1118
|
-
const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value);
|
|
1119
|
-
const { functions, function_call } = this.invocationParams(options);
|
|
1120
|
-
const promptTokenUsage = await this._getEstimatedTokenCountFromPrompt(messages, functions, function_call);
|
|
1121
|
-
const completionTokenUsage = await this._getNumTokensFromGenerations(generations);
|
|
1122
|
-
usageMetadata.input_tokens = promptTokenUsage;
|
|
1123
|
-
usageMetadata.output_tokens = completionTokenUsage;
|
|
1124
|
-
usageMetadata.total_tokens = promptTokenUsage + completionTokenUsage;
|
|
1125
|
-
return {
|
|
1126
|
-
generations,
|
|
1127
|
-
llmOutput: { estimatedTokenUsage: {
|
|
1128
|
-
promptTokens: usageMetadata.input_tokens,
|
|
1129
|
-
completionTokens: usageMetadata.output_tokens,
|
|
1130
|
-
totalTokens: usageMetadata.total_tokens
|
|
1131
|
-
} }
|
|
1132
|
-
};
|
|
1133
|
-
} else {
|
|
1134
|
-
const data = await this.completionWithRetry({
|
|
1135
|
-
...params,
|
|
1136
|
-
stream: false,
|
|
1137
|
-
messages: messagesMapped
|
|
1138
|
-
}, {
|
|
1139
|
-
signal: options?.signal,
|
|
1140
|
-
...options?.options
|
|
1141
|
-
});
|
|
1142
|
-
const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {};
|
|
1143
|
-
if (completionTokens) usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens;
|
|
1144
|
-
if (promptTokens) usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens;
|
|
1145
|
-
if (totalTokens) usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens;
|
|
1146
|
-
if (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) usageMetadata.input_token_details = {
|
|
1147
|
-
...promptTokensDetails?.audio_tokens !== null && { audio: promptTokensDetails?.audio_tokens },
|
|
1148
|
-
...promptTokensDetails?.cached_tokens !== null && { cache_read: promptTokensDetails?.cached_tokens }
|
|
1149
|
-
};
|
|
1150
|
-
if (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) usageMetadata.output_token_details = {
|
|
1151
|
-
...completionTokensDetails?.audio_tokens !== null && { audio: completionTokensDetails?.audio_tokens },
|
|
1152
|
-
...completionTokensDetails?.reasoning_tokens !== null && { reasoning: completionTokensDetails?.reasoning_tokens }
|
|
1153
|
-
};
|
|
1154
|
-
const generations = [];
|
|
1155
|
-
for (const part of data?.choices ?? []) {
|
|
1156
|
-
const text = part.message?.content ?? "";
|
|
1157
|
-
const generation = {
|
|
1158
|
-
text,
|
|
1159
|
-
message: this._convertCompletionsMessageToBaseMessage(part.message ?? { role: "assistant" }, data)
|
|
1160
|
-
};
|
|
1161
|
-
generation.generationInfo = {
|
|
1162
|
-
...part.finish_reason ? { finish_reason: part.finish_reason } : {},
|
|
1163
|
-
...part.logprobs ? { logprobs: part.logprobs } : {}
|
|
1164
|
-
};
|
|
1165
|
-
if (isAIMessage(generation.message)) generation.message.usage_metadata = usageMetadata;
|
|
1166
|
-
generation.message = new AIMessage(Object.fromEntries(Object.entries(generation.message).filter(([key]) => !key.startsWith("lc_"))));
|
|
1167
|
-
generations.push(generation);
|
|
1168
|
-
}
|
|
1169
|
-
return {
|
|
1170
|
-
generations,
|
|
1171
|
-
llmOutput: { tokenUsage: {
|
|
1172
|
-
promptTokens: usageMetadata.input_tokens,
|
|
1173
|
-
completionTokens: usageMetadata.output_tokens,
|
|
1174
|
-
totalTokens: usageMetadata.total_tokens
|
|
1175
|
-
} }
|
|
1176
|
-
};
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
async *_streamResponseChunks(messages, options, runManager) {
|
|
1180
|
-
const messagesMapped = _convertMessagesToOpenAIParams(messages, this.model);
|
|
1181
|
-
const params = {
|
|
1182
|
-
...this.invocationParams(options, { streaming: true }),
|
|
1183
|
-
messages: messagesMapped,
|
|
1184
|
-
stream: true
|
|
1185
|
-
};
|
|
1186
|
-
let defaultRole;
|
|
1187
|
-
const streamIterable = await this.completionWithRetry(params, options);
|
|
1188
|
-
let usage;
|
|
1189
|
-
for await (const data of streamIterable) {
|
|
1190
|
-
const choice = data?.choices?.[0];
|
|
1191
|
-
if (data.usage) usage = data.usage;
|
|
1192
|
-
if (!choice) continue;
|
|
1193
|
-
const { delta } = choice;
|
|
1194
|
-
if (!delta) continue;
|
|
1195
|
-
const chunk = this._convertCompletionsDeltaToBaseMessageChunk(delta, data, defaultRole);
|
|
1196
|
-
defaultRole = delta.role ?? defaultRole;
|
|
1197
|
-
const newTokenIndices = {
|
|
1198
|
-
prompt: options.promptIndex ?? 0,
|
|
1199
|
-
completion: choice.index ?? 0
|
|
1200
|
-
};
|
|
1201
|
-
if (typeof chunk.content !== "string") {
|
|
1202
|
-
console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");
|
|
1203
|
-
continue;
|
|
1204
|
-
}
|
|
1205
|
-
const generationInfo = { ...newTokenIndices };
|
|
1206
|
-
if (choice.finish_reason != null) {
|
|
1207
|
-
generationInfo.finish_reason = choice.finish_reason;
|
|
1208
|
-
generationInfo.system_fingerprint = data.system_fingerprint;
|
|
1209
|
-
generationInfo.model_name = data.model;
|
|
1210
|
-
generationInfo.service_tier = data.service_tier;
|
|
1211
|
-
}
|
|
1212
|
-
if (this.logprobs) generationInfo.logprobs = choice.logprobs;
|
|
1213
|
-
const generationChunk = new ChatGenerationChunk({
|
|
1214
|
-
message: chunk,
|
|
1215
|
-
text: chunk.content,
|
|
1216
|
-
generationInfo
|
|
1217
|
-
});
|
|
1218
|
-
yield generationChunk;
|
|
1219
|
-
await runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk });
|
|
1220
|
-
}
|
|
1221
|
-
if (usage) {
|
|
1222
|
-
const inputTokenDetails = {
|
|
1223
|
-
...usage.prompt_tokens_details?.audio_tokens !== null && { audio: usage.prompt_tokens_details?.audio_tokens },
|
|
1224
|
-
...usage.prompt_tokens_details?.cached_tokens !== null && { cache_read: usage.prompt_tokens_details?.cached_tokens }
|
|
1225
|
-
};
|
|
1226
|
-
const outputTokenDetails = {
|
|
1227
|
-
...usage.completion_tokens_details?.audio_tokens !== null && { audio: usage.completion_tokens_details?.audio_tokens },
|
|
1228
|
-
...usage.completion_tokens_details?.reasoning_tokens !== null && { reasoning: usage.completion_tokens_details?.reasoning_tokens }
|
|
1229
|
-
};
|
|
1230
|
-
const generationChunk = new ChatGenerationChunk({
|
|
1231
|
-
message: new AIMessageChunk({
|
|
1232
|
-
content: "",
|
|
1233
|
-
response_metadata: { usage: { ...usage } },
|
|
1234
|
-
usage_metadata: {
|
|
1235
|
-
input_tokens: usage.prompt_tokens,
|
|
1236
|
-
output_tokens: usage.completion_tokens,
|
|
1237
|
-
total_tokens: usage.total_tokens,
|
|
1238
|
-
...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails },
|
|
1239
|
-
...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails }
|
|
1240
|
-
}
|
|
1241
|
-
}),
|
|
1242
|
-
text: ""
|
|
1243
|
-
});
|
|
1244
|
-
yield generationChunk;
|
|
1245
|
-
}
|
|
1246
|
-
if (options.signal?.aborted) throw new Error("AbortError");
|
|
1247
|
-
}
|
|
1248
|
-
async completionWithRetry(request, requestOptions) {
|
|
1249
|
-
const clientOptions = this._getClientOptions(requestOptions);
|
|
1250
|
-
const isParseableFormat = request.response_format && request.response_format.type === "json_schema";
|
|
1251
|
-
return this.caller.call(async () => {
|
|
1252
|
-
try {
|
|
1253
|
-
if (isParseableFormat && !request.stream) return await this.client.chat.completions.parse(request, clientOptions);
|
|
1254
|
-
else return await this.client.chat.completions.create(request, clientOptions);
|
|
1255
|
-
} catch (e) {
|
|
1256
|
-
const error = wrapOpenAIClientError(e);
|
|
1257
|
-
throw error;
|
|
1258
|
-
}
|
|
1259
|
-
});
|
|
1260
|
-
}
|
|
1261
|
-
/** @internal */
|
|
1262
|
-
_convertCompletionsMessageToBaseMessage(message, rawResponse) {
|
|
1263
|
-
const rawToolCalls = message.tool_calls;
|
|
1264
|
-
switch (message.role) {
|
|
1265
|
-
case "assistant": {
|
|
1266
|
-
const toolCalls = [];
|
|
1267
|
-
const invalidToolCalls = [];
|
|
1268
|
-
for (const rawToolCall of rawToolCalls ?? []) try {
|
|
1269
|
-
toolCalls.push(parseToolCall(rawToolCall, { returnId: true }));
|
|
1270
|
-
} catch (e) {
|
|
1271
|
-
invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message));
|
|
1272
|
-
}
|
|
1273
|
-
const additional_kwargs = {
|
|
1274
|
-
function_call: message.function_call,
|
|
1275
|
-
tool_calls: rawToolCalls
|
|
1276
|
-
};
|
|
1277
|
-
if (this.__includeRawResponse !== void 0) additional_kwargs.__raw_response = rawResponse;
|
|
1278
|
-
const response_metadata = {
|
|
1279
|
-
model_provider: "openai",
|
|
1280
|
-
model_name: rawResponse.model,
|
|
1281
|
-
...rawResponse.system_fingerprint ? {
|
|
1282
|
-
usage: { ...rawResponse.usage },
|
|
1283
|
-
system_fingerprint: rawResponse.system_fingerprint
|
|
1284
|
-
} : {}
|
|
1285
|
-
};
|
|
1286
|
-
if (message.audio) additional_kwargs.audio = message.audio;
|
|
1287
|
-
const content = handleMultiModalOutput(message.content || "", rawResponse.choices?.[0]?.message);
|
|
1288
|
-
return new AIMessage({
|
|
1289
|
-
content,
|
|
1290
|
-
tool_calls: toolCalls,
|
|
1291
|
-
invalid_tool_calls: invalidToolCalls,
|
|
1292
|
-
additional_kwargs,
|
|
1293
|
-
response_metadata,
|
|
1294
|
-
id: rawResponse.id
|
|
1295
|
-
});
|
|
1296
|
-
}
|
|
1297
|
-
default: return new ChatMessage(message.content || "", message.role ?? "unknown");
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
/** @internal */
|
|
1301
|
-
_convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) {
|
|
1302
|
-
const role = delta.role ?? defaultRole;
|
|
1303
|
-
const content = delta.content ?? "";
|
|
1304
|
-
let additional_kwargs;
|
|
1305
|
-
if (delta.function_call) additional_kwargs = { function_call: delta.function_call };
|
|
1306
|
-
else if (delta.tool_calls) additional_kwargs = { tool_calls: delta.tool_calls };
|
|
1307
|
-
else additional_kwargs = {};
|
|
1308
|
-
if (this.__includeRawResponse) additional_kwargs.__raw_response = rawResponse;
|
|
1309
|
-
if (delta.audio) additional_kwargs.audio = {
|
|
1310
|
-
...delta.audio,
|
|
1311
|
-
index: rawResponse.choices[0].index
|
|
1312
|
-
};
|
|
1313
|
-
const response_metadata = {
|
|
1314
|
-
model_provider: "openai",
|
|
1315
|
-
usage: { ...rawResponse.usage }
|
|
1316
|
-
};
|
|
1317
|
-
if (role === "user") return new HumanMessageChunk({
|
|
1318
|
-
content,
|
|
1319
|
-
response_metadata
|
|
1320
|
-
});
|
|
1321
|
-
else if (role === "assistant") {
|
|
1322
|
-
const toolCallChunks = [];
|
|
1323
|
-
if (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) toolCallChunks.push({
|
|
1324
|
-
name: rawToolCall.function?.name,
|
|
1325
|
-
args: rawToolCall.function?.arguments,
|
|
1326
|
-
id: rawToolCall.id,
|
|
1327
|
-
index: rawToolCall.index,
|
|
1328
|
-
type: "tool_call_chunk"
|
|
1329
|
-
});
|
|
1330
|
-
return new AIMessageChunk({
|
|
1331
|
-
content,
|
|
1332
|
-
tool_call_chunks: toolCallChunks,
|
|
1333
|
-
additional_kwargs,
|
|
1334
|
-
id: rawResponse.id,
|
|
1335
|
-
response_metadata
|
|
1336
|
-
});
|
|
1337
|
-
} else if (role === "system") return new SystemMessageChunk({
|
|
1338
|
-
content,
|
|
1339
|
-
response_metadata
|
|
1340
|
-
});
|
|
1341
|
-
else if (role === "developer") return new SystemMessageChunk({
|
|
1342
|
-
content,
|
|
1343
|
-
response_metadata,
|
|
1344
|
-
additional_kwargs: { __openai_role__: "developer" }
|
|
1345
|
-
});
|
|
1346
|
-
else if (role === "function") return new FunctionMessageChunk({
|
|
1347
|
-
content,
|
|
1348
|
-
additional_kwargs,
|
|
1349
|
-
name: delta.name,
|
|
1350
|
-
response_metadata
|
|
1351
|
-
});
|
|
1352
|
-
else if (role === "tool") return new ToolMessageChunk({
|
|
1353
|
-
content,
|
|
1354
|
-
additional_kwargs,
|
|
1355
|
-
tool_call_id: delta.tool_call_id,
|
|
1356
|
-
response_metadata
|
|
1357
|
-
});
|
|
1358
|
-
else return new ChatMessageChunk({
|
|
1359
|
-
content,
|
|
1360
|
-
role,
|
|
1361
|
-
response_metadata
|
|
1362
|
-
});
|
|
1363
|
-
}
|
|
1364
|
-
};
|
|
1365
|
-
/**
|
|
1366
|
-
* OpenAI chat model integration.
|
|
1367
|
-
*
|
|
1368
|
-
* To use with Azure, import the `AzureChatOpenAI` class.
|
|
1369
|
-
*
|
|
1370
|
-
* Setup:
|
|
1371
|
-
* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
|
|
1372
|
-
*
|
|
1373
|
-
* ```bash
|
|
1374
|
-
* npm install @langchain/openai
|
|
1375
|
-
* export OPENAI_API_KEY="your-api-key"
|
|
1376
|
-
* ```
|
|
1377
|
-
*
|
|
1378
|
-
* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
|
|
1379
|
-
*
|
|
1380
|
-
* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
|
|
1381
|
-
*
|
|
1382
|
-
* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
|
|
1383
|
-
* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:
|
|
1384
|
-
*
|
|
1385
|
-
* ```typescript
|
|
1386
|
-
* // When calling `.withConfig`, call options should be passed via the first argument
|
|
1387
|
-
* const llmWithArgsBound = llm.withConfig({
|
|
1388
|
-
* stop: ["\n"],
|
|
1389
|
-
* tools: [...],
|
|
1390
|
-
* });
|
|
1391
|
-
*
|
|
1392
|
-
* // When calling `.bindTools`, call options should be passed via the second argument
|
|
1393
|
-
* const llmWithTools = llm.bindTools(
|
|
1394
|
-
* [...],
|
|
1395
|
-
* {
|
|
1396
|
-
* tool_choice: "auto",
|
|
1397
|
-
* }
|
|
1398
|
-
* );
|
|
1399
|
-
* ```
|
|
1400
|
-
*
|
|
1401
|
-
* ## Examples
|
|
1402
|
-
*
|
|
1403
|
-
* <details open>
|
|
1404
|
-
* <summary><strong>Instantiate</strong></summary>
|
|
1405
|
-
*
|
|
1406
|
-
* ```typescript
|
|
1407
|
-
* import { ChatOpenAI } from '@langchain/openai';
|
|
1408
|
-
*
|
|
1409
|
-
* const llm = new ChatOpenAI({
|
|
1410
|
-
* model: "gpt-4o-mini",
|
|
1411
|
-
* temperature: 0,
|
|
1412
|
-
* maxTokens: undefined,
|
|
1413
|
-
* timeout: undefined,
|
|
1414
|
-
* maxRetries: 2,
|
|
1415
|
-
* // apiKey: "...",
|
|
1416
|
-
* // baseUrl: "...",
|
|
1417
|
-
* // organization: "...",
|
|
1418
|
-
* // other params...
|
|
1419
|
-
* });
|
|
1420
|
-
* ```
|
|
1421
|
-
* </details>
|
|
1422
|
-
*
|
|
1423
|
-
* <br />
|
|
1424
|
-
*
|
|
1425
|
-
* <details>
|
|
1426
|
-
* <summary><strong>Invoking</strong></summary>
|
|
1427
|
-
*
|
|
1428
|
-
* ```typescript
|
|
1429
|
-
* const input = `Translate "I love programming" into French.`;
|
|
1430
|
-
*
|
|
1431
|
-
* // Models also accept a list of chat messages or a formatted prompt
|
|
1432
|
-
* const result = await llm.invoke(input);
|
|
1433
|
-
* console.log(result);
|
|
1434
|
-
* ```
|
|
1435
|
-
*
|
|
1436
|
-
* ```txt
|
|
1437
|
-
* AIMessage {
|
|
1438
|
-
* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
|
|
1439
|
-
* "content": "J'adore la programmation.",
|
|
1440
|
-
* "response_metadata": {
|
|
1441
|
-
* "tokenUsage": {
|
|
1442
|
-
* "completionTokens": 5,
|
|
1443
|
-
* "promptTokens": 28,
|
|
1444
|
-
* "totalTokens": 33
|
|
1445
|
-
* },
|
|
1446
|
-
* "finish_reason": "stop",
|
|
1447
|
-
* "system_fingerprint": "fp_3aa7262c27"
|
|
1448
|
-
* },
|
|
1449
|
-
* "usage_metadata": {
|
|
1450
|
-
* "input_tokens": 28,
|
|
1451
|
-
* "output_tokens": 5,
|
|
1452
|
-
* "total_tokens": 33
|
|
1453
|
-
* }
|
|
1454
|
-
* }
|
|
1455
|
-
* ```
|
|
1456
|
-
* </details>
|
|
1457
|
-
*
|
|
1458
|
-
* <br />
|
|
1459
|
-
*
|
|
1460
|
-
* <details>
|
|
1461
|
-
* <summary><strong>Streaming Chunks</strong></summary>
|
|
1462
|
-
*
|
|
1463
|
-
* ```typescript
|
|
1464
|
-
* for await (const chunk of await llm.stream(input)) {
|
|
1465
|
-
* console.log(chunk);
|
|
1466
|
-
* }
|
|
1467
|
-
* ```
|
|
1468
|
-
*
|
|
1469
|
-
* ```txt
|
|
1470
|
-
* AIMessageChunk {
|
|
1471
|
-
* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
|
|
1472
|
-
* "content": ""
|
|
1473
|
-
* }
|
|
1474
|
-
* AIMessageChunk {
|
|
1475
|
-
* "content": "J"
|
|
1476
|
-
* }
|
|
1477
|
-
* AIMessageChunk {
|
|
1478
|
-
* "content": "'adore"
|
|
1479
|
-
* }
|
|
1480
|
-
* AIMessageChunk {
|
|
1481
|
-
* "content": " la"
|
|
1482
|
-
* }
|
|
1483
|
-
* AIMessageChunk {
|
|
1484
|
-
* "content": " programmation",,
|
|
1485
|
-
* }
|
|
1486
|
-
* AIMessageChunk {
|
|
1487
|
-
* "content": ".",,
|
|
1488
|
-
* }
|
|
1489
|
-
* AIMessageChunk {
|
|
1490
|
-
* "content": "",
|
|
1491
|
-
* "response_metadata": {
|
|
1492
|
-
* "finish_reason": "stop",
|
|
1493
|
-
* "system_fingerprint": "fp_c9aa9c0491"
|
|
1494
|
-
* },
|
|
1495
|
-
* }
|
|
1496
|
-
* AIMessageChunk {
|
|
1497
|
-
* "content": "",
|
|
1498
|
-
* "usage_metadata": {
|
|
1499
|
-
* "input_tokens": 28,
|
|
1500
|
-
* "output_tokens": 5,
|
|
1501
|
-
* "total_tokens": 33
|
|
1502
|
-
* }
|
|
1503
|
-
* }
|
|
1504
|
-
* ```
|
|
1505
|
-
* </details>
|
|
1506
|
-
*
|
|
1507
|
-
* <br />
|
|
1508
|
-
*
|
|
1509
|
-
* <details>
|
|
1510
|
-
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
|
|
1511
|
-
*
|
|
1512
|
-
* ```typescript
|
|
1513
|
-
* import { AIMessageChunk } from '@langchain/core/messages';
|
|
1514
|
-
* import { concat } from '@langchain/core/utils/stream';
|
|
1515
|
-
*
|
|
1516
|
-
* const stream = await llm.stream(input);
|
|
1517
|
-
* let full: AIMessageChunk | undefined;
|
|
1518
|
-
* for await (const chunk of stream) {
|
|
1519
|
-
* full = !full ? chunk : concat(full, chunk);
|
|
1520
|
-
* }
|
|
1521
|
-
* console.log(full);
|
|
1522
|
-
* ```
|
|
1523
|
-
*
|
|
1524
|
-
* ```txt
|
|
1525
|
-
* AIMessageChunk {
|
|
1526
|
-
* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
|
|
1527
|
-
* "content": "J'adore la programmation.",
|
|
1528
|
-
* "response_metadata": {
|
|
1529
|
-
* "prompt": 0,
|
|
1530
|
-
* "completion": 0,
|
|
1531
|
-
* "finish_reason": "stop",
|
|
1532
|
-
* },
|
|
1533
|
-
* "usage_metadata": {
|
|
1534
|
-
* "input_tokens": 28,
|
|
1535
|
-
* "output_tokens": 5,
|
|
1536
|
-
* "total_tokens": 33
|
|
1537
|
-
* }
|
|
1538
|
-
* }
|
|
1539
|
-
* ```
|
|
1540
|
-
* </details>
|
|
1541
|
-
*
|
|
1542
|
-
* <br />
|
|
1543
|
-
*
|
|
1544
|
-
* <details>
|
|
1545
|
-
* <summary><strong>Bind tools</strong></summary>
|
|
1546
|
-
*
|
|
1547
|
-
* ```typescript
|
|
1548
|
-
* import { z } from 'zod';
|
|
1549
|
-
*
|
|
1550
|
-
* const GetWeather = {
|
|
1551
|
-
* name: "GetWeather",
|
|
1552
|
-
* description: "Get the current weather in a given location",
|
|
1553
|
-
* schema: z.object({
|
|
1554
|
-
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
1555
|
-
* }),
|
|
1556
|
-
* }
|
|
1557
|
-
*
|
|
1558
|
-
* const GetPopulation = {
|
|
1559
|
-
* name: "GetPopulation",
|
|
1560
|
-
* description: "Get the current population in a given location",
|
|
1561
|
-
* schema: z.object({
|
|
1562
|
-
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
1563
|
-
* }),
|
|
1564
|
-
* }
|
|
1565
|
-
*
|
|
1566
|
-
* const llmWithTools = llm.bindTools(
|
|
1567
|
-
* [GetWeather, GetPopulation],
|
|
1568
|
-
* {
|
|
1569
|
-
* // strict: true // enforce tool args schema is respected
|
|
1570
|
-
* }
|
|
1571
|
-
* );
|
|
1572
|
-
* const aiMsg = await llmWithTools.invoke(
|
|
1573
|
-
* "Which city is hotter today and which is bigger: LA or NY?"
|
|
1574
|
-
* );
|
|
1575
|
-
* console.log(aiMsg.tool_calls);
|
|
1576
|
-
* ```
|
|
1577
|
-
*
|
|
1578
|
-
* ```txt
|
|
1579
|
-
* [
|
|
1580
|
-
* {
|
|
1581
|
-
* name: 'GetWeather',
|
|
1582
|
-
* args: { location: 'Los Angeles, CA' },
|
|
1583
|
-
* type: 'tool_call',
|
|
1584
|
-
* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
|
|
1585
|
-
* },
|
|
1586
|
-
* {
|
|
1587
|
-
* name: 'GetWeather',
|
|
1588
|
-
* args: { location: 'New York, NY' },
|
|
1589
|
-
* type: 'tool_call',
|
|
1590
|
-
* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
|
|
1591
|
-
* },
|
|
1592
|
-
* {
|
|
1593
|
-
* name: 'GetPopulation',
|
|
1594
|
-
* args: { location: 'Los Angeles, CA' },
|
|
1595
|
-
* type: 'tool_call',
|
|
1596
|
-
* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
|
|
1597
|
-
* },
|
|
1598
|
-
* {
|
|
1599
|
-
* name: 'GetPopulation',
|
|
1600
|
-
* args: { location: 'New York, NY' },
|
|
1601
|
-
* type: 'tool_call',
|
|
1602
|
-
* id: 'call_s9KQB1UWj45LLGaEnjz0179q'
|
|
1603
|
-
* }
|
|
1604
|
-
* ]
|
|
1605
|
-
* ```
|
|
1606
|
-
* </details>
|
|
1607
|
-
*
|
|
1608
|
-
* <br />
|
|
1609
|
-
*
|
|
1610
|
-
* <details>
|
|
1611
|
-
* <summary><strong>Structured Output</strong></summary>
|
|
1612
|
-
*
|
|
1613
|
-
* ```typescript
|
|
1614
|
-
* import { z } from 'zod';
|
|
1615
|
-
*
|
|
1616
|
-
* const Joke = z.object({
|
|
1617
|
-
* setup: z.string().describe("The setup of the joke"),
|
|
1618
|
-
* punchline: z.string().describe("The punchline to the joke"),
|
|
1619
|
-
* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10")
|
|
1620
|
-
* }).describe('Joke to tell user.');
|
|
1621
|
-
*
|
|
1622
|
-
* const structuredLlm = llm.withStructuredOutput(Joke, {
|
|
1623
|
-
* name: "Joke",
|
|
1624
|
-
* strict: true, // Optionally enable OpenAI structured outputs
|
|
1625
|
-
* });
|
|
1626
|
-
* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
|
|
1627
|
-
* console.log(jokeResult);
|
|
1628
|
-
* ```
|
|
1629
|
-
*
|
|
1630
|
-
* ```txt
|
|
1631
|
-
* {
|
|
1632
|
-
* setup: 'Why was the cat sitting on the computer?',
|
|
1633
|
-
* punchline: 'Because it wanted to keep an eye on the mouse!',
|
|
1634
|
-
* rating: 7
|
|
1635
|
-
* }
|
|
1636
|
-
* ```
|
|
1637
|
-
* </details>
|
|
1638
|
-
*
|
|
1639
|
-
* <br />
|
|
1640
|
-
*
|
|
1641
|
-
* <details>
|
|
1642
|
-
* <summary><strong>JSON Object Response Format</strong></summary>
|
|
1643
|
-
*
|
|
1644
|
-
* ```typescript
|
|
1645
|
-
* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } });
|
|
1646
|
-
* const jsonLlmAiMsg = await jsonLlm.invoke(
|
|
1647
|
-
* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
|
|
1648
|
-
* );
|
|
1649
|
-
* console.log(jsonLlmAiMsg.content);
|
|
1650
|
-
* ```
|
|
1651
|
-
*
|
|
1652
|
-
* ```txt
|
|
1653
|
-
* {
|
|
1654
|
-
* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
|
|
1655
|
-
* }
|
|
1656
|
-
* ```
|
|
1657
|
-
* </details>
|
|
1658
|
-
*
|
|
1659
|
-
* <br />
|
|
1660
|
-
*
|
|
1661
|
-
* <details>
|
|
1662
|
-
* <summary><strong>Multimodal</strong></summary>
|
|
1663
|
-
*
|
|
1664
|
-
* ```typescript
|
|
1665
|
-
* import { HumanMessage } from '@langchain/core/messages';
|
|
1666
|
-
*
|
|
1667
|
-
* const imageUrl = "https://example.com/image.jpg";
|
|
1668
|
-
* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
|
|
1669
|
-
* const base64Image = Buffer.from(imageData).toString('base64');
|
|
1670
|
-
*
|
|
1671
|
-
* const message = new HumanMessage({
|
|
1672
|
-
* content: [
|
|
1673
|
-
* { type: "text", text: "describe the weather in this image" },
|
|
1674
|
-
* {
|
|
1675
|
-
* type: "image_url",
|
|
1676
|
-
* image_url: { url: `data:image/jpeg;base64,${base64Image}` },
|
|
1677
|
-
* },
|
|
1678
|
-
* ]
|
|
1679
|
-
* });
|
|
1680
|
-
*
|
|
1681
|
-
* const imageDescriptionAiMsg = await llm.invoke([message]);
|
|
1682
|
-
* console.log(imageDescriptionAiMsg.content);
|
|
1683
|
-
* ```
|
|
1684
|
-
*
|
|
1685
|
-
* ```txt
|
|
1686
|
-
* 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.
|
|
1687
|
-
* ```
|
|
1688
|
-
* </details>
|
|
1689
|
-
*
|
|
1690
|
-
* <br />
|
|
1691
|
-
*
|
|
1692
|
-
* <details>
|
|
1693
|
-
* <summary><strong>Usage Metadata</strong></summary>
|
|
1694
|
-
*
|
|
1695
|
-
* ```typescript
|
|
1696
|
-
* const aiMsgForMetadata = await llm.invoke(input);
|
|
1697
|
-
* console.log(aiMsgForMetadata.usage_metadata);
|
|
1698
|
-
* ```
|
|
1699
|
-
*
|
|
1700
|
-
* ```txt
|
|
1701
|
-
* { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
|
|
1702
|
-
* ```
|
|
1703
|
-
* </details>
|
|
1704
|
-
*
|
|
1705
|
-
* <br />
|
|
1706
|
-
*
|
|
1707
|
-
* <details>
|
|
1708
|
-
* <summary><strong>Logprobs</strong></summary>
|
|
1709
|
-
*
|
|
1710
|
-
* ```typescript
|
|
1711
|
-
* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true });
|
|
1712
|
-
* const aiMsgForLogprobs = await logprobsLlm.invoke(input);
|
|
1713
|
-
* console.log(aiMsgForLogprobs.response_metadata.logprobs);
|
|
1714
|
-
* ```
|
|
1715
|
-
*
|
|
1716
|
-
* ```txt
|
|
1717
|
-
* {
|
|
1718
|
-
* content: [
|
|
1719
|
-
* {
|
|
1720
|
-
* token: 'J',
|
|
1721
|
-
* logprob: -0.000050616763,
|
|
1722
|
-
* bytes: [Array],
|
|
1723
|
-
* top_logprobs: []
|
|
1724
|
-
* },
|
|
1725
|
-
* {
|
|
1726
|
-
* token: "'",
|
|
1727
|
-
* logprob: -0.01868736,
|
|
1728
|
-
* bytes: [Array],
|
|
1729
|
-
* top_logprobs: []
|
|
1730
|
-
* },
|
|
1731
|
-
* {
|
|
1732
|
-
* token: 'ad',
|
|
1733
|
-
* logprob: -0.0000030545007,
|
|
1734
|
-
* bytes: [Array],
|
|
1735
|
-
* top_logprobs: []
|
|
1736
|
-
* },
|
|
1737
|
-
* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
1738
|
-
* {
|
|
1739
|
-
* token: ' la',
|
|
1740
|
-
* logprob: -0.515404,
|
|
1741
|
-
* bytes: [Array],
|
|
1742
|
-
* top_logprobs: []
|
|
1743
|
-
* },
|
|
1744
|
-
* {
|
|
1745
|
-
* token: ' programm',
|
|
1746
|
-
* logprob: -0.0000118755715,
|
|
1747
|
-
* bytes: [Array],
|
|
1748
|
-
* top_logprobs: []
|
|
1749
|
-
* },
|
|
1750
|
-
* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
1751
|
-
* {
|
|
1752
|
-
* token: '.',
|
|
1753
|
-
* logprob: -0.0000037697225,
|
|
1754
|
-
* bytes: [Array],
|
|
1755
|
-
* top_logprobs: []
|
|
1756
|
-
* }
|
|
1757
|
-
* ],
|
|
1758
|
-
* refusal: null
|
|
1759
|
-
* }
|
|
1760
|
-
* ```
|
|
1761
|
-
* </details>
|
|
1762
|
-
*
|
|
1763
|
-
* <br />
|
|
1764
|
-
*
|
|
1765
|
-
* <details>
|
|
1766
|
-
* <summary><strong>Response Metadata</strong></summary>
|
|
1767
|
-
*
|
|
1768
|
-
* ```typescript
|
|
1769
|
-
* const aiMsgForResponseMetadata = await llm.invoke(input);
|
|
1770
|
-
* console.log(aiMsgForResponseMetadata.response_metadata);
|
|
1771
|
-
* ```
|
|
1772
|
-
*
|
|
1773
|
-
* ```txt
|
|
1774
|
-
* {
|
|
1775
|
-
* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
|
|
1776
|
-
* finish_reason: 'stop',
|
|
1777
|
-
* system_fingerprint: 'fp_3aa7262c27'
|
|
1778
|
-
* }
|
|
1779
|
-
* ```
|
|
1780
|
-
* </details>
|
|
1781
|
-
*
|
|
1782
|
-
* <br />
|
|
1783
|
-
*
|
|
1784
|
-
* <details>
|
|
1785
|
-
* <summary><strong>JSON Schema Structured Output</strong></summary>
|
|
1786
|
-
*
|
|
1787
|
-
* ```typescript
|
|
1788
|
-
* const llmForJsonSchema = new ChatOpenAI({
|
|
1789
|
-
* model: "gpt-4o-2024-08-06",
|
|
1790
|
-
* }).withStructuredOutput(
|
|
1791
|
-
* z.object({
|
|
1792
|
-
* command: z.string().describe("The command to execute"),
|
|
1793
|
-
* expectedOutput: z.string().describe("The expected output of the command"),
|
|
1794
|
-
* options: z
|
|
1795
|
-
* .array(z.string())
|
|
1796
|
-
* .describe("The options you can pass to the command"),
|
|
1797
|
-
* }),
|
|
1798
|
-
* {
|
|
1799
|
-
* method: "jsonSchema",
|
|
1800
|
-
* strict: true, // Optional when using the `jsonSchema` method
|
|
1801
|
-
* }
|
|
1802
|
-
* );
|
|
1803
|
-
*
|
|
1804
|
-
* const jsonSchemaRes = await llmForJsonSchema.invoke(
|
|
1805
|
-
* "What is the command to list files in a directory?"
|
|
1806
|
-
* );
|
|
1807
|
-
* console.log(jsonSchemaRes);
|
|
1808
|
-
* ```
|
|
1809
|
-
*
|
|
1810
|
-
* ```txt
|
|
1811
|
-
* {
|
|
1812
|
-
* command: 'ls',
|
|
1813
|
-
* expectedOutput: 'A list of files and subdirectories within the specified directory.',
|
|
1814
|
-
* options: [
|
|
1815
|
-
* '-a: include directory entries whose names begin with a dot (.).',
|
|
1816
|
-
* '-l: use a long listing format.',
|
|
1817
|
-
* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).',
|
|
1818
|
-
* '-t: sort by time, newest first.',
|
|
1819
|
-
* '-r: reverse order while sorting.',
|
|
1820
|
-
* '-S: sort by file size, largest first.',
|
|
1821
|
-
* '-R: list subdirectories recursively.'
|
|
1822
|
-
* ]
|
|
1823
|
-
* }
|
|
1824
|
-
* ```
|
|
1825
|
-
* </details>
|
|
1826
|
-
*
|
|
1827
|
-
* <br />
|
|
1828
|
-
*
|
|
1829
|
-
* <details>
|
|
1830
|
-
* <summary><strong>Audio Outputs</strong></summary>
|
|
1831
|
-
*
|
|
1832
|
-
* ```typescript
|
|
1833
|
-
* import { ChatOpenAI } from "@langchain/openai";
|
|
1834
|
-
*
|
|
1835
|
-
* const modelWithAudioOutput = new ChatOpenAI({
|
|
1836
|
-
* model: "gpt-4o-audio-preview",
|
|
1837
|
-
* // You may also pass these fields to `.withConfig` as a call argument.
|
|
1838
|
-
* modalities: ["text", "audio"], // Specifies that the model should output audio.
|
|
1839
|
-
* audio: {
|
|
1840
|
-
* voice: "alloy",
|
|
1841
|
-
* format: "wav",
|
|
1842
|
-
* },
|
|
1843
|
-
* });
|
|
1844
|
-
*
|
|
1845
|
-
* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats.");
|
|
1846
|
-
* const castMessageContent = audioOutputResult.content[0] as Record<string, any>;
|
|
1847
|
-
*
|
|
1848
|
-
* console.log({
|
|
1849
|
-
* ...castMessageContent,
|
|
1850
|
-
* data: castMessageContent.data.slice(0, 100) // Sliced for brevity
|
|
1851
|
-
* })
|
|
1852
|
-
* ```
|
|
1853
|
-
*
|
|
1854
|
-
* ```txt
|
|
1855
|
-
* {
|
|
1856
|
-
* id: 'audio_67117718c6008190a3afad3e3054b9b6',
|
|
1857
|
-
* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',
|
|
1858
|
-
* expires_at: 1729201448,
|
|
1859
|
-
* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'
|
|
1860
|
-
* }
|
|
1861
|
-
* ```
|
|
1862
|
-
* </details>
|
|
1863
|
-
*
|
|
1864
|
-
* <br />
|
|
1865
|
-
*
|
|
1866
|
-
* <details>
|
|
1867
|
-
* <summary><strong>Audio Outputs</strong></summary>
|
|
1868
|
-
*
|
|
1869
|
-
* ```typescript
|
|
1870
|
-
* import { ChatOpenAI } from "@langchain/openai";
|
|
1871
|
-
*
|
|
1872
|
-
* const modelWithAudioOutput = new ChatOpenAI({
|
|
1873
|
-
* model: "gpt-4o-audio-preview",
|
|
1874
|
-
* // You may also pass these fields to `.withConfig` as a call argument.
|
|
1875
|
-
* modalities: ["text", "audio"], // Specifies that the model should output audio.
|
|
1876
|
-
* audio: {
|
|
1877
|
-
* voice: "alloy",
|
|
1878
|
-
* format: "wav",
|
|
1879
|
-
* },
|
|
1880
|
-
* });
|
|
1881
|
-
*
|
|
1882
|
-
* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats.");
|
|
1883
|
-
* const castAudioContent = audioOutputResult.additional_kwargs.audio as Record<string, any>;
|
|
1884
|
-
*
|
|
1885
|
-
* console.log({
|
|
1886
|
-
* ...castAudioContent,
|
|
1887
|
-
* data: castAudioContent.data.slice(0, 100) // Sliced for brevity
|
|
1888
|
-
* })
|
|
1889
|
-
* ```
|
|
1890
|
-
*
|
|
1891
|
-
* ```txt
|
|
1892
|
-
* {
|
|
1893
|
-
* id: 'audio_67117718c6008190a3afad3e3054b9b6',
|
|
1894
|
-
* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',
|
|
1895
|
-
* expires_at: 1729201448,
|
|
1896
|
-
* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'
|
|
1897
|
-
* }
|
|
1898
|
-
* ```
|
|
1899
|
-
* </details>
|
|
1900
|
-
*
|
|
1901
|
-
* <br />
|
|
1902
|
-
*/
|
|
1903
|
-
var ChatOpenAI = class ChatOpenAI extends BaseChatOpenAI {
|
|
1904
|
-
/**
|
|
1905
|
-
* Whether to use the responses API for all requests. If `false` the responses API will be used
|
|
1906
|
-
* only when required in order to fulfill the request.
|
|
1907
|
-
*/
|
|
1908
|
-
useResponsesApi = false;
|
|
1909
|
-
responses;
|
|
1910
|
-
completions;
|
|
1911
|
-
get lc_serializable_keys() {
|
|
1912
|
-
return [...super.lc_serializable_keys, "useResponsesApi"];
|
|
1913
|
-
}
|
|
1914
|
-
constructor(fields) {
|
|
1915
|
-
super(fields);
|
|
1916
|
-
this.fields = fields;
|
|
1917
|
-
this.useResponsesApi = fields?.useResponsesApi ?? false;
|
|
1918
|
-
this.responses = fields?.responses ?? new ChatOpenAIResponses(fields);
|
|
1919
|
-
this.completions = fields?.completions ?? new ChatOpenAICompletions(fields);
|
|
1920
|
-
}
|
|
1921
|
-
_useResponsesApi(options) {
|
|
1922
|
-
const usesBuiltInTools = options?.tools?.some(isBuiltInTool);
|
|
1923
|
-
const hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null;
|
|
1924
|
-
const hasCustomTools = options?.tools?.some(isOpenAICustomTool);
|
|
1925
|
-
return this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools;
|
|
1926
|
-
}
|
|
1927
|
-
getLsParams(options) {
|
|
1928
|
-
const optionsWithDefaults = this._combineCallOptions(options);
|
|
1929
|
-
if (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults);
|
|
1930
|
-
return this.completions.getLsParams(optionsWithDefaults);
|
|
1931
|
-
}
|
|
1932
|
-
invocationParams(options) {
|
|
1933
|
-
const optionsWithDefaults = this._combineCallOptions(options);
|
|
1934
|
-
if (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults);
|
|
1935
|
-
return this.completions.invocationParams(optionsWithDefaults);
|
|
1936
|
-
}
|
|
1937
|
-
/** @ignore */
|
|
1938
|
-
async _generate(messages, options, runManager) {
|
|
1939
|
-
if (this._useResponsesApi(options)) return this.responses._generate(messages, options);
|
|
1940
|
-
return this.completions._generate(messages, options, runManager);
|
|
1941
|
-
}
|
|
1942
|
-
async *_streamResponseChunks(messages, options, runManager) {
|
|
1943
|
-
if (this._useResponsesApi(options)) {
|
|
1944
|
-
yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
|
|
1945
|
-
return;
|
|
1946
|
-
}
|
|
1947
|
-
yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
|
|
1948
|
-
}
|
|
1949
|
-
withConfig(config) {
|
|
1950
|
-
const newModel = new ChatOpenAI(this.fields);
|
|
1951
|
-
newModel.defaultOptions = {
|
|
1952
|
-
...this.defaultOptions,
|
|
1953
|
-
...config
|
|
1954
|
-
};
|
|
1955
|
-
return newModel;
|
|
1956
|
-
}
|
|
1957
|
-
};
|
|
1958
|
-
|
|
1959
|
-
//#endregion
|
|
1960
|
-
export { BaseChatOpenAI, ChatOpenAI, ChatOpenAICompletions, ChatOpenAIResponses };
|
|
1961
|
-
//# sourceMappingURL=chat_models.js.map
|