@langchain/openai 0.6.16 → 1.0.0-alpha.2

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