@langchain/openai 0.6.8 → 1.0.0-alpha.1

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