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