@langchain/openai 0.5.18 → 0.6.0

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