@langchain/openai 0.6.9 → 1.0.0-alpha.1

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