@langchain/openai 0.5.18 → 0.6.1

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