@langchain/openai 1.0.0-alpha.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/azure/chat_models/common.cjs +130 -0
  3. package/dist/azure/chat_models/common.cjs.map +1 -0
  4. package/dist/azure/chat_models/common.d.cts +16 -0
  5. package/dist/azure/chat_models/common.d.cts.map +1 -0
  6. package/dist/azure/chat_models/common.d.ts +16 -0
  7. package/dist/azure/chat_models/common.d.ts.map +1 -0
  8. package/dist/azure/chat_models/common.js +124 -0
  9. package/dist/azure/chat_models/common.js.map +1 -0
  10. package/dist/azure/chat_models/completions.cjs +50 -0
  11. package/dist/azure/chat_models/completions.cjs.map +1 -0
  12. package/dist/azure/chat_models/completions.d.cts +29 -0
  13. package/dist/azure/chat_models/completions.d.cts.map +1 -0
  14. package/dist/azure/chat_models/completions.d.ts +29 -0
  15. package/dist/azure/chat_models/completions.d.ts.map +1 -0
  16. package/dist/azure/chat_models/completions.js +50 -0
  17. package/dist/azure/chat_models/completions.js.map +1 -0
  18. package/dist/azure/{chat_models.cjs → chat_models/index.cjs} +14 -214
  19. package/dist/azure/chat_models/index.cjs.map +1 -0
  20. package/dist/azure/{chat_models.d.ts → chat_models/index.d.cts} +6 -11
  21. package/dist/azure/chat_models/index.d.cts.map +1 -0
  22. package/dist/azure/{chat_models.d.cts → chat_models/index.d.ts} +6 -11
  23. package/dist/azure/chat_models/index.d.ts.map +1 -0
  24. package/dist/azure/{chat_models.js → chat_models/index.js} +6 -205
  25. package/dist/azure/chat_models/index.js.map +1 -0
  26. package/dist/azure/chat_models/responses.cjs +50 -0
  27. package/dist/azure/chat_models/responses.cjs.map +1 -0
  28. package/dist/azure/chat_models/responses.d.cts +29 -0
  29. package/dist/azure/chat_models/responses.d.cts.map +1 -0
  30. package/dist/azure/chat_models/responses.d.ts +29 -0
  31. package/dist/azure/chat_models/responses.d.ts.map +1 -0
  32. package/dist/azure/chat_models/responses.js +50 -0
  33. package/dist/azure/chat_models/responses.js.map +1 -0
  34. package/dist/chat_models/base.cjs +533 -0
  35. package/dist/chat_models/base.cjs.map +1 -0
  36. package/dist/chat_models/base.d.cts +272 -0
  37. package/dist/chat_models/base.d.cts.map +1 -0
  38. package/dist/chat_models/base.d.ts +272 -0
  39. package/dist/chat_models/base.d.ts.map +1 -0
  40. package/dist/chat_models/base.js +532 -0
  41. package/dist/chat_models/base.js.map +1 -0
  42. package/dist/chat_models/completions.cjs +258 -0
  43. package/dist/chat_models/completions.cjs.map +1 -0
  44. package/dist/chat_models/completions.d.cts +44 -0
  45. package/dist/chat_models/completions.d.cts.map +1 -0
  46. package/dist/chat_models/completions.d.ts +44 -0
  47. package/dist/chat_models/completions.d.ts.map +1 -0
  48. package/dist/chat_models/completions.js +257 -0
  49. package/dist/chat_models/completions.js.map +1 -0
  50. package/dist/chat_models/index.cjs +608 -0
  51. package/dist/chat_models/index.cjs.map +1 -0
  52. package/dist/chat_models/index.d.cts +593 -0
  53. package/dist/chat_models/index.d.cts.map +1 -0
  54. package/dist/chat_models/index.d.ts +593 -0
  55. package/dist/chat_models/index.d.ts.map +1 -0
  56. package/dist/chat_models/index.js +608 -0
  57. package/dist/chat_models/index.js.map +1 -0
  58. package/dist/chat_models/responses.cjs +189 -0
  59. package/dist/chat_models/responses.cjs.map +1 -0
  60. package/dist/chat_models/responses.d.cts +62 -0
  61. package/dist/chat_models/responses.d.cts.map +1 -0
  62. package/dist/chat_models/responses.d.ts +62 -0
  63. package/dist/chat_models/responses.d.ts.map +1 -0
  64. package/dist/chat_models/responses.js +188 -0
  65. package/dist/chat_models/responses.js.map +1 -0
  66. package/dist/converters/completions.cjs +603 -0
  67. package/dist/converters/completions.cjs.map +1 -0
  68. package/dist/converters/completions.js +599 -0
  69. package/dist/converters/completions.js.map +1 -0
  70. package/dist/converters/responses.cjs +892 -0
  71. package/dist/converters/responses.cjs.map +1 -0
  72. package/dist/converters/responses.js +889 -0
  73. package/dist/converters/responses.js.map +1 -0
  74. package/dist/index.cjs +14 -9
  75. package/dist/index.d.cts +9 -4
  76. package/dist/index.d.ts +9 -4
  77. package/dist/index.js +8 -4
  78. package/dist/langchain-core/dist/callbacks/base.d.ts +1 -0
  79. package/dist/langchain-core/dist/callbacks/manager.d.ts +2 -0
  80. package/dist/langchain-core/dist/language_models/base.d.ts +5 -0
  81. package/dist/langchain-core/dist/language_models/chat_models.d.cts +13 -0
  82. package/dist/langchain-core/dist/language_models/chat_models.d.cts.map +1 -0
  83. package/dist/langchain-core/dist/language_models/chat_models.d.ts +20 -0
  84. package/dist/langchain-core/dist/language_models/chat_models.d.ts.map +1 -0
  85. package/dist/langchain-core/dist/runnables/base.d.ts +7 -0
  86. package/dist/langchain-core/dist/runnables/graph.d.ts +1 -0
  87. package/dist/langchain-core/dist/runnables/types.d.ts +2 -0
  88. package/dist/langchain-core/dist/tools/types.d.ts +5 -0
  89. package/dist/langchain-core/dist/tracers/base.d.ts +2 -0
  90. package/dist/langchain-core/dist/tracers/event_stream.d.ts +1 -0
  91. package/dist/langchain-core/dist/tracers/log_stream.d.ts +3 -0
  92. package/dist/langchain-core/dist/utils/types/index.d.ts +1 -0
  93. package/dist/langchain-core/dist/utils/types/zod.d.ts +1 -0
  94. package/dist/llms.cjs +1 -1
  95. package/dist/llms.d.cts +1 -1
  96. package/dist/llms.js +1 -1
  97. package/dist/utils/errors.cjs +1 -1
  98. package/dist/utils/errors.cjs.map +1 -1
  99. package/dist/utils/errors.js +1 -1
  100. package/dist/utils/errors.js.map +1 -1
  101. package/dist/utils/misc.js +2 -2
  102. package/dist/utils/misc.js.map +1 -1
  103. package/dist/utils/output.cjs +0 -12
  104. package/dist/utils/output.cjs.map +1 -1
  105. package/dist/utils/output.js +1 -12
  106. package/dist/utils/output.js.map +1 -1
  107. package/dist/utils/prompts.cjs +2 -2
  108. package/dist/utils/prompts.cjs.map +1 -1
  109. package/dist/utils/prompts.d.cts +1 -0
  110. package/dist/utils/prompts.d.cts.map +1 -1
  111. package/dist/utils/prompts.d.ts +1 -0
  112. package/dist/utils/prompts.d.ts.map +1 -1
  113. package/dist/utils/prompts.js +2 -2
  114. package/dist/utils/prompts.js.map +1 -1
  115. package/package.json +10 -7
  116. package/dist/azure/chat_models.cjs.map +0 -1
  117. package/dist/azure/chat_models.d.cts.map +0 -1
  118. package/dist/azure/chat_models.d.ts.map +0 -1
  119. package/dist/azure/chat_models.js.map +0 -1
  120. package/dist/chat_models.cjs +0 -1967
  121. package/dist/chat_models.cjs.map +0 -1
  122. package/dist/chat_models.d.cts +0 -933
  123. package/dist/chat_models.d.cts.map +0 -1
  124. package/dist/chat_models.d.ts +0 -933
  125. package/dist/chat_models.d.ts.map +0 -1
  126. package/dist/chat_models.js +0 -1963
  127. package/dist/chat_models.js.map +0 -1
  128. package/dist/utils/message_inputs.cjs +0 -139
  129. package/dist/utils/message_inputs.cjs.map +0 -1
  130. package/dist/utils/message_inputs.d.cts +0 -9
  131. package/dist/utils/message_inputs.d.cts.map +0 -1
  132. package/dist/utils/message_inputs.d.ts +0 -9
  133. package/dist/utils/message_inputs.d.ts.map +0 -1
  134. package/dist/utils/message_inputs.js +0 -137
  135. package/dist/utils/message_inputs.js.map +0 -1
  136. package/dist/utils/standard.cjs +0 -315
  137. package/dist/utils/standard.cjs.map +0 -1
  138. package/dist/utils/standard.js +0 -313
  139. package/dist/utils/standard.js.map +0 -1
@@ -1,1967 +0,0 @@
1
- const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
- const require_misc = require('./utils/misc.cjs');
3
- const require_azure = require('./utils/azure.cjs');
4
- const require_client = require('./utils/client.cjs');
5
- const require_tools = require('./utils/tools.cjs');
6
- const require_output = require('./utils/output.cjs');
7
- const require_standard = require('./utils/standard.cjs');
8
- const require_message_inputs = require('./utils/message_inputs.cjs');
9
- const openai = require_rolldown_runtime.__toESM(require("openai"));
10
- const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
11
- const __langchain_core_outputs = require_rolldown_runtime.__toESM(require("@langchain/core/outputs"));
12
- const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
13
- const __langchain_core_language_models_chat_models = require_rolldown_runtime.__toESM(require("@langchain/core/language_models/chat_models"));
14
- const __langchain_core_language_models_base = require_rolldown_runtime.__toESM(require("@langchain/core/language_models/base"));
15
- const __langchain_core_runnables = require_rolldown_runtime.__toESM(require("@langchain/core/runnables"));
16
- const __langchain_core_output_parsers = require_rolldown_runtime.__toESM(require("@langchain/core/output_parsers"));
17
- const __langchain_core_output_parsers_openai_tools = require_rolldown_runtime.__toESM(require("@langchain/core/output_parsers/openai_tools"));
18
- const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
19
- const __langchain_core_utils_json_schema = require_rolldown_runtime.__toESM(require("@langchain/core/utils/json_schema"));
20
-
21
- //#region src/chat_models.ts
22
- const _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__";
23
- /** @internal */
24
- var BaseChatOpenAI = class extends __langchain_core_language_models_chat_models.BaseChatModel {
25
- temperature;
26
- topP;
27
- frequencyPenalty;
28
- presencePenalty;
29
- n;
30
- logitBias;
31
- model = "gpt-3.5-turbo";
32
- modelKwargs;
33
- stop;
34
- stopSequences;
35
- user;
36
- timeout;
37
- streaming = false;
38
- streamUsage = true;
39
- maxTokens;
40
- logprobs;
41
- topLogprobs;
42
- apiKey;
43
- organization;
44
- __includeRawResponse;
45
- /** @internal */
46
- client;
47
- /** @internal */
48
- clientConfig;
49
- /**
50
- * Whether the model supports the `strict` argument when passing in tools.
51
- * If `undefined` the `strict` argument will not be passed to OpenAI.
52
- */
53
- supportsStrictToolCalling;
54
- audio;
55
- modalities;
56
- reasoning;
57
- /**
58
- * Must be set to `true` in tenancies with Zero Data Retention. Setting to `true` will disable
59
- * output storage in the Responses API, but this DOES NOT enable Zero Data Retention in your
60
- * OpenAI organization or project. This must be configured directly with OpenAI.
61
- *
62
- * See:
63
- * https://platform.openai.com/docs/guides/your-data
64
- * https://platform.openai.com/docs/api-reference/responses/create#responses-create-store
65
- *
66
- * @default false
67
- */
68
- zdrEnabled;
69
- /**
70
- * Service tier to use for this request. Can be "auto", "default", or "flex" or "priority".
71
- * Specifies the service tier for prioritization and latency optimization.
72
- */
73
- service_tier;
74
- /**
75
- * Used by OpenAI to cache responses for similar requests to optimize your cache
76
- * hit rates.
77
- * [Learn more](https://platform.openai.com/docs/guides/prompt-caching).
78
- */
79
- promptCacheKey;
80
- /**
81
- * The verbosity of the model's response.
82
- */
83
- verbosity;
84
- defaultOptions;
85
- _llmType() {
86
- return "openai";
87
- }
88
- static lc_name() {
89
- return "ChatOpenAI";
90
- }
91
- get callKeys() {
92
- return [
93
- ...super.callKeys,
94
- "options",
95
- "function_call",
96
- "functions",
97
- "tools",
98
- "tool_choice",
99
- "promptIndex",
100
- "response_format",
101
- "seed",
102
- "reasoning",
103
- "service_tier"
104
- ];
105
- }
106
- lc_serializable = true;
107
- get lc_secrets() {
108
- return {
109
- apiKey: "OPENAI_API_KEY",
110
- organization: "OPENAI_ORGANIZATION"
111
- };
112
- }
113
- get lc_aliases() {
114
- return {
115
- apiKey: "openai_api_key",
116
- modelName: "model"
117
- };
118
- }
119
- get lc_serializable_keys() {
120
- return [
121
- "configuration",
122
- "logprobs",
123
- "topLogprobs",
124
- "prefixMessages",
125
- "supportsStrictToolCalling",
126
- "modalities",
127
- "audio",
128
- "temperature",
129
- "maxTokens",
130
- "topP",
131
- "frequencyPenalty",
132
- "presencePenalty",
133
- "n",
134
- "logitBias",
135
- "user",
136
- "streaming",
137
- "streamUsage",
138
- "model",
139
- "modelName",
140
- "modelKwargs",
141
- "stop",
142
- "stopSequences",
143
- "timeout",
144
- "apiKey",
145
- "cache",
146
- "maxConcurrency",
147
- "maxRetries",
148
- "verbose",
149
- "callbacks",
150
- "tags",
151
- "metadata",
152
- "disableStreaming",
153
- "zdrEnabled",
154
- "reasoning",
155
- "promptCacheKey",
156
- "verbosity"
157
- ];
158
- }
159
- getLsParams(options) {
160
- const params = this.invocationParams(options);
161
- return {
162
- ls_provider: "openai",
163
- ls_model_name: this.model,
164
- ls_model_type: "chat",
165
- ls_temperature: params.temperature ?? void 0,
166
- ls_max_tokens: params.max_tokens ?? void 0,
167
- ls_stop: options.stop
168
- };
169
- }
170
- /** @ignore */
171
- _identifyingParams() {
172
- return {
173
- model_name: this.model,
174
- ...this.invocationParams(),
175
- ...this.clientConfig
176
- };
177
- }
178
- /**
179
- * Get the identifying parameters for the model
180
- */
181
- identifyingParams() {
182
- return this._identifyingParams();
183
- }
184
- constructor(fields) {
185
- super(fields ?? {});
186
- this.apiKey = fields?.apiKey ?? fields?.configuration?.apiKey ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("OPENAI_API_KEY");
187
- this.organization = fields?.configuration?.organization ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("OPENAI_ORGANIZATION");
188
- this.model = fields?.model ?? fields?.modelName ?? this.model;
189
- this.modelKwargs = fields?.modelKwargs ?? {};
190
- this.timeout = fields?.timeout;
191
- this.temperature = fields?.temperature ?? this.temperature;
192
- this.topP = fields?.topP ?? this.topP;
193
- this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty;
194
- this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty;
195
- this.logprobs = fields?.logprobs;
196
- this.topLogprobs = fields?.topLogprobs;
197
- this.n = fields?.n ?? this.n;
198
- this.logitBias = fields?.logitBias;
199
- this.stop = fields?.stopSequences ?? fields?.stop;
200
- this.stopSequences = this.stop;
201
- this.user = fields?.user;
202
- this.__includeRawResponse = fields?.__includeRawResponse;
203
- this.audio = fields?.audio;
204
- this.modalities = fields?.modalities;
205
- this.reasoning = fields?.reasoning;
206
- this.maxTokens = fields?.maxCompletionTokens ?? fields?.maxTokens;
207
- this.promptCacheKey = fields?.promptCacheKey ?? this.promptCacheKey;
208
- this.verbosity = fields?.verbosity ?? this.verbosity;
209
- this.disableStreaming = fields?.disableStreaming === true;
210
- this.streaming = fields?.streaming === true;
211
- if (this.disableStreaming) this.streaming = false;
212
- if (fields?.streaming === false) this.disableStreaming = true;
213
- this.streamUsage = fields?.streamUsage ?? this.streamUsage;
214
- if (this.disableStreaming) this.streamUsage = false;
215
- this.clientConfig = {
216
- apiKey: this.apiKey,
217
- organization: this.organization,
218
- dangerouslyAllowBrowser: true,
219
- ...fields?.configuration
220
- };
221
- if (fields?.supportsStrictToolCalling !== void 0) this.supportsStrictToolCalling = fields.supportsStrictToolCalling;
222
- if (fields?.service_tier !== void 0) this.service_tier = fields.service_tier;
223
- this.zdrEnabled = fields?.zdrEnabled ?? false;
224
- }
225
- /**
226
- * Returns backwards compatible reasoning parameters from constructor params and call options
227
- * @internal
228
- */
229
- _getReasoningParams(options) {
230
- if (!require_misc.isReasoningModel(this.model)) return;
231
- let reasoning;
232
- if (this.reasoning !== void 0) reasoning = {
233
- ...reasoning,
234
- ...this.reasoning
235
- };
236
- if (options?.reasoning !== void 0) reasoning = {
237
- ...reasoning,
238
- ...options.reasoning
239
- };
240
- return reasoning;
241
- }
242
- /**
243
- * Returns an openai compatible response format from a set of options
244
- * @internal
245
- */
246
- _getResponseFormat(resFormat) {
247
- if (resFormat && resFormat.type === "json_schema" && resFormat.json_schema.schema && (0, __langchain_core_utils_types.isInteropZodSchema)(resFormat.json_schema.schema)) return require_output.interopZodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, { description: resFormat.json_schema.description });
248
- return resFormat;
249
- }
250
- _combineCallOptions(additionalOptions) {
251
- return {
252
- ...this.defaultOptions,
253
- ...additionalOptions ?? {}
254
- };
255
- }
256
- /** @internal */
257
- _getClientOptions(options) {
258
- if (!this.client) {
259
- const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL };
260
- const endpoint = require_azure.getEndpoint(openAIEndpointConfig);
261
- const params = {
262
- ...this.clientConfig,
263
- baseURL: endpoint,
264
- timeout: this.timeout,
265
- maxRetries: 0
266
- };
267
- if (!params.baseURL) delete params.baseURL;
268
- this.client = new openai.OpenAI(params);
269
- }
270
- const requestOptions = {
271
- ...this.clientConfig,
272
- ...options
273
- };
274
- return requestOptions;
275
- }
276
- _convertChatOpenAIToolToCompletionsTool(tool, fields) {
277
- if (require_tools.isCustomTool(tool)) return require_tools.convertResponsesCustomTool(tool.metadata.customTool);
278
- if ((0, __langchain_core_language_models_base.isOpenAITool)(tool)) {
279
- if (fields?.strict !== void 0) return {
280
- ...tool,
281
- function: {
282
- ...tool.function,
283
- strict: fields.strict
284
- }
285
- };
286
- return tool;
287
- }
288
- return require_tools._convertToOpenAITool(tool, fields);
289
- }
290
- bindTools(tools, kwargs) {
291
- let strict;
292
- if (kwargs?.strict !== void 0) strict = kwargs.strict;
293
- else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;
294
- return this.withConfig({
295
- tools: tools.map((tool) => require_tools.isBuiltInTool(tool) ? tool : this._convertChatOpenAIToolToCompletionsTool(tool, { strict })),
296
- ...kwargs
297
- });
298
- }
299
- async stream(input, options) {
300
- return super.stream(input, this._combineCallOptions(options));
301
- }
302
- async invoke(input, options) {
303
- return super.invoke(input, this._combineCallOptions(options));
304
- }
305
- /** @ignore */
306
- _combineLLMOutput(...llmOutputs) {
307
- return llmOutputs.reduce((acc, llmOutput) => {
308
- if (llmOutput && llmOutput.tokenUsage) {
309
- acc.tokenUsage.completionTokens += llmOutput.tokenUsage.completionTokens ?? 0;
310
- acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0;
311
- acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0;
312
- }
313
- return acc;
314
- }, { tokenUsage: {
315
- completionTokens: 0,
316
- promptTokens: 0,
317
- totalTokens: 0
318
- } });
319
- }
320
- async getNumTokensFromMessages(messages) {
321
- let totalCount = 0;
322
- let tokensPerMessage = 0;
323
- let tokensPerName = 0;
324
- if (this.model === "gpt-3.5-turbo-0301") {
325
- tokensPerMessage = 4;
326
- tokensPerName = -1;
327
- } else {
328
- tokensPerMessage = 3;
329
- tokensPerName = 1;
330
- }
331
- const countPerMessage = await Promise.all(messages.map(async (message) => {
332
- const textCount = await this.getNumTokens(message.content);
333
- const roleCount = await this.getNumTokens(require_misc.messageToOpenAIRole(message));
334
- const nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0;
335
- let count = textCount + tokensPerMessage + roleCount + nameCount;
336
- const openAIMessage = message;
337
- if (openAIMessage._getType() === "function") count -= 2;
338
- if (openAIMessage.additional_kwargs?.function_call) count += 3;
339
- if (openAIMessage?.additional_kwargs.function_call?.name) count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name);
340
- if (openAIMessage.additional_kwargs.function_call?.arguments) try {
341
- count += await this.getNumTokens(JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments)));
342
- } catch (error) {
343
- console.error("Error parsing function arguments", error, JSON.stringify(openAIMessage.additional_kwargs.function_call));
344
- count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments);
345
- }
346
- totalCount += count;
347
- return count;
348
- }));
349
- totalCount += 3;
350
- return {
351
- totalCount,
352
- countPerMessage
353
- };
354
- }
355
- /** @internal */
356
- async _getNumTokensFromGenerations(generations) {
357
- const generationUsages = await Promise.all(generations.map(async (generation) => {
358
- if (generation.message.additional_kwargs?.function_call) return (await this.getNumTokensFromMessages([generation.message])).countPerMessage[0];
359
- else return await this.getNumTokens(generation.message.content);
360
- }));
361
- return generationUsages.reduce((a, b) => a + b, 0);
362
- }
363
- /** @internal */
364
- async _getEstimatedTokenCountFromPrompt(messages, functions, function_call) {
365
- let tokens = (await this.getNumTokensFromMessages(messages)).totalCount;
366
- if (functions && function_call !== "auto") {
367
- const promptDefinitions = require_tools.formatFunctionDefinitions(functions);
368
- tokens += await this.getNumTokens(promptDefinitions);
369
- tokens += 9;
370
- }
371
- if (functions && messages.find((m) => m._getType() === "system")) tokens -= 4;
372
- if (function_call === "none") tokens += 1;
373
- else if (typeof function_call === "object") tokens += await this.getNumTokens(function_call.name) + 4;
374
- return tokens;
375
- }
376
- /** @internal */
377
- _getStructuredOutputMethod(config) {
378
- const ensuredConfig = { ...config };
379
- if (!this.model.startsWith("gpt-3") && !this.model.startsWith("gpt-4-") && this.model !== "gpt-4") {
380
- if (ensuredConfig?.method === void 0) return "jsonSchema";
381
- } else if (ensuredConfig.method === "jsonSchema") console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);
382
- return ensuredConfig.method;
383
- }
384
- /**
385
- * Add structured output to the model.
386
- *
387
- * The OpenAI model family supports the following structured output methods:
388
- * - `jsonSchema`: Use the `response_format` field in the response to return a JSON schema. Only supported with the `gpt-4o-mini`,
389
- * `gpt-4o-mini-2024-07-18`, and `gpt-4o-2024-08-06` model snapshots and later.
390
- * - `functionCalling`: Function calling is useful when you are building an application that bridges the models and functionality
391
- * of your application.
392
- * - `jsonMode`: JSON mode is a more basic version of the Structured Outputs feature. While JSON mode ensures that model
393
- * output is valid JSON, Structured Outputs reliably matches the model's output to the schema you specify.
394
- * We recommend you use `functionCalling` or `jsonSchema` if it is supported for your use case.
395
- *
396
- * The default method is `functionCalling`.
397
- *
398
- * @see https://platform.openai.com/docs/guides/structured-outputs
399
- * @param outputSchema - The schema to use for structured output.
400
- * @param config - The structured output method options.
401
- * @returns The model with structured output.
402
- */
403
- withStructuredOutput(outputSchema, config) {
404
- let llm;
405
- let outputParser;
406
- const { schema, name, includeRaw } = {
407
- ...config,
408
- schema: outputSchema
409
- };
410
- if (config?.strict !== void 0 && config.method === "jsonMode") throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");
411
- const method = require_output.getStructuredOutputMethod(this.model, config?.method);
412
- if (method === "jsonMode") {
413
- if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) outputParser = __langchain_core_output_parsers.StructuredOutputParser.fromZodSchema(schema);
414
- else outputParser = new __langchain_core_output_parsers.JsonOutputParser();
415
- const asJsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(schema);
416
- llm = this.withConfig({
417
- response_format: { type: "json_object" },
418
- ls_structured_output_format: {
419
- kwargs: { method: "json_mode" },
420
- schema: {
421
- title: name ?? "extract",
422
- ...asJsonSchema
423
- }
424
- }
425
- });
426
- } else if (method === "jsonSchema") {
427
- const openaiJsonSchemaParams = {
428
- name: name ?? "extract",
429
- description: (0, __langchain_core_utils_types.getSchemaDescription)(schema),
430
- schema,
431
- strict: config?.strict
432
- };
433
- const asJsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(openaiJsonSchemaParams.schema);
434
- llm = this.withConfig({
435
- response_format: {
436
- type: "json_schema",
437
- json_schema: openaiJsonSchemaParams
438
- },
439
- ls_structured_output_format: {
440
- kwargs: { method: "json_schema" },
441
- schema: {
442
- title: openaiJsonSchemaParams.name,
443
- description: openaiJsonSchemaParams.description,
444
- ...asJsonSchema
445
- }
446
- }
447
- });
448
- if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) {
449
- const altParser = __langchain_core_output_parsers.StructuredOutputParser.fromZodSchema(schema);
450
- outputParser = __langchain_core_runnables.RunnableLambda.from((aiMessage) => {
451
- if ("parsed" in aiMessage.additional_kwargs) return aiMessage.additional_kwargs.parsed;
452
- return altParser;
453
- });
454
- } else outputParser = new __langchain_core_output_parsers.JsonOutputParser();
455
- } else {
456
- let functionName = name ?? "extract";
457
- if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) {
458
- const asJsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(schema);
459
- llm = this.withConfig({
460
- tools: [{
461
- type: "function",
462
- function: {
463
- name: functionName,
464
- description: asJsonSchema.description,
465
- parameters: asJsonSchema
466
- }
467
- }],
468
- tool_choice: {
469
- type: "function",
470
- function: { name: functionName }
471
- },
472
- ls_structured_output_format: {
473
- kwargs: { method: "function_calling" },
474
- schema: {
475
- title: functionName,
476
- ...asJsonSchema
477
- }
478
- },
479
- ...config?.strict !== void 0 ? { strict: config.strict } : {}
480
- });
481
- outputParser = new __langchain_core_output_parsers_openai_tools.JsonOutputKeyToolsParser({
482
- returnSingle: true,
483
- keyName: functionName,
484
- zodSchema: schema
485
- });
486
- } else {
487
- let openAIFunctionDefinition;
488
- if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) {
489
- openAIFunctionDefinition = schema;
490
- functionName = schema.name;
491
- } else {
492
- functionName = schema.title ?? functionName;
493
- openAIFunctionDefinition = {
494
- name: functionName,
495
- description: schema.description ?? "",
496
- parameters: schema
497
- };
498
- }
499
- const asJsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(schema);
500
- llm = this.withConfig({
501
- tools: [{
502
- type: "function",
503
- function: openAIFunctionDefinition
504
- }],
505
- tool_choice: {
506
- type: "function",
507
- function: { name: functionName }
508
- },
509
- ls_structured_output_format: {
510
- kwargs: { method: "function_calling" },
511
- schema: {
512
- title: functionName,
513
- ...asJsonSchema
514
- }
515
- },
516
- ...config?.strict !== void 0 ? { strict: config.strict } : {}
517
- });
518
- outputParser = new __langchain_core_output_parsers_openai_tools.JsonOutputKeyToolsParser({
519
- returnSingle: true,
520
- keyName: functionName
521
- });
522
- }
523
- }
524
- if (!includeRaw) return llm.pipe(outputParser);
525
- const parserAssign = __langchain_core_runnables.RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });
526
- const parserNone = __langchain_core_runnables.RunnablePassthrough.assign({ parsed: () => null });
527
- const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });
528
- return __langchain_core_runnables.RunnableSequence.from([{ raw: llm }, parsedWithFallback]);
529
- }
530
- };
531
- /**
532
- * OpenAI Responses API implementation.
533
- *
534
- * Will be exported in a later version of @langchain/openai.
535
- *
536
- * @internal
537
- */
538
- var ChatOpenAIResponses = class extends BaseChatOpenAI {
539
- invocationParams(options) {
540
- let strict;
541
- if (options?.strict !== void 0) strict = options.strict;
542
- else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;
543
- const params = {
544
- model: this.model,
545
- temperature: this.temperature,
546
- top_p: this.topP,
547
- user: this.user,
548
- stream: this.streaming,
549
- previous_response_id: options?.previous_response_id,
550
- truncation: options?.truncation,
551
- include: options?.include,
552
- tools: options?.tools?.length ? this._reduceChatOpenAITools(options.tools, {
553
- stream: this.streaming,
554
- strict
555
- }) : void 0,
556
- tool_choice: require_tools.isBuiltInToolChoice(options?.tool_choice) ? options?.tool_choice : (() => {
557
- const formatted = require_tools.formatToOpenAIToolChoice(options?.tool_choice);
558
- if (typeof formatted === "object" && "type" in formatted) {
559
- if (formatted.type === "function") return {
560
- type: "function",
561
- name: formatted.function.name
562
- };
563
- else if (formatted.type === "allowed_tools") return {
564
- type: "allowed_tools",
565
- mode: formatted.allowed_tools.mode,
566
- tools: formatted.allowed_tools.tools
567
- };
568
- else if (formatted.type === "custom") return {
569
- type: "custom",
570
- name: formatted.custom.name
571
- };
572
- }
573
- return void 0;
574
- })(),
575
- text: (() => {
576
- if (options?.text) return options.text;
577
- const format = this._getResponseFormat(options?.response_format);
578
- if (format?.type === "json_schema") {
579
- if (format.json_schema.schema != null) return {
580
- format: {
581
- type: "json_schema",
582
- schema: format.json_schema.schema,
583
- description: format.json_schema.description,
584
- name: format.json_schema.name,
585
- strict: format.json_schema.strict
586
- },
587
- verbosity: options?.verbosity
588
- };
589
- return void 0;
590
- }
591
- return {
592
- format,
593
- verbosity: options?.verbosity
594
- };
595
- })(),
596
- parallel_tool_calls: options?.parallel_tool_calls,
597
- max_output_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens,
598
- prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,
599
- ...this.zdrEnabled ? { store: false } : {},
600
- ...this.modelKwargs
601
- };
602
- const reasoning = this._getReasoningParams(options);
603
- if (reasoning !== void 0) params.reasoning = reasoning;
604
- return params;
605
- }
606
- async _generate(messages, options) {
607
- const invocationParams = this.invocationParams(options);
608
- if (invocationParams.stream) {
609
- const stream = this._streamResponseChunks(messages, options);
610
- let finalChunk;
611
- for await (const chunk of stream) {
612
- chunk.message.response_metadata = {
613
- ...chunk.generationInfo,
614
- ...chunk.message.response_metadata
615
- };
616
- finalChunk = finalChunk?.concat(chunk) ?? chunk;
617
- }
618
- return {
619
- generations: finalChunk ? [finalChunk] : [],
620
- llmOutput: { estimatedTokenUsage: (finalChunk?.message)?.usage_metadata }
621
- };
622
- } else {
623
- const input = this._convertMessagesToResponsesParams(messages);
624
- const data = await this.completionWithRetry({
625
- input,
626
- ...invocationParams,
627
- stream: false
628
- }, {
629
- signal: options?.signal,
630
- ...options?.options
631
- });
632
- return {
633
- generations: [{
634
- text: data.output_text,
635
- message: this._convertResponsesMessageToBaseMessage(data)
636
- }],
637
- llmOutput: {
638
- id: data.id,
639
- estimatedTokenUsage: data.usage ? {
640
- promptTokens: data.usage.input_tokens,
641
- completionTokens: data.usage.output_tokens,
642
- totalTokens: data.usage.total_tokens
643
- } : void 0
644
- }
645
- };
646
- }
647
- }
648
- async *_streamResponseChunks(messages, options, runManager) {
649
- const streamIterable = await this.completionWithRetry({
650
- ...this.invocationParams(options),
651
- input: this._convertMessagesToResponsesParams(messages),
652
- stream: true
653
- }, options);
654
- for await (const data of streamIterable) {
655
- const chunk = this._convertResponsesDeltaToBaseMessageChunk(data);
656
- if (chunk == null) continue;
657
- yield chunk;
658
- await runManager?.handleLLMNewToken(chunk.text || "", {
659
- prompt: options.promptIndex ?? 0,
660
- completion: 0
661
- }, void 0, void 0, void 0, { chunk });
662
- }
663
- }
664
- async completionWithRetry(request, requestOptions) {
665
- return this.caller.call(async () => {
666
- const clientOptions = this._getClientOptions(requestOptions);
667
- try {
668
- if (request.text?.format?.type === "json_schema" && !request.stream) return await this.client.responses.parse(request, clientOptions);
669
- return await this.client.responses.create(request, clientOptions);
670
- } catch (e) {
671
- const error = require_client.wrapOpenAIClientError(e);
672
- throw error;
673
- }
674
- });
675
- }
676
- /** @internal */
677
- _convertResponsesMessageToBaseMessage(response) {
678
- if (response.error) {
679
- const error = new Error(response.error.message);
680
- error.name = response.error.code;
681
- throw error;
682
- }
683
- let messageId;
684
- const content = [];
685
- const tool_calls = [];
686
- const invalid_tool_calls = [];
687
- const response_metadata = {
688
- model_provider: "openai",
689
- model: response.model,
690
- created_at: response.created_at,
691
- id: response.id,
692
- incomplete_details: response.incomplete_details,
693
- metadata: response.metadata,
694
- object: response.object,
695
- status: response.status,
696
- user: response.user,
697
- service_tier: response.service_tier,
698
- model_name: response.model
699
- };
700
- const additional_kwargs = {};
701
- for (const item of response.output) if (item.type === "message") {
702
- messageId = item.id;
703
- content.push(...item.content.flatMap((part) => {
704
- if (part.type === "output_text") {
705
- if ("parsed" in part && part.parsed != null) additional_kwargs.parsed = part.parsed;
706
- return {
707
- type: "text",
708
- text: part.text,
709
- annotations: part.annotations
710
- };
711
- }
712
- if (part.type === "refusal") {
713
- additional_kwargs.refusal = part.refusal;
714
- return [];
715
- }
716
- return part;
717
- }));
718
- } else if (item.type === "function_call") {
719
- const fnAdapter = {
720
- function: {
721
- name: item.name,
722
- arguments: item.arguments
723
- },
724
- id: item.call_id
725
- };
726
- try {
727
- tool_calls.push((0, __langchain_core_output_parsers_openai_tools.parseToolCall)(fnAdapter, { returnId: true }));
728
- } catch (e) {
729
- let errMessage;
730
- if (typeof e === "object" && e != null && "message" in e && typeof e.message === "string") errMessage = e.message;
731
- invalid_tool_calls.push((0, __langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(fnAdapter, errMessage));
732
- }
733
- additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {};
734
- if (item.id) additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id;
735
- } else if (item.type === "reasoning") additional_kwargs.reasoning = item;
736
- else if (item.type === "custom_tool_call") {
737
- const parsed = require_tools.parseCustomToolCall(item);
738
- if (parsed) tool_calls.push(parsed);
739
- else invalid_tool_calls.push((0, __langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(item, "Malformed custom tool call"));
740
- } else {
741
- additional_kwargs.tool_outputs ??= [];
742
- additional_kwargs.tool_outputs.push(item);
743
- }
744
- return new __langchain_core_messages.AIMessage({
745
- id: messageId,
746
- content,
747
- tool_calls,
748
- invalid_tool_calls,
749
- usage_metadata: require_output._convertOpenAIResponsesUsageToLangChainUsage(response.usage),
750
- additional_kwargs,
751
- response_metadata
752
- });
753
- }
754
- /** @internal */
755
- _convertResponsesDeltaToBaseMessageChunk(chunk) {
756
- const content = [];
757
- let generationInfo = {};
758
- let usage_metadata;
759
- const tool_call_chunks = [];
760
- const response_metadata = { model_provider: "openai" };
761
- const additional_kwargs = {};
762
- let id;
763
- if (chunk.type === "response.output_text.delta") content.push({
764
- type: "text",
765
- text: chunk.delta,
766
- index: chunk.content_index
767
- });
768
- else if (chunk.type === "response.output_text.annotation.added") content.push({
769
- type: "text",
770
- text: "",
771
- annotations: [chunk.annotation],
772
- index: chunk.content_index
773
- });
774
- else if (chunk.type === "response.output_item.added" && chunk.item.type === "message") id = chunk.item.id;
775
- else if (chunk.type === "response.output_item.added" && chunk.item.type === "function_call") {
776
- tool_call_chunks.push({
777
- type: "tool_call_chunk",
778
- name: chunk.item.name,
779
- args: chunk.item.arguments,
780
- id: chunk.item.call_id,
781
- index: chunk.output_index
782
- });
783
- additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = { [chunk.item.call_id]: chunk.item.id };
784
- } else if (chunk.type === "response.output_item.done" && [
785
- "web_search_call",
786
- "file_search_call",
787
- "computer_call",
788
- "code_interpreter_call",
789
- "mcp_call",
790
- "mcp_list_tools",
791
- "mcp_approval_request",
792
- "image_generation_call",
793
- "custom_tool_call"
794
- ].includes(chunk.item.type)) additional_kwargs.tool_outputs = [chunk.item];
795
- else if (chunk.type === "response.created") {
796
- response_metadata.id = chunk.response.id;
797
- response_metadata.model_name = chunk.response.model;
798
- response_metadata.model = chunk.response.model;
799
- } else if (chunk.type === "response.completed") {
800
- const msg = this._convertResponsesMessageToBaseMessage(chunk.response);
801
- usage_metadata = require_output._convertOpenAIResponsesUsageToLangChainUsage(chunk.response.usage);
802
- if (chunk.response.text?.format?.type === "json_schema") additional_kwargs.parsed ??= JSON.parse(msg.text);
803
- for (const [key, value] of Object.entries(chunk.response)) if (key !== "id") response_metadata[key] = value;
804
- } else if (chunk.type === "response.function_call_arguments.delta" || chunk.type === "response.custom_tool_call_input.delta") tool_call_chunks.push({
805
- type: "tool_call_chunk",
806
- args: chunk.delta,
807
- index: chunk.output_index
808
- });
809
- else if (chunk.type === "response.web_search_call.completed" || chunk.type === "response.file_search_call.completed") generationInfo = { tool_outputs: {
810
- id: chunk.item_id,
811
- type: chunk.type.replace("response.", "").replace(".completed", ""),
812
- status: "completed"
813
- } };
814
- else if (chunk.type === "response.refusal.done") additional_kwargs.refusal = chunk.refusal;
815
- else if (chunk.type === "response.output_item.added" && "item" in chunk && chunk.item.type === "reasoning") {
816
- const summary = chunk.item.summary ? chunk.item.summary.map((s, index) => ({
817
- ...s,
818
- index
819
- })) : void 0;
820
- additional_kwargs.reasoning = {
821
- id: chunk.item.id,
822
- type: chunk.item.type,
823
- ...summary ? { summary } : {}
824
- };
825
- } else if (chunk.type === "response.reasoning_summary_part.added") additional_kwargs.reasoning = {
826
- type: "reasoning",
827
- summary: [{
828
- ...chunk.part,
829
- index: chunk.summary_index
830
- }]
831
- };
832
- else if (chunk.type === "response.reasoning_summary_text.delta") additional_kwargs.reasoning = {
833
- type: "reasoning",
834
- summary: [{
835
- text: chunk.delta,
836
- type: "summary_text",
837
- index: chunk.summary_index
838
- }]
839
- };
840
- else if (chunk.type === "response.image_generation_call.partial_image") return null;
841
- else return null;
842
- return new __langchain_core_outputs.ChatGenerationChunk({
843
- text: content.map((part) => part.text).join(""),
844
- message: new __langchain_core_messages.AIMessageChunk({
845
- id,
846
- content,
847
- tool_call_chunks,
848
- usage_metadata,
849
- additional_kwargs,
850
- response_metadata
851
- }),
852
- generationInfo
853
- });
854
- }
855
- /** @internal */
856
- _convertMessagesToResponsesParams(messages) {
857
- return messages.flatMap((lcMsg) => {
858
- const responseMetadata = lcMsg.response_metadata;
859
- if (responseMetadata?.output_version === "v1") return require_standard._convertToResponsesMessageFromV1(lcMsg);
860
- const additional_kwargs = lcMsg.additional_kwargs;
861
- let role = require_misc.messageToOpenAIRole(lcMsg);
862
- if (role === "system" && require_misc.isReasoningModel(this.model)) role = "developer";
863
- if (role === "function") throw new Error("Function messages are not supported in Responses API");
864
- if (role === "tool") {
865
- const toolMessage = lcMsg;
866
- if (additional_kwargs?.type === "computer_call_output") {
867
- const output = (() => {
868
- if (typeof toolMessage.content === "string") return {
869
- type: "computer_screenshot",
870
- image_url: toolMessage.content
871
- };
872
- if (Array.isArray(toolMessage.content)) {
873
- const oaiScreenshot = toolMessage.content.find((i) => i.type === "computer_screenshot");
874
- if (oaiScreenshot) return oaiScreenshot;
875
- const lcImage = toolMessage.content.find((i) => i.type === "image_url");
876
- if (lcImage) return {
877
- type: "computer_screenshot",
878
- image_url: typeof lcImage.image_url === "string" ? lcImage.image_url : lcImage.image_url.url
879
- };
880
- }
881
- throw new Error("Invalid computer call output");
882
- })();
883
- return {
884
- type: "computer_call_output",
885
- output,
886
- call_id: toolMessage.tool_call_id
887
- };
888
- }
889
- if (toolMessage.additional_kwargs?.customTool) return {
890
- type: "custom_tool_call_output",
891
- call_id: toolMessage.tool_call_id,
892
- output: toolMessage.content
893
- };
894
- return {
895
- type: "function_call_output",
896
- call_id: toolMessage.tool_call_id,
897
- id: toolMessage.id?.startsWith("fc_") ? toolMessage.id : void 0,
898
- output: typeof toolMessage.content !== "string" ? JSON.stringify(toolMessage.content) : toolMessage.content
899
- };
900
- }
901
- if (role === "assistant") {
902
- if (!this.zdrEnabled && responseMetadata?.output != null && Array.isArray(responseMetadata?.output) && responseMetadata?.output.length > 0 && responseMetadata?.output.every((item) => "type" in item)) return responseMetadata?.output;
903
- const input = [];
904
- if (additional_kwargs?.reasoning && !this.zdrEnabled) {
905
- const reasoningItem = this._convertReasoningSummary(additional_kwargs.reasoning);
906
- input.push(reasoningItem);
907
- }
908
- let { content } = lcMsg;
909
- if (additional_kwargs?.refusal) {
910
- if (typeof content === "string") content = [{
911
- type: "output_text",
912
- text: content,
913
- annotations: []
914
- }];
915
- content = [...content, {
916
- type: "refusal",
917
- refusal: additional_kwargs.refusal
918
- }];
919
- }
920
- if (typeof content === "string" || content.length > 0) input.push({
921
- type: "message",
922
- role: "assistant",
923
- ...lcMsg.id && !this.zdrEnabled && lcMsg.id.startsWith("msg_") ? { id: lcMsg.id } : {},
924
- content: require_misc.iife(() => {
925
- if (typeof content === "string") return content;
926
- return content.flatMap((item) => {
927
- if (item.type === "text") return {
928
- type: "output_text",
929
- text: item.text,
930
- annotations: item.annotations ?? []
931
- };
932
- if (item.type === "output_text" || item.type === "refusal") return item;
933
- return [];
934
- });
935
- })
936
- });
937
- const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];
938
- if ((0, __langchain_core_messages.isAIMessage)(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => {
939
- if (require_tools.isCustomToolCall(toolCall)) return {
940
- type: "custom_tool_call",
941
- id: toolCall.call_id,
942
- call_id: toolCall.id ?? "",
943
- input: toolCall.args.input,
944
- name: toolCall.name
945
- };
946
- return {
947
- type: "function_call",
948
- name: toolCall.name,
949
- arguments: JSON.stringify(toolCall.args),
950
- call_id: toolCall.id,
951
- ...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}
952
- };
953
- }));
954
- else if (additional_kwargs?.tool_calls) input.push(...additional_kwargs.tool_calls.map((toolCall) => ({
955
- type: "function_call",
956
- name: toolCall.function.name,
957
- call_id: toolCall.id,
958
- arguments: toolCall.function.arguments,
959
- ...this.zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}
960
- })));
961
- const toolOutputs = (responseMetadata?.output)?.length ? responseMetadata?.output : additional_kwargs.tool_outputs;
962
- const fallthroughCallTypes = [
963
- "computer_call",
964
- "mcp_call",
965
- "code_interpreter_call",
966
- "image_generation_call"
967
- ];
968
- if (toolOutputs != null) {
969
- const castToolOutputs = toolOutputs;
970
- const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type));
971
- if (fallthroughCalls.length > 0) input.push(...fallthroughCalls);
972
- }
973
- return input;
974
- }
975
- if (role === "user" || role === "system" || role === "developer") {
976
- if (typeof lcMsg.content === "string") return {
977
- type: "message",
978
- role,
979
- content: lcMsg.content
980
- };
981
- const messages$1 = [];
982
- const content = lcMsg.content.flatMap((item) => {
983
- if (item.type === "mcp_approval_response") messages$1.push({
984
- type: "mcp_approval_response",
985
- approval_request_id: item.approval_request_id,
986
- approve: item.approve
987
- });
988
- if ((0, __langchain_core_messages.isDataContentBlock)(item)) return (0, __langchain_core_messages.convertToProviderContentBlock)(item, require_message_inputs.completionsApiContentBlockConverter);
989
- if (item.type === "text") return {
990
- type: "input_text",
991
- text: item.text
992
- };
993
- if (item.type === "image_url") {
994
- const imageUrl = require_misc.iife(() => {
995
- if (typeof item.image_url === "string") return item.image_url;
996
- else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) return item.image_url.url;
997
- return void 0;
998
- });
999
- const detail = require_misc.iife(() => {
1000
- if (typeof item.image_url === "string") return "auto";
1001
- else if (typeof item.image_url === "object" && item.image_url !== null && "detail" in item.image_url) return item.image_url.detail;
1002
- return void 0;
1003
- });
1004
- return {
1005
- type: "input_image",
1006
- image_url: imageUrl,
1007
- detail
1008
- };
1009
- }
1010
- if (item.type === "input_text" || item.type === "input_image" || item.type === "input_file") return item;
1011
- return [];
1012
- });
1013
- if (content.length > 0) messages$1.push({
1014
- type: "message",
1015
- role,
1016
- content
1017
- });
1018
- return messages$1;
1019
- }
1020
- console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`);
1021
- return [];
1022
- });
1023
- }
1024
- /** @internal */
1025
- _convertReasoningSummary(reasoning) {
1026
- const summary = (reasoning.summary.length > 1 ? reasoning.summary.reduce((acc, curr) => {
1027
- const last = acc.at(-1);
1028
- if (last.index === curr.index) last.text += curr.text;
1029
- else acc.push(curr);
1030
- return acc;
1031
- }, [{ ...reasoning.summary[0] }]) : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index")));
1032
- return {
1033
- ...reasoning,
1034
- summary
1035
- };
1036
- }
1037
- /** @internal */
1038
- _reduceChatOpenAITools(tools, fields) {
1039
- const reducedTools = [];
1040
- for (const tool of tools) if (require_tools.isBuiltInTool(tool)) {
1041
- if (tool.type === "image_generation" && fields?.stream) tool.partial_images = 1;
1042
- reducedTools.push(tool);
1043
- } else if ((0, __langchain_core_language_models_base.isOpenAITool)(tool)) reducedTools.push({
1044
- type: "function",
1045
- name: tool.function.name,
1046
- parameters: tool.function.parameters,
1047
- description: tool.function.description,
1048
- strict: fields?.strict ?? null
1049
- });
1050
- else if (require_tools.isOpenAICustomTool(tool)) reducedTools.push(require_tools.convertCompletionsCustomTool(tool));
1051
- return reducedTools;
1052
- }
1053
- };
1054
- /**
1055
- * OpenAI Completions API implementation.
1056
- * @internal
1057
- */
1058
- var ChatOpenAICompletions = class extends BaseChatOpenAI {
1059
- /** @internal */
1060
- invocationParams(options, extra) {
1061
- let strict;
1062
- if (options?.strict !== void 0) strict = options.strict;
1063
- else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling;
1064
- let streamOptionsConfig = {};
1065
- if (options?.stream_options !== void 0) streamOptionsConfig = { stream_options: options.stream_options };
1066
- else if (this.streamUsage && (this.streaming || extra?.streaming)) streamOptionsConfig = { stream_options: { include_usage: true } };
1067
- const params = {
1068
- model: this.model,
1069
- temperature: this.temperature,
1070
- top_p: this.topP,
1071
- frequency_penalty: this.frequencyPenalty,
1072
- presence_penalty: this.presencePenalty,
1073
- logprobs: this.logprobs,
1074
- top_logprobs: this.topLogprobs,
1075
- n: this.n,
1076
- logit_bias: this.logitBias,
1077
- stop: options?.stop ?? this.stopSequences,
1078
- user: this.user,
1079
- stream: this.streaming,
1080
- functions: options?.functions,
1081
- function_call: options?.function_call,
1082
- tools: options?.tools?.length ? options.tools.map((tool) => this._convertChatOpenAIToolToCompletionsTool(tool, { strict })) : void 0,
1083
- tool_choice: require_tools.formatToOpenAIToolChoice(options?.tool_choice),
1084
- response_format: this._getResponseFormat(options?.response_format),
1085
- seed: options?.seed,
1086
- ...streamOptionsConfig,
1087
- parallel_tool_calls: options?.parallel_tool_calls,
1088
- ...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {},
1089
- ...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {},
1090
- ...this.modelKwargs,
1091
- prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,
1092
- verbosity: options?.verbosity ?? this.verbosity
1093
- };
1094
- if (options?.prediction !== void 0) params.prediction = options.prediction;
1095
- if (this.service_tier !== void 0) params.service_tier = this.service_tier;
1096
- if (options?.service_tier !== void 0) params.service_tier = options.service_tier;
1097
- const reasoning = this._getReasoningParams(options);
1098
- if (reasoning !== void 0 && reasoning.effort !== void 0) params.reasoning_effort = reasoning.effort;
1099
- if (require_misc.isReasoningModel(params.model)) params.max_completion_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens;
1100
- else params.max_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens;
1101
- return params;
1102
- }
1103
- async _generate(messages, options, runManager) {
1104
- const usageMetadata = {};
1105
- const params = this.invocationParams(options);
1106
- const messagesMapped = require_message_inputs._convertMessagesToOpenAIParams(messages, this.model);
1107
- if (params.stream) {
1108
- const stream = this._streamResponseChunks(messages, options, runManager);
1109
- const finalChunks = {};
1110
- for await (const chunk of stream) {
1111
- chunk.message.response_metadata = {
1112
- ...chunk.generationInfo,
1113
- ...chunk.message.response_metadata
1114
- };
1115
- const index = chunk.generationInfo?.completion ?? 0;
1116
- if (finalChunks[index] === void 0) finalChunks[index] = chunk;
1117
- else finalChunks[index] = finalChunks[index].concat(chunk);
1118
- }
1119
- const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value);
1120
- const { functions, function_call } = this.invocationParams(options);
1121
- const promptTokenUsage = await this._getEstimatedTokenCountFromPrompt(messages, functions, function_call);
1122
- const completionTokenUsage = await this._getNumTokensFromGenerations(generations);
1123
- usageMetadata.input_tokens = promptTokenUsage;
1124
- usageMetadata.output_tokens = completionTokenUsage;
1125
- usageMetadata.total_tokens = promptTokenUsage + completionTokenUsage;
1126
- return {
1127
- generations,
1128
- llmOutput: { estimatedTokenUsage: {
1129
- promptTokens: usageMetadata.input_tokens,
1130
- completionTokens: usageMetadata.output_tokens,
1131
- totalTokens: usageMetadata.total_tokens
1132
- } }
1133
- };
1134
- } else {
1135
- const data = await this.completionWithRetry({
1136
- ...params,
1137
- stream: false,
1138
- messages: messagesMapped
1139
- }, {
1140
- signal: options?.signal,
1141
- ...options?.options
1142
- });
1143
- const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {};
1144
- if (completionTokens) usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens;
1145
- if (promptTokens) usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens;
1146
- if (totalTokens) usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens;
1147
- if (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) usageMetadata.input_token_details = {
1148
- ...promptTokensDetails?.audio_tokens !== null && { audio: promptTokensDetails?.audio_tokens },
1149
- ...promptTokensDetails?.cached_tokens !== null && { cache_read: promptTokensDetails?.cached_tokens }
1150
- };
1151
- if (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) usageMetadata.output_token_details = {
1152
- ...completionTokensDetails?.audio_tokens !== null && { audio: completionTokensDetails?.audio_tokens },
1153
- ...completionTokensDetails?.reasoning_tokens !== null && { reasoning: completionTokensDetails?.reasoning_tokens }
1154
- };
1155
- const generations = [];
1156
- for (const part of data?.choices ?? []) {
1157
- const text = part.message?.content ?? "";
1158
- const generation = {
1159
- text,
1160
- message: this._convertCompletionsMessageToBaseMessage(part.message ?? { role: "assistant" }, data)
1161
- };
1162
- generation.generationInfo = {
1163
- ...part.finish_reason ? { finish_reason: part.finish_reason } : {},
1164
- ...part.logprobs ? { logprobs: part.logprobs } : {}
1165
- };
1166
- if ((0, __langchain_core_messages.isAIMessage)(generation.message)) generation.message.usage_metadata = usageMetadata;
1167
- generation.message = new __langchain_core_messages.AIMessage(Object.fromEntries(Object.entries(generation.message).filter(([key]) => !key.startsWith("lc_"))));
1168
- generations.push(generation);
1169
- }
1170
- return {
1171
- generations,
1172
- llmOutput: { tokenUsage: {
1173
- promptTokens: usageMetadata.input_tokens,
1174
- completionTokens: usageMetadata.output_tokens,
1175
- totalTokens: usageMetadata.total_tokens
1176
- } }
1177
- };
1178
- }
1179
- }
1180
- async *_streamResponseChunks(messages, options, runManager) {
1181
- const messagesMapped = require_message_inputs._convertMessagesToOpenAIParams(messages, this.model);
1182
- const params = {
1183
- ...this.invocationParams(options, { streaming: true }),
1184
- messages: messagesMapped,
1185
- stream: true
1186
- };
1187
- let defaultRole;
1188
- const streamIterable = await this.completionWithRetry(params, options);
1189
- let usage;
1190
- for await (const data of streamIterable) {
1191
- const choice = data?.choices?.[0];
1192
- if (data.usage) usage = data.usage;
1193
- if (!choice) continue;
1194
- const { delta } = choice;
1195
- if (!delta) continue;
1196
- const chunk = this._convertCompletionsDeltaToBaseMessageChunk(delta, data, defaultRole);
1197
- defaultRole = delta.role ?? defaultRole;
1198
- const newTokenIndices = {
1199
- prompt: options.promptIndex ?? 0,
1200
- completion: choice.index ?? 0
1201
- };
1202
- if (typeof chunk.content !== "string") {
1203
- console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");
1204
- continue;
1205
- }
1206
- const generationInfo = { ...newTokenIndices };
1207
- if (choice.finish_reason != null) {
1208
- generationInfo.finish_reason = choice.finish_reason;
1209
- generationInfo.system_fingerprint = data.system_fingerprint;
1210
- generationInfo.model_name = data.model;
1211
- generationInfo.service_tier = data.service_tier;
1212
- }
1213
- if (this.logprobs) generationInfo.logprobs = choice.logprobs;
1214
- const generationChunk = new __langchain_core_outputs.ChatGenerationChunk({
1215
- message: chunk,
1216
- text: chunk.content,
1217
- generationInfo
1218
- });
1219
- yield generationChunk;
1220
- await runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk });
1221
- }
1222
- if (usage) {
1223
- const inputTokenDetails = {
1224
- ...usage.prompt_tokens_details?.audio_tokens !== null && { audio: usage.prompt_tokens_details?.audio_tokens },
1225
- ...usage.prompt_tokens_details?.cached_tokens !== null && { cache_read: usage.prompt_tokens_details?.cached_tokens }
1226
- };
1227
- const outputTokenDetails = {
1228
- ...usage.completion_tokens_details?.audio_tokens !== null && { audio: usage.completion_tokens_details?.audio_tokens },
1229
- ...usage.completion_tokens_details?.reasoning_tokens !== null && { reasoning: usage.completion_tokens_details?.reasoning_tokens }
1230
- };
1231
- const generationChunk = new __langchain_core_outputs.ChatGenerationChunk({
1232
- message: new __langchain_core_messages.AIMessageChunk({
1233
- content: "",
1234
- response_metadata: { usage: { ...usage } },
1235
- usage_metadata: {
1236
- input_tokens: usage.prompt_tokens,
1237
- output_tokens: usage.completion_tokens,
1238
- total_tokens: usage.total_tokens,
1239
- ...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails },
1240
- ...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails }
1241
- }
1242
- }),
1243
- text: ""
1244
- });
1245
- yield generationChunk;
1246
- }
1247
- if (options.signal?.aborted) throw new Error("AbortError");
1248
- }
1249
- async completionWithRetry(request, requestOptions) {
1250
- const clientOptions = this._getClientOptions(requestOptions);
1251
- const isParseableFormat = request.response_format && request.response_format.type === "json_schema";
1252
- return this.caller.call(async () => {
1253
- try {
1254
- if (isParseableFormat && !request.stream) return await this.client.chat.completions.parse(request, clientOptions);
1255
- else return await this.client.chat.completions.create(request, clientOptions);
1256
- } catch (e) {
1257
- const error = require_client.wrapOpenAIClientError(e);
1258
- throw error;
1259
- }
1260
- });
1261
- }
1262
- /** @internal */
1263
- _convertCompletionsMessageToBaseMessage(message, rawResponse) {
1264
- const rawToolCalls = message.tool_calls;
1265
- switch (message.role) {
1266
- case "assistant": {
1267
- const toolCalls = [];
1268
- const invalidToolCalls = [];
1269
- for (const rawToolCall of rawToolCalls ?? []) try {
1270
- toolCalls.push((0, __langchain_core_output_parsers_openai_tools.parseToolCall)(rawToolCall, { returnId: true }));
1271
- } catch (e) {
1272
- invalidToolCalls.push((0, __langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(rawToolCall, e.message));
1273
- }
1274
- const additional_kwargs = {
1275
- function_call: message.function_call,
1276
- tool_calls: rawToolCalls
1277
- };
1278
- if (this.__includeRawResponse !== void 0) additional_kwargs.__raw_response = rawResponse;
1279
- const response_metadata = {
1280
- model_provider: "openai",
1281
- model_name: rawResponse.model,
1282
- ...rawResponse.system_fingerprint ? {
1283
- usage: { ...rawResponse.usage },
1284
- system_fingerprint: rawResponse.system_fingerprint
1285
- } : {}
1286
- };
1287
- if (message.audio) additional_kwargs.audio = message.audio;
1288
- const content = require_output.handleMultiModalOutput(message.content || "", rawResponse.choices?.[0]?.message);
1289
- return new __langchain_core_messages.AIMessage({
1290
- content,
1291
- tool_calls: toolCalls,
1292
- invalid_tool_calls: invalidToolCalls,
1293
- additional_kwargs,
1294
- response_metadata,
1295
- id: rawResponse.id
1296
- });
1297
- }
1298
- default: return new __langchain_core_messages.ChatMessage(message.content || "", message.role ?? "unknown");
1299
- }
1300
- }
1301
- /** @internal */
1302
- _convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) {
1303
- const role = delta.role ?? defaultRole;
1304
- const content = delta.content ?? "";
1305
- let additional_kwargs;
1306
- if (delta.function_call) additional_kwargs = { function_call: delta.function_call };
1307
- else if (delta.tool_calls) additional_kwargs = { tool_calls: delta.tool_calls };
1308
- else additional_kwargs = {};
1309
- if (this.__includeRawResponse) additional_kwargs.__raw_response = rawResponse;
1310
- if (delta.audio) additional_kwargs.audio = {
1311
- ...delta.audio,
1312
- index: rawResponse.choices[0].index
1313
- };
1314
- const response_metadata = {
1315
- model_provider: "openai",
1316
- usage: { ...rawResponse.usage }
1317
- };
1318
- if (role === "user") return new __langchain_core_messages.HumanMessageChunk({
1319
- content,
1320
- response_metadata
1321
- });
1322
- else if (role === "assistant") {
1323
- const toolCallChunks = [];
1324
- if (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) toolCallChunks.push({
1325
- name: rawToolCall.function?.name,
1326
- args: rawToolCall.function?.arguments,
1327
- id: rawToolCall.id,
1328
- index: rawToolCall.index,
1329
- type: "tool_call_chunk"
1330
- });
1331
- return new __langchain_core_messages.AIMessageChunk({
1332
- content,
1333
- tool_call_chunks: toolCallChunks,
1334
- additional_kwargs,
1335
- id: rawResponse.id,
1336
- response_metadata
1337
- });
1338
- } else if (role === "system") return new __langchain_core_messages.SystemMessageChunk({
1339
- content,
1340
- response_metadata
1341
- });
1342
- else if (role === "developer") return new __langchain_core_messages.SystemMessageChunk({
1343
- content,
1344
- response_metadata,
1345
- additional_kwargs: { __openai_role__: "developer" }
1346
- });
1347
- else if (role === "function") return new __langchain_core_messages.FunctionMessageChunk({
1348
- content,
1349
- additional_kwargs,
1350
- name: delta.name,
1351
- response_metadata
1352
- });
1353
- else if (role === "tool") return new __langchain_core_messages.ToolMessageChunk({
1354
- content,
1355
- additional_kwargs,
1356
- tool_call_id: delta.tool_call_id,
1357
- response_metadata
1358
- });
1359
- else return new __langchain_core_messages.ChatMessageChunk({
1360
- content,
1361
- role,
1362
- response_metadata
1363
- });
1364
- }
1365
- };
1366
- /**
1367
- * OpenAI chat model integration.
1368
- *
1369
- * To use with Azure, import the `AzureChatOpenAI` class.
1370
- *
1371
- * Setup:
1372
- * Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
1373
- *
1374
- * ```bash
1375
- * npm install @langchain/openai
1376
- * export OPENAI_API_KEY="your-api-key"
1377
- * ```
1378
- *
1379
- * ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
1380
- *
1381
- * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
1382
- *
1383
- * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
1384
- * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:
1385
- *
1386
- * ```typescript
1387
- * // When calling `.withConfig`, call options should be passed via the first argument
1388
- * const llmWithArgsBound = llm.withConfig({
1389
- * stop: ["\n"],
1390
- * tools: [...],
1391
- * });
1392
- *
1393
- * // When calling `.bindTools`, call options should be passed via the second argument
1394
- * const llmWithTools = llm.bindTools(
1395
- * [...],
1396
- * {
1397
- * tool_choice: "auto",
1398
- * }
1399
- * );
1400
- * ```
1401
- *
1402
- * ## Examples
1403
- *
1404
- * <details open>
1405
- * <summary><strong>Instantiate</strong></summary>
1406
- *
1407
- * ```typescript
1408
- * import { ChatOpenAI } from '@langchain/openai';
1409
- *
1410
- * const llm = new ChatOpenAI({
1411
- * model: "gpt-4o-mini",
1412
- * temperature: 0,
1413
- * maxTokens: undefined,
1414
- * timeout: undefined,
1415
- * maxRetries: 2,
1416
- * // apiKey: "...",
1417
- * // configuration: {
1418
- * // baseURL: "...",
1419
- * // }
1420
- * // organization: "...",
1421
- * // other params...
1422
- * });
1423
- * ```
1424
- * </details>
1425
- *
1426
- * <br />
1427
- *
1428
- * <details>
1429
- * <summary><strong>Invoking</strong></summary>
1430
- *
1431
- * ```typescript
1432
- * const input = `Translate "I love programming" into French.`;
1433
- *
1434
- * // Models also accept a list of chat messages or a formatted prompt
1435
- * const result = await llm.invoke(input);
1436
- * console.log(result);
1437
- * ```
1438
- *
1439
- * ```txt
1440
- * AIMessage {
1441
- * "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
1442
- * "content": "J'adore la programmation.",
1443
- * "response_metadata": {
1444
- * "tokenUsage": {
1445
- * "completionTokens": 5,
1446
- * "promptTokens": 28,
1447
- * "totalTokens": 33
1448
- * },
1449
- * "finish_reason": "stop",
1450
- * "system_fingerprint": "fp_3aa7262c27"
1451
- * },
1452
- * "usage_metadata": {
1453
- * "input_tokens": 28,
1454
- * "output_tokens": 5,
1455
- * "total_tokens": 33
1456
- * }
1457
- * }
1458
- * ```
1459
- * </details>
1460
- *
1461
- * <br />
1462
- *
1463
- * <details>
1464
- * <summary><strong>Streaming Chunks</strong></summary>
1465
- *
1466
- * ```typescript
1467
- * for await (const chunk of await llm.stream(input)) {
1468
- * console.log(chunk);
1469
- * }
1470
- * ```
1471
- *
1472
- * ```txt
1473
- * AIMessageChunk {
1474
- * "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
1475
- * "content": ""
1476
- * }
1477
- * AIMessageChunk {
1478
- * "content": "J"
1479
- * }
1480
- * AIMessageChunk {
1481
- * "content": "'adore"
1482
- * }
1483
- * AIMessageChunk {
1484
- * "content": " la"
1485
- * }
1486
- * AIMessageChunk {
1487
- * "content": " programmation",,
1488
- * }
1489
- * AIMessageChunk {
1490
- * "content": ".",,
1491
- * }
1492
- * AIMessageChunk {
1493
- * "content": "",
1494
- * "response_metadata": {
1495
- * "finish_reason": "stop",
1496
- * "system_fingerprint": "fp_c9aa9c0491"
1497
- * },
1498
- * }
1499
- * AIMessageChunk {
1500
- * "content": "",
1501
- * "usage_metadata": {
1502
- * "input_tokens": 28,
1503
- * "output_tokens": 5,
1504
- * "total_tokens": 33
1505
- * }
1506
- * }
1507
- * ```
1508
- * </details>
1509
- *
1510
- * <br />
1511
- *
1512
- * <details>
1513
- * <summary><strong>Aggregate Streamed Chunks</strong></summary>
1514
- *
1515
- * ```typescript
1516
- * import { AIMessageChunk } from '@langchain/core/messages';
1517
- * import { concat } from '@langchain/core/utils/stream';
1518
- *
1519
- * const stream = await llm.stream(input);
1520
- * let full: AIMessageChunk | undefined;
1521
- * for await (const chunk of stream) {
1522
- * full = !full ? chunk : concat(full, chunk);
1523
- * }
1524
- * console.log(full);
1525
- * ```
1526
- *
1527
- * ```txt
1528
- * AIMessageChunk {
1529
- * "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
1530
- * "content": "J'adore la programmation.",
1531
- * "response_metadata": {
1532
- * "prompt": 0,
1533
- * "completion": 0,
1534
- * "finish_reason": "stop",
1535
- * },
1536
- * "usage_metadata": {
1537
- * "input_tokens": 28,
1538
- * "output_tokens": 5,
1539
- * "total_tokens": 33
1540
- * }
1541
- * }
1542
- * ```
1543
- * </details>
1544
- *
1545
- * <br />
1546
- *
1547
- * <details>
1548
- * <summary><strong>Bind tools</strong></summary>
1549
- *
1550
- * ```typescript
1551
- * import { z } from 'zod';
1552
- *
1553
- * const GetWeather = {
1554
- * name: "GetWeather",
1555
- * description: "Get the current weather in a given location",
1556
- * schema: z.object({
1557
- * location: z.string().describe("The city and state, e.g. San Francisco, CA")
1558
- * }),
1559
- * }
1560
- *
1561
- * const GetPopulation = {
1562
- * name: "GetPopulation",
1563
- * description: "Get the current population in a given location",
1564
- * schema: z.object({
1565
- * location: z.string().describe("The city and state, e.g. San Francisco, CA")
1566
- * }),
1567
- * }
1568
- *
1569
- * const llmWithTools = llm.bindTools(
1570
- * [GetWeather, GetPopulation],
1571
- * {
1572
- * // strict: true // enforce tool args schema is respected
1573
- * }
1574
- * );
1575
- * const aiMsg = await llmWithTools.invoke(
1576
- * "Which city is hotter today and which is bigger: LA or NY?"
1577
- * );
1578
- * console.log(aiMsg.tool_calls);
1579
- * ```
1580
- *
1581
- * ```txt
1582
- * [
1583
- * {
1584
- * name: 'GetWeather',
1585
- * args: { location: 'Los Angeles, CA' },
1586
- * type: 'tool_call',
1587
- * id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
1588
- * },
1589
- * {
1590
- * name: 'GetWeather',
1591
- * args: { location: 'New York, NY' },
1592
- * type: 'tool_call',
1593
- * id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
1594
- * },
1595
- * {
1596
- * name: 'GetPopulation',
1597
- * args: { location: 'Los Angeles, CA' },
1598
- * type: 'tool_call',
1599
- * id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
1600
- * },
1601
- * {
1602
- * name: 'GetPopulation',
1603
- * args: { location: 'New York, NY' },
1604
- * type: 'tool_call',
1605
- * id: 'call_s9KQB1UWj45LLGaEnjz0179q'
1606
- * }
1607
- * ]
1608
- * ```
1609
- * </details>
1610
- *
1611
- * <br />
1612
- *
1613
- * <details>
1614
- * <summary><strong>Structured Output</strong></summary>
1615
- *
1616
- * ```typescript
1617
- * import { z } from 'zod';
1618
- *
1619
- * const Joke = z.object({
1620
- * setup: z.string().describe("The setup of the joke"),
1621
- * punchline: z.string().describe("The punchline to the joke"),
1622
- * rating: z.number().nullable().describe("How funny the joke is, from 1 to 10")
1623
- * }).describe('Joke to tell user.');
1624
- *
1625
- * const structuredLlm = llm.withStructuredOutput(Joke, {
1626
- * name: "Joke",
1627
- * strict: true, // Optionally enable OpenAI structured outputs
1628
- * });
1629
- * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
1630
- * console.log(jokeResult);
1631
- * ```
1632
- *
1633
- * ```txt
1634
- * {
1635
- * setup: 'Why was the cat sitting on the computer?',
1636
- * punchline: 'Because it wanted to keep an eye on the mouse!',
1637
- * rating: 7
1638
- * }
1639
- * ```
1640
- * </details>
1641
- *
1642
- * <br />
1643
- *
1644
- * <details>
1645
- * <summary><strong>JSON Object Response Format</strong></summary>
1646
- *
1647
- * ```typescript
1648
- * const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } });
1649
- * const jsonLlmAiMsg = await jsonLlm.invoke(
1650
- * "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
1651
- * );
1652
- * console.log(jsonLlmAiMsg.content);
1653
- * ```
1654
- *
1655
- * ```txt
1656
- * {
1657
- * "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
1658
- * }
1659
- * ```
1660
- * </details>
1661
- *
1662
- * <br />
1663
- *
1664
- * <details>
1665
- * <summary><strong>Multimodal</strong></summary>
1666
- *
1667
- * ```typescript
1668
- * import { HumanMessage } from '@langchain/core/messages';
1669
- *
1670
- * const imageUrl = "https://example.com/image.jpg";
1671
- * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
1672
- * const base64Image = Buffer.from(imageData).toString('base64');
1673
- *
1674
- * const message = new HumanMessage({
1675
- * content: [
1676
- * { type: "text", text: "describe the weather in this image" },
1677
- * {
1678
- * type: "image_url",
1679
- * image_url: { url: `data:image/jpeg;base64,${base64Image}` },
1680
- * },
1681
- * ]
1682
- * });
1683
- *
1684
- * const imageDescriptionAiMsg = await llm.invoke([message]);
1685
- * console.log(imageDescriptionAiMsg.content);
1686
- * ```
1687
- *
1688
- * ```txt
1689
- * 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.
1690
- * ```
1691
- * </details>
1692
- *
1693
- * <br />
1694
- *
1695
- * <details>
1696
- * <summary><strong>Usage Metadata</strong></summary>
1697
- *
1698
- * ```typescript
1699
- * const aiMsgForMetadata = await llm.invoke(input);
1700
- * console.log(aiMsgForMetadata.usage_metadata);
1701
- * ```
1702
- *
1703
- * ```txt
1704
- * { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
1705
- * ```
1706
- * </details>
1707
- *
1708
- * <br />
1709
- *
1710
- * <details>
1711
- * <summary><strong>Logprobs</strong></summary>
1712
- *
1713
- * ```typescript
1714
- * const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true });
1715
- * const aiMsgForLogprobs = await logprobsLlm.invoke(input);
1716
- * console.log(aiMsgForLogprobs.response_metadata.logprobs);
1717
- * ```
1718
- *
1719
- * ```txt
1720
- * {
1721
- * content: [
1722
- * {
1723
- * token: 'J',
1724
- * logprob: -0.000050616763,
1725
- * bytes: [Array],
1726
- * top_logprobs: []
1727
- * },
1728
- * {
1729
- * token: "'",
1730
- * logprob: -0.01868736,
1731
- * bytes: [Array],
1732
- * top_logprobs: []
1733
- * },
1734
- * {
1735
- * token: 'ad',
1736
- * logprob: -0.0000030545007,
1737
- * bytes: [Array],
1738
- * top_logprobs: []
1739
- * },
1740
- * { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
1741
- * {
1742
- * token: ' la',
1743
- * logprob: -0.515404,
1744
- * bytes: [Array],
1745
- * top_logprobs: []
1746
- * },
1747
- * {
1748
- * token: ' programm',
1749
- * logprob: -0.0000118755715,
1750
- * bytes: [Array],
1751
- * top_logprobs: []
1752
- * },
1753
- * { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
1754
- * {
1755
- * token: '.',
1756
- * logprob: -0.0000037697225,
1757
- * bytes: [Array],
1758
- * top_logprobs: []
1759
- * }
1760
- * ],
1761
- * refusal: null
1762
- * }
1763
- * ```
1764
- * </details>
1765
- *
1766
- * <br />
1767
- *
1768
- * <details>
1769
- * <summary><strong>Response Metadata</strong></summary>
1770
- *
1771
- * ```typescript
1772
- * const aiMsgForResponseMetadata = await llm.invoke(input);
1773
- * console.log(aiMsgForResponseMetadata.response_metadata);
1774
- * ```
1775
- *
1776
- * ```txt
1777
- * {
1778
- * tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
1779
- * finish_reason: 'stop',
1780
- * system_fingerprint: 'fp_3aa7262c27'
1781
- * }
1782
- * ```
1783
- * </details>
1784
- *
1785
- * <br />
1786
- *
1787
- * <details>
1788
- * <summary><strong>JSON Schema Structured Output</strong></summary>
1789
- *
1790
- * ```typescript
1791
- * const llmForJsonSchema = new ChatOpenAI({
1792
- * model: "gpt-4o-2024-08-06",
1793
- * }).withStructuredOutput(
1794
- * z.object({
1795
- * command: z.string().describe("The command to execute"),
1796
- * expectedOutput: z.string().describe("The expected output of the command"),
1797
- * options: z
1798
- * .array(z.string())
1799
- * .describe("The options you can pass to the command"),
1800
- * }),
1801
- * {
1802
- * method: "jsonSchema",
1803
- * strict: true, // Optional when using the `jsonSchema` method
1804
- * }
1805
- * );
1806
- *
1807
- * const jsonSchemaRes = await llmForJsonSchema.invoke(
1808
- * "What is the command to list files in a directory?"
1809
- * );
1810
- * console.log(jsonSchemaRes);
1811
- * ```
1812
- *
1813
- * ```txt
1814
- * {
1815
- * command: 'ls',
1816
- * expectedOutput: 'A list of files and subdirectories within the specified directory.',
1817
- * options: [
1818
- * '-a: include directory entries whose names begin with a dot (.).',
1819
- * '-l: use a long listing format.',
1820
- * '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).',
1821
- * '-t: sort by time, newest first.',
1822
- * '-r: reverse order while sorting.',
1823
- * '-S: sort by file size, largest first.',
1824
- * '-R: list subdirectories recursively.'
1825
- * ]
1826
- * }
1827
- * ```
1828
- * </details>
1829
- *
1830
- * <br />
1831
- *
1832
- * <details>
1833
- * <summary><strong>Audio Outputs</strong></summary>
1834
- *
1835
- * ```typescript
1836
- * import { ChatOpenAI } from "@langchain/openai";
1837
- *
1838
- * const modelWithAudioOutput = new ChatOpenAI({
1839
- * model: "gpt-4o-audio-preview",
1840
- * // You may also pass these fields to `.withConfig` as a call argument.
1841
- * modalities: ["text", "audio"], // Specifies that the model should output audio.
1842
- * audio: {
1843
- * voice: "alloy",
1844
- * format: "wav",
1845
- * },
1846
- * });
1847
- *
1848
- * const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats.");
1849
- * const castMessageContent = audioOutputResult.content[0] as Record<string, any>;
1850
- *
1851
- * console.log({
1852
- * ...castMessageContent,
1853
- * data: castMessageContent.data.slice(0, 100) // Sliced for brevity
1854
- * })
1855
- * ```
1856
- *
1857
- * ```txt
1858
- * {
1859
- * id: 'audio_67117718c6008190a3afad3e3054b9b6',
1860
- * data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',
1861
- * expires_at: 1729201448,
1862
- * transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'
1863
- * }
1864
- * ```
1865
- * </details>
1866
- *
1867
- * <br />
1868
- *
1869
- * <details>
1870
- * <summary><strong>Audio Outputs</strong></summary>
1871
- *
1872
- * ```typescript
1873
- * import { ChatOpenAI } from "@langchain/openai";
1874
- *
1875
- * const modelWithAudioOutput = new ChatOpenAI({
1876
- * model: "gpt-4o-audio-preview",
1877
- * // You may also pass these fields to `.withConfig` as a call argument.
1878
- * modalities: ["text", "audio"], // Specifies that the model should output audio.
1879
- * audio: {
1880
- * voice: "alloy",
1881
- * format: "wav",
1882
- * },
1883
- * });
1884
- *
1885
- * const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats.");
1886
- * const castAudioContent = audioOutputResult.additional_kwargs.audio as Record<string, any>;
1887
- *
1888
- * console.log({
1889
- * ...castAudioContent,
1890
- * data: castAudioContent.data.slice(0, 100) // Sliced for brevity
1891
- * })
1892
- * ```
1893
- *
1894
- * ```txt
1895
- * {
1896
- * id: 'audio_67117718c6008190a3afad3e3054b9b6',
1897
- * data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',
1898
- * expires_at: 1729201448,
1899
- * transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'
1900
- * }
1901
- * ```
1902
- * </details>
1903
- *
1904
- * <br />
1905
- */
1906
- var ChatOpenAI = class ChatOpenAI extends BaseChatOpenAI {
1907
- /**
1908
- * Whether to use the responses API for all requests. If `false` the responses API will be used
1909
- * only when required in order to fulfill the request.
1910
- */
1911
- useResponsesApi = false;
1912
- responses;
1913
- completions;
1914
- get lc_serializable_keys() {
1915
- return [...super.lc_serializable_keys, "useResponsesApi"];
1916
- }
1917
- constructor(fields) {
1918
- super(fields);
1919
- this.fields = fields;
1920
- this.useResponsesApi = fields?.useResponsesApi ?? false;
1921
- this.responses = fields?.responses ?? new ChatOpenAIResponses(fields);
1922
- this.completions = fields?.completions ?? new ChatOpenAICompletions(fields);
1923
- }
1924
- _useResponsesApi(options) {
1925
- const usesBuiltInTools = options?.tools?.some(require_tools.isBuiltInTool);
1926
- const hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null;
1927
- const hasCustomTools = options?.tools?.some(require_tools.isOpenAICustomTool);
1928
- return this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools;
1929
- }
1930
- getLsParams(options) {
1931
- const optionsWithDefaults = this._combineCallOptions(options);
1932
- if (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults);
1933
- return this.completions.getLsParams(optionsWithDefaults);
1934
- }
1935
- invocationParams(options) {
1936
- const optionsWithDefaults = this._combineCallOptions(options);
1937
- if (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults);
1938
- return this.completions.invocationParams(optionsWithDefaults);
1939
- }
1940
- /** @ignore */
1941
- async _generate(messages, options, runManager) {
1942
- if (this._useResponsesApi(options)) return this.responses._generate(messages, options);
1943
- return this.completions._generate(messages, options, runManager);
1944
- }
1945
- async *_streamResponseChunks(messages, options, runManager) {
1946
- if (this._useResponsesApi(options)) {
1947
- yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
1948
- return;
1949
- }
1950
- yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
1951
- }
1952
- withConfig(config) {
1953
- const newModel = new ChatOpenAI(this.fields);
1954
- newModel.defaultOptions = {
1955
- ...this.defaultOptions,
1956
- ...config
1957
- };
1958
- return newModel;
1959
- }
1960
- };
1961
-
1962
- //#endregion
1963
- exports.BaseChatOpenAI = BaseChatOpenAI;
1964
- exports.ChatOpenAI = ChatOpenAI;
1965
- exports.ChatOpenAICompletions = ChatOpenAICompletions;
1966
- exports.ChatOpenAIResponses = ChatOpenAIResponses;
1967
- //# sourceMappingURL=chat_models.cjs.map