@langchain/openai 0.5.18 → 0.6.0

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