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