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