@langchain/openai 1.0.0-alpha.2 → 1.0.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 (110) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE +6 -6
  3. package/dist/azure/chat_models/common.cjs +130 -0
  4. package/dist/azure/chat_models/common.cjs.map +1 -0
  5. package/dist/azure/chat_models/common.d.cts +16 -0
  6. package/dist/azure/chat_models/common.d.cts.map +1 -0
  7. package/dist/azure/chat_models/common.d.ts +16 -0
  8. package/dist/azure/chat_models/common.d.ts.map +1 -0
  9. package/dist/azure/chat_models/common.js +124 -0
  10. package/dist/azure/chat_models/common.js.map +1 -0
  11. package/dist/azure/chat_models/completions.cjs +50 -0
  12. package/dist/azure/chat_models/completions.cjs.map +1 -0
  13. package/dist/azure/chat_models/completions.d.cts +29 -0
  14. package/dist/azure/chat_models/completions.d.cts.map +1 -0
  15. package/dist/azure/chat_models/completions.d.ts +29 -0
  16. package/dist/azure/chat_models/completions.d.ts.map +1 -0
  17. package/dist/azure/chat_models/completions.js +50 -0
  18. package/dist/azure/chat_models/completions.js.map +1 -0
  19. package/dist/azure/{chat_models.cjs → chat_models/index.cjs} +14 -214
  20. package/dist/azure/chat_models/index.cjs.map +1 -0
  21. package/dist/azure/{chat_models.d.ts → chat_models/index.d.cts} +6 -11
  22. package/dist/azure/chat_models/index.d.cts.map +1 -0
  23. package/dist/azure/{chat_models.d.cts → chat_models/index.d.ts} +6 -11
  24. package/dist/azure/chat_models/index.d.ts.map +1 -0
  25. package/dist/azure/{chat_models.js → chat_models/index.js} +6 -205
  26. package/dist/azure/chat_models/index.js.map +1 -0
  27. package/dist/azure/chat_models/responses.cjs +50 -0
  28. package/dist/azure/chat_models/responses.cjs.map +1 -0
  29. package/dist/azure/chat_models/responses.d.cts +29 -0
  30. package/dist/azure/chat_models/responses.d.cts.map +1 -0
  31. package/dist/azure/chat_models/responses.d.ts +29 -0
  32. package/dist/azure/chat_models/responses.d.ts.map +1 -0
  33. package/dist/azure/chat_models/responses.js +50 -0
  34. package/dist/azure/chat_models/responses.js.map +1 -0
  35. package/dist/chat_models/base.cjs +533 -0
  36. package/dist/chat_models/base.cjs.map +1 -0
  37. package/dist/chat_models/base.d.cts +272 -0
  38. package/dist/chat_models/base.d.cts.map +1 -0
  39. package/dist/chat_models/base.d.ts +272 -0
  40. package/dist/chat_models/base.d.ts.map +1 -0
  41. package/dist/chat_models/base.js +532 -0
  42. package/dist/chat_models/base.js.map +1 -0
  43. package/dist/chat_models/completions.cjs +328 -0
  44. package/dist/chat_models/completions.cjs.map +1 -0
  45. package/dist/chat_models/completions.d.cts +33 -0
  46. package/dist/chat_models/completions.d.cts.map +1 -0
  47. package/dist/chat_models/completions.d.ts +33 -0
  48. package/dist/chat_models/completions.d.ts.map +1 -0
  49. package/dist/chat_models/completions.js +327 -0
  50. package/dist/chat_models/completions.js.map +1 -0
  51. package/dist/chat_models/index.cjs +608 -0
  52. package/dist/chat_models/index.cjs.map +1 -0
  53. package/dist/chat_models/index.d.cts +593 -0
  54. package/dist/chat_models/index.d.cts.map +1 -0
  55. package/dist/chat_models/index.d.ts +593 -0
  56. package/dist/chat_models/index.d.ts.map +1 -0
  57. package/dist/chat_models/index.js +608 -0
  58. package/dist/chat_models/index.js.map +1 -0
  59. package/dist/chat_models/responses.cjs +550 -0
  60. package/dist/chat_models/responses.cjs.map +1 -0
  61. package/dist/chat_models/responses.d.cts +77 -0
  62. package/dist/chat_models/responses.d.cts.map +1 -0
  63. package/dist/chat_models/responses.d.ts +77 -0
  64. package/dist/chat_models/responses.d.ts.map +1 -0
  65. package/dist/chat_models/responses.js +549 -0
  66. package/dist/chat_models/responses.js.map +1 -0
  67. package/dist/index.cjs +14 -7
  68. package/dist/index.d.cts +9 -3
  69. package/dist/index.d.ts +9 -3
  70. package/dist/index.js +8 -3
  71. package/dist/langchain-core/dist/callbacks/base.d.ts +1 -0
  72. package/dist/langchain-core/dist/callbacks/manager.d.ts +2 -0
  73. package/dist/langchain-core/dist/language_models/base.d.ts +5 -0
  74. package/dist/langchain-core/dist/language_models/chat_models.d.cts +13 -0
  75. package/dist/langchain-core/dist/language_models/chat_models.d.cts.map +1 -0
  76. package/dist/langchain-core/dist/language_models/chat_models.d.ts +20 -0
  77. package/dist/langchain-core/dist/language_models/chat_models.d.ts.map +1 -0
  78. package/dist/langchain-core/dist/runnables/base.d.ts +7 -0
  79. package/dist/langchain-core/dist/runnables/graph.d.ts +1 -0
  80. package/dist/langchain-core/dist/runnables/types.d.ts +2 -0
  81. package/dist/langchain-core/dist/tools/types.d.ts +5 -0
  82. package/dist/langchain-core/dist/tracers/base.d.ts +2 -0
  83. package/dist/langchain-core/dist/tracers/event_stream.d.ts +1 -0
  84. package/dist/langchain-core/dist/tracers/log_stream.d.ts +3 -0
  85. package/dist/langchain-core/dist/utils/types/index.d.ts +1 -0
  86. package/dist/langchain-core/dist/utils/types/zod.d.ts +1 -0
  87. package/dist/llms.cjs +1 -1
  88. package/dist/llms.d.cts +1 -1
  89. package/dist/llms.js +1 -1
  90. package/dist/utils/message_inputs.cjs +1 -1
  91. package/dist/utils/message_inputs.js +1 -1
  92. package/dist/utils/misc.cjs +4 -1
  93. package/dist/utils/misc.cjs.map +1 -1
  94. package/dist/utils/misc.d.cts.map +1 -1
  95. package/dist/utils/misc.d.ts.map +1 -1
  96. package/dist/utils/misc.js +4 -1
  97. package/dist/utils/misc.js.map +1 -1
  98. package/package.json +11 -10
  99. package/dist/azure/chat_models.cjs.map +0 -1
  100. package/dist/azure/chat_models.d.cts.map +0 -1
  101. package/dist/azure/chat_models.d.ts.map +0 -1
  102. package/dist/azure/chat_models.js.map +0 -1
  103. package/dist/chat_models.cjs +0 -1965
  104. package/dist/chat_models.cjs.map +0 -1
  105. package/dist/chat_models.d.cts +0 -931
  106. package/dist/chat_models.d.cts.map +0 -1
  107. package/dist/chat_models.d.ts +0 -931
  108. package/dist/chat_models.d.ts.map +0 -1
  109. package/dist/chat_models.js +0 -1961
  110. package/dist/chat_models.js.map +0 -1
@@ -0,0 +1,608 @@
1
+ const require_tools = require('../utils/tools.cjs');
2
+ const require_base = require('./base.cjs');
3
+ const require_responses = require('./responses.cjs');
4
+ const require_completions = require('./completions.cjs');
5
+
6
+ //#region src/chat_models/index.ts
7
+ /**
8
+ * OpenAI chat model integration.
9
+ *
10
+ * To use with Azure, import the `AzureChatOpenAI` class.
11
+ *
12
+ * Setup:
13
+ * Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
14
+ *
15
+ * ```bash
16
+ * npm install @langchain/openai
17
+ * export OPENAI_API_KEY="your-api-key"
18
+ * ```
19
+ *
20
+ * ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
21
+ *
22
+ * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
23
+ *
24
+ * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
25
+ * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:
26
+ *
27
+ * ```typescript
28
+ * // When calling `.withConfig`, call options should be passed via the first argument
29
+ * const llmWithArgsBound = llm.withConfig({
30
+ * stop: ["\n"],
31
+ * tools: [...],
32
+ * });
33
+ *
34
+ * // When calling `.bindTools`, call options should be passed via the second argument
35
+ * const llmWithTools = llm.bindTools(
36
+ * [...],
37
+ * {
38
+ * tool_choice: "auto",
39
+ * }
40
+ * );
41
+ * ```
42
+ *
43
+ * ## Examples
44
+ *
45
+ * <details open>
46
+ * <summary><strong>Instantiate</strong></summary>
47
+ *
48
+ * ```typescript
49
+ * import { ChatOpenAI } from '@langchain/openai';
50
+ *
51
+ * const llm = new ChatOpenAI({
52
+ * model: "gpt-4o-mini",
53
+ * temperature: 0,
54
+ * maxTokens: undefined,
55
+ * timeout: undefined,
56
+ * maxRetries: 2,
57
+ * // apiKey: "...",
58
+ * // configuration: {
59
+ * // baseURL: "...",
60
+ * // }
61
+ * // organization: "...",
62
+ * // other params...
63
+ * });
64
+ * ```
65
+ * </details>
66
+ *
67
+ * <br />
68
+ *
69
+ * <details>
70
+ * <summary><strong>Invoking</strong></summary>
71
+ *
72
+ * ```typescript
73
+ * const input = `Translate "I love programming" into French.`;
74
+ *
75
+ * // Models also accept a list of chat messages or a formatted prompt
76
+ * const result = await llm.invoke(input);
77
+ * console.log(result);
78
+ * ```
79
+ *
80
+ * ```txt
81
+ * AIMessage {
82
+ * "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
83
+ * "content": "J'adore la programmation.",
84
+ * "response_metadata": {
85
+ * "tokenUsage": {
86
+ * "completionTokens": 5,
87
+ * "promptTokens": 28,
88
+ * "totalTokens": 33
89
+ * },
90
+ * "finish_reason": "stop",
91
+ * "system_fingerprint": "fp_3aa7262c27"
92
+ * },
93
+ * "usage_metadata": {
94
+ * "input_tokens": 28,
95
+ * "output_tokens": 5,
96
+ * "total_tokens": 33
97
+ * }
98
+ * }
99
+ * ```
100
+ * </details>
101
+ *
102
+ * <br />
103
+ *
104
+ * <details>
105
+ * <summary><strong>Streaming Chunks</strong></summary>
106
+ *
107
+ * ```typescript
108
+ * for await (const chunk of await llm.stream(input)) {
109
+ * console.log(chunk);
110
+ * }
111
+ * ```
112
+ *
113
+ * ```txt
114
+ * AIMessageChunk {
115
+ * "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
116
+ * "content": ""
117
+ * }
118
+ * AIMessageChunk {
119
+ * "content": "J"
120
+ * }
121
+ * AIMessageChunk {
122
+ * "content": "'adore"
123
+ * }
124
+ * AIMessageChunk {
125
+ * "content": " la"
126
+ * }
127
+ * AIMessageChunk {
128
+ * "content": " programmation",,
129
+ * }
130
+ * AIMessageChunk {
131
+ * "content": ".",,
132
+ * }
133
+ * AIMessageChunk {
134
+ * "content": "",
135
+ * "response_metadata": {
136
+ * "finish_reason": "stop",
137
+ * "system_fingerprint": "fp_c9aa9c0491"
138
+ * },
139
+ * }
140
+ * AIMessageChunk {
141
+ * "content": "",
142
+ * "usage_metadata": {
143
+ * "input_tokens": 28,
144
+ * "output_tokens": 5,
145
+ * "total_tokens": 33
146
+ * }
147
+ * }
148
+ * ```
149
+ * </details>
150
+ *
151
+ * <br />
152
+ *
153
+ * <details>
154
+ * <summary><strong>Aggregate Streamed Chunks</strong></summary>
155
+ *
156
+ * ```typescript
157
+ * import { AIMessageChunk } from '@langchain/core/messages';
158
+ * import { concat } from '@langchain/core/utils/stream';
159
+ *
160
+ * const stream = await llm.stream(input);
161
+ * let full: AIMessageChunk | undefined;
162
+ * for await (const chunk of stream) {
163
+ * full = !full ? chunk : concat(full, chunk);
164
+ * }
165
+ * console.log(full);
166
+ * ```
167
+ *
168
+ * ```txt
169
+ * AIMessageChunk {
170
+ * "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
171
+ * "content": "J'adore la programmation.",
172
+ * "response_metadata": {
173
+ * "prompt": 0,
174
+ * "completion": 0,
175
+ * "finish_reason": "stop",
176
+ * },
177
+ * "usage_metadata": {
178
+ * "input_tokens": 28,
179
+ * "output_tokens": 5,
180
+ * "total_tokens": 33
181
+ * }
182
+ * }
183
+ * ```
184
+ * </details>
185
+ *
186
+ * <br />
187
+ *
188
+ * <details>
189
+ * <summary><strong>Bind tools</strong></summary>
190
+ *
191
+ * ```typescript
192
+ * import { z } from 'zod';
193
+ *
194
+ * const GetWeather = {
195
+ * name: "GetWeather",
196
+ * description: "Get the current weather in a given location",
197
+ * schema: z.object({
198
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
199
+ * }),
200
+ * }
201
+ *
202
+ * const GetPopulation = {
203
+ * name: "GetPopulation",
204
+ * description: "Get the current population in a given location",
205
+ * schema: z.object({
206
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
207
+ * }),
208
+ * }
209
+ *
210
+ * const llmWithTools = llm.bindTools(
211
+ * [GetWeather, GetPopulation],
212
+ * {
213
+ * // strict: true // enforce tool args schema is respected
214
+ * }
215
+ * );
216
+ * const aiMsg = await llmWithTools.invoke(
217
+ * "Which city is hotter today and which is bigger: LA or NY?"
218
+ * );
219
+ * console.log(aiMsg.tool_calls);
220
+ * ```
221
+ *
222
+ * ```txt
223
+ * [
224
+ * {
225
+ * name: 'GetWeather',
226
+ * args: { location: 'Los Angeles, CA' },
227
+ * type: 'tool_call',
228
+ * id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
229
+ * },
230
+ * {
231
+ * name: 'GetWeather',
232
+ * args: { location: 'New York, NY' },
233
+ * type: 'tool_call',
234
+ * id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
235
+ * },
236
+ * {
237
+ * name: 'GetPopulation',
238
+ * args: { location: 'Los Angeles, CA' },
239
+ * type: 'tool_call',
240
+ * id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
241
+ * },
242
+ * {
243
+ * name: 'GetPopulation',
244
+ * args: { location: 'New York, NY' },
245
+ * type: 'tool_call',
246
+ * id: 'call_s9KQB1UWj45LLGaEnjz0179q'
247
+ * }
248
+ * ]
249
+ * ```
250
+ * </details>
251
+ *
252
+ * <br />
253
+ *
254
+ * <details>
255
+ * <summary><strong>Structured Output</strong></summary>
256
+ *
257
+ * ```typescript
258
+ * import { z } from 'zod';
259
+ *
260
+ * const Joke = z.object({
261
+ * setup: z.string().describe("The setup of the joke"),
262
+ * punchline: z.string().describe("The punchline to the joke"),
263
+ * rating: z.number().nullable().describe("How funny the joke is, from 1 to 10")
264
+ * }).describe('Joke to tell user.');
265
+ *
266
+ * const structuredLlm = llm.withStructuredOutput(Joke, {
267
+ * name: "Joke",
268
+ * strict: true, // Optionally enable OpenAI structured outputs
269
+ * });
270
+ * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
271
+ * console.log(jokeResult);
272
+ * ```
273
+ *
274
+ * ```txt
275
+ * {
276
+ * setup: 'Why was the cat sitting on the computer?',
277
+ * punchline: 'Because it wanted to keep an eye on the mouse!',
278
+ * rating: 7
279
+ * }
280
+ * ```
281
+ * </details>
282
+ *
283
+ * <br />
284
+ *
285
+ * <details>
286
+ * <summary><strong>JSON Object Response Format</strong></summary>
287
+ *
288
+ * ```typescript
289
+ * const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } });
290
+ * const jsonLlmAiMsg = await jsonLlm.invoke(
291
+ * "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
292
+ * );
293
+ * console.log(jsonLlmAiMsg.content);
294
+ * ```
295
+ *
296
+ * ```txt
297
+ * {
298
+ * "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
299
+ * }
300
+ * ```
301
+ * </details>
302
+ *
303
+ * <br />
304
+ *
305
+ * <details>
306
+ * <summary><strong>Multimodal</strong></summary>
307
+ *
308
+ * ```typescript
309
+ * import { HumanMessage } from '@langchain/core/messages';
310
+ *
311
+ * const imageUrl = "https://example.com/image.jpg";
312
+ * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
313
+ * const base64Image = Buffer.from(imageData).toString('base64');
314
+ *
315
+ * const message = new HumanMessage({
316
+ * content: [
317
+ * { type: "text", text: "describe the weather in this image" },
318
+ * {
319
+ * type: "image_url",
320
+ * image_url: { url: `data:image/jpeg;base64,${base64Image}` },
321
+ * },
322
+ * ]
323
+ * });
324
+ *
325
+ * const imageDescriptionAiMsg = await llm.invoke([message]);
326
+ * console.log(imageDescriptionAiMsg.content);
327
+ * ```
328
+ *
329
+ * ```txt
330
+ * 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.
331
+ * ```
332
+ * </details>
333
+ *
334
+ * <br />
335
+ *
336
+ * <details>
337
+ * <summary><strong>Usage Metadata</strong></summary>
338
+ *
339
+ * ```typescript
340
+ * const aiMsgForMetadata = await llm.invoke(input);
341
+ * console.log(aiMsgForMetadata.usage_metadata);
342
+ * ```
343
+ *
344
+ * ```txt
345
+ * { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
346
+ * ```
347
+ * </details>
348
+ *
349
+ * <br />
350
+ *
351
+ * <details>
352
+ * <summary><strong>Logprobs</strong></summary>
353
+ *
354
+ * ```typescript
355
+ * const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true });
356
+ * const aiMsgForLogprobs = await logprobsLlm.invoke(input);
357
+ * console.log(aiMsgForLogprobs.response_metadata.logprobs);
358
+ * ```
359
+ *
360
+ * ```txt
361
+ * {
362
+ * content: [
363
+ * {
364
+ * token: 'J',
365
+ * logprob: -0.000050616763,
366
+ * bytes: [Array],
367
+ * top_logprobs: []
368
+ * },
369
+ * {
370
+ * token: "'",
371
+ * logprob: -0.01868736,
372
+ * bytes: [Array],
373
+ * top_logprobs: []
374
+ * },
375
+ * {
376
+ * token: 'ad',
377
+ * logprob: -0.0000030545007,
378
+ * bytes: [Array],
379
+ * top_logprobs: []
380
+ * },
381
+ * { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
382
+ * {
383
+ * token: ' la',
384
+ * logprob: -0.515404,
385
+ * bytes: [Array],
386
+ * top_logprobs: []
387
+ * },
388
+ * {
389
+ * token: ' programm',
390
+ * logprob: -0.0000118755715,
391
+ * bytes: [Array],
392
+ * top_logprobs: []
393
+ * },
394
+ * { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
395
+ * {
396
+ * token: '.',
397
+ * logprob: -0.0000037697225,
398
+ * bytes: [Array],
399
+ * top_logprobs: []
400
+ * }
401
+ * ],
402
+ * refusal: null
403
+ * }
404
+ * ```
405
+ * </details>
406
+ *
407
+ * <br />
408
+ *
409
+ * <details>
410
+ * <summary><strong>Response Metadata</strong></summary>
411
+ *
412
+ * ```typescript
413
+ * const aiMsgForResponseMetadata = await llm.invoke(input);
414
+ * console.log(aiMsgForResponseMetadata.response_metadata);
415
+ * ```
416
+ *
417
+ * ```txt
418
+ * {
419
+ * tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
420
+ * finish_reason: 'stop',
421
+ * system_fingerprint: 'fp_3aa7262c27'
422
+ * }
423
+ * ```
424
+ * </details>
425
+ *
426
+ * <br />
427
+ *
428
+ * <details>
429
+ * <summary><strong>JSON Schema Structured Output</strong></summary>
430
+ *
431
+ * ```typescript
432
+ * const llmForJsonSchema = new ChatOpenAI({
433
+ * model: "gpt-4o-2024-08-06",
434
+ * }).withStructuredOutput(
435
+ * z.object({
436
+ * command: z.string().describe("The command to execute"),
437
+ * expectedOutput: z.string().describe("The expected output of the command"),
438
+ * options: z
439
+ * .array(z.string())
440
+ * .describe("The options you can pass to the command"),
441
+ * }),
442
+ * {
443
+ * method: "jsonSchema",
444
+ * strict: true, // Optional when using the `jsonSchema` method
445
+ * }
446
+ * );
447
+ *
448
+ * const jsonSchemaRes = await llmForJsonSchema.invoke(
449
+ * "What is the command to list files in a directory?"
450
+ * );
451
+ * console.log(jsonSchemaRes);
452
+ * ```
453
+ *
454
+ * ```txt
455
+ * {
456
+ * command: 'ls',
457
+ * expectedOutput: 'A list of files and subdirectories within the specified directory.',
458
+ * options: [
459
+ * '-a: include directory entries whose names begin with a dot (.).',
460
+ * '-l: use a long listing format.',
461
+ * '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).',
462
+ * '-t: sort by time, newest first.',
463
+ * '-r: reverse order while sorting.',
464
+ * '-S: sort by file size, largest first.',
465
+ * '-R: list subdirectories recursively.'
466
+ * ]
467
+ * }
468
+ * ```
469
+ * </details>
470
+ *
471
+ * <br />
472
+ *
473
+ * <details>
474
+ * <summary><strong>Audio Outputs</strong></summary>
475
+ *
476
+ * ```typescript
477
+ * import { ChatOpenAI } from "@langchain/openai";
478
+ *
479
+ * const modelWithAudioOutput = new ChatOpenAI({
480
+ * model: "gpt-4o-audio-preview",
481
+ * // You may also pass these fields to `.withConfig` as a call argument.
482
+ * modalities: ["text", "audio"], // Specifies that the model should output audio.
483
+ * audio: {
484
+ * voice: "alloy",
485
+ * format: "wav",
486
+ * },
487
+ * });
488
+ *
489
+ * const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats.");
490
+ * const castMessageContent = audioOutputResult.content[0] as Record<string, any>;
491
+ *
492
+ * console.log({
493
+ * ...castMessageContent,
494
+ * data: castMessageContent.data.slice(0, 100) // Sliced for brevity
495
+ * })
496
+ * ```
497
+ *
498
+ * ```txt
499
+ * {
500
+ * id: 'audio_67117718c6008190a3afad3e3054b9b6',
501
+ * data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',
502
+ * expires_at: 1729201448,
503
+ * transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'
504
+ * }
505
+ * ```
506
+ * </details>
507
+ *
508
+ * <br />
509
+ *
510
+ * <details>
511
+ * <summary><strong>Audio Outputs</strong></summary>
512
+ *
513
+ * ```typescript
514
+ * import { ChatOpenAI } from "@langchain/openai";
515
+ *
516
+ * const modelWithAudioOutput = new ChatOpenAI({
517
+ * model: "gpt-4o-audio-preview",
518
+ * // You may also pass these fields to `.withConfig` as a call argument.
519
+ * modalities: ["text", "audio"], // Specifies that the model should output audio.
520
+ * audio: {
521
+ * voice: "alloy",
522
+ * format: "wav",
523
+ * },
524
+ * });
525
+ *
526
+ * const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats.");
527
+ * const castAudioContent = audioOutputResult.additional_kwargs.audio as Record<string, any>;
528
+ *
529
+ * console.log({
530
+ * ...castAudioContent,
531
+ * data: castAudioContent.data.slice(0, 100) // Sliced for brevity
532
+ * })
533
+ * ```
534
+ *
535
+ * ```txt
536
+ * {
537
+ * id: 'audio_67117718c6008190a3afad3e3054b9b6',
538
+ * data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',
539
+ * expires_at: 1729201448,
540
+ * transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'
541
+ * }
542
+ * ```
543
+ * </details>
544
+ *
545
+ * <br />
546
+ */
547
+ var ChatOpenAI = class ChatOpenAI extends require_base.BaseChatOpenAI {
548
+ /**
549
+ * Whether to use the responses API for all requests. If `false` the responses API will be used
550
+ * only when required in order to fulfill the request.
551
+ */
552
+ useResponsesApi = false;
553
+ responses;
554
+ completions;
555
+ get lc_serializable_keys() {
556
+ return [...super.lc_serializable_keys, "useResponsesApi"];
557
+ }
558
+ get callKeys() {
559
+ return [...super.callKeys, "useResponsesApi"];
560
+ }
561
+ constructor(fields) {
562
+ super(fields);
563
+ this.fields = fields;
564
+ this.useResponsesApi = fields?.useResponsesApi ?? false;
565
+ this.responses = fields?.responses ?? new require_responses.ChatOpenAIResponses(fields);
566
+ this.completions = fields?.completions ?? new require_completions.ChatOpenAICompletions(fields);
567
+ }
568
+ _useResponsesApi(options) {
569
+ const usesBuiltInTools = options?.tools?.some(require_tools.isBuiltInTool);
570
+ const hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null;
571
+ const hasCustomTools = options?.tools?.some(require_tools.isOpenAICustomTool) || options?.tools?.some(require_tools.isCustomTool);
572
+ return this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools;
573
+ }
574
+ getLsParams(options) {
575
+ const optionsWithDefaults = this._combineCallOptions(options);
576
+ if (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults);
577
+ return this.completions.getLsParams(optionsWithDefaults);
578
+ }
579
+ invocationParams(options) {
580
+ const optionsWithDefaults = this._combineCallOptions(options);
581
+ if (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults);
582
+ return this.completions.invocationParams(optionsWithDefaults);
583
+ }
584
+ /** @ignore */
585
+ async _generate(messages, options, runManager) {
586
+ if (this._useResponsesApi(options)) return this.responses._generate(messages, options);
587
+ return this.completions._generate(messages, options, runManager);
588
+ }
589
+ async *_streamResponseChunks(messages, options, runManager) {
590
+ if (this._useResponsesApi(options)) {
591
+ yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
592
+ return;
593
+ }
594
+ yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager);
595
+ }
596
+ withConfig(config) {
597
+ const newModel = new ChatOpenAI(this.fields);
598
+ newModel.defaultOptions = {
599
+ ...this.defaultOptions,
600
+ ...config
601
+ };
602
+ return newModel;
603
+ }
604
+ };
605
+
606
+ //#endregion
607
+ exports.ChatOpenAI = ChatOpenAI;
608
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["BaseChatOpenAI","fields?: ChatOpenAIFields","ChatOpenAIResponses","ChatOpenAICompletions","options: this[\"ParsedCallOptions\"] | undefined","isBuiltInTool","isOpenAICustomTool","isCustomTool","options: this[\"ParsedCallOptions\"]","options?: this[\"ParsedCallOptions\"]","messages: BaseMessage[]","runManager?: CallbackManagerForLLMRun","config: Partial<CallOptions>"],"sources":["../../src/chat_models/index.ts"],"sourcesContent":["import { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessageChunk, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { type BaseLanguageModelInput } from \"@langchain/core/language_models/base\";\nimport { Runnable } from \"@langchain/core/runnables\";\nimport { type OpenAICallOptions, type OpenAIChatInput } from \"../types.js\";\nimport {\n _convertToOpenAITool,\n isBuiltInTool,\n isCustomTool,\n isOpenAICustomTool,\n} from \"../utils/tools.js\";\nimport { _convertOpenAIResponsesUsageToLangChainUsage } from \"../utils/output.js\";\nimport { _convertMessagesToOpenAIParams } from \"../utils/message_inputs.js\";\nimport { _convertToResponsesMessageFromV1 } from \"../utils/standard.js\";\nimport {\n ChatOpenAICompletions,\n ChatOpenAICompletionsCallOptions,\n} from \"./completions.js\";\nimport {\n ChatOpenAIResponses,\n ChatOpenAIResponsesCallOptions,\n} from \"./responses.js\";\nimport { BaseChatOpenAI, BaseChatOpenAIFields } from \"./base.js\";\n\nexport type { OpenAICallOptions, OpenAIChatInput };\n\nexport type ChatOpenAICallOptions = ChatOpenAICompletionsCallOptions &\n ChatOpenAIResponsesCallOptions;\n\nexport interface ChatOpenAIFields extends BaseChatOpenAIFields {\n /**\n * Whether to use the responses API for all requests. If `false` the responses API will be used\n * only when required in order to fulfill the request.\n */\n useResponsesApi?: boolean;\n /**\n * The completions chat instance\n * @internal\n */\n completions?: ChatOpenAICompletions;\n /**\n * The responses chat instance\n * @internal\n */\n responses?: ChatOpenAIResponses;\n}\n\n/**\n * OpenAI chat model integration.\n *\n * To use with Azure, import the `AzureChatOpenAI` class.\n *\n * Setup:\n * Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.\n *\n * ```bash\n * npm install @langchain/openai\n * export OPENAI_API_KEY=\"your-api-key\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.withConfig`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.withConfig({\n * stop: [\"\\n\"],\n * tools: [...],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatOpenAI } from '@langchain/openai';\n *\n * const llm = new ChatOpenAI({\n * model: \"gpt-4o-mini\",\n * temperature: 0,\n * maxTokens: undefined,\n * timeout: undefined,\n * maxRetries: 2,\n * // apiKey: \"...\",\n * // configuration: {\n * // baseURL: \"...\",\n * // }\n * // organization: \"...\",\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessage {\n * \"id\": \"chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz\",\n * \"content\": \"J'adore la programmation.\",\n * \"response_metadata\": {\n * \"tokenUsage\": {\n * \"completionTokens\": 5,\n * \"promptTokens\": 28,\n * \"totalTokens\": 33\n * },\n * \"finish_reason\": \"stop\",\n * \"system_fingerprint\": \"fp_3aa7262c27\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 28,\n * \"output_tokens\": 5,\n * \"total_tokens\": 33\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs\",\n * \"content\": \"\"\n * }\n * AIMessageChunk {\n * \"content\": \"J\"\n * }\n * AIMessageChunk {\n * \"content\": \"'adore\"\n * }\n * AIMessageChunk {\n * \"content\": \" la\"\n * }\n * AIMessageChunk {\n * \"content\": \" programmation\",,\n * }\n * AIMessageChunk {\n * \"content\": \".\",,\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"response_metadata\": {\n * \"finish_reason\": \"stop\",\n * \"system_fingerprint\": \"fp_c9aa9c0491\"\n * },\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"usage_metadata\": {\n * \"input_tokens\": 28,\n * \"output_tokens\": 5,\n * \"total_tokens\": 33\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu\",\n * \"content\": \"J'adore la programmation.\",\n * \"response_metadata\": {\n * \"prompt\": 0,\n * \"completion\": 0,\n * \"finish_reason\": \"stop\",\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 28,\n * \"output_tokens\": 5,\n * \"total_tokens\": 33\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools(\n * [GetWeather, GetPopulation],\n * {\n * // strict: true // enforce tool args schema is respected\n * }\n * );\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetWeather',\n * args: { location: 'Los Angeles, CA' },\n * type: 'tool_call',\n * id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'\n * },\n * {\n * name: 'GetWeather',\n * args: { location: 'New York, NY' },\n * type: 'tool_call',\n * id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'Los Angeles, CA' },\n * type: 'tool_call',\n * id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York, NY' },\n * type: 'tool_call',\n * id: 'call_s9KQB1UWj45LLGaEnjz0179q'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().nullable().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, {\n * name: \"Joke\",\n * strict: true, // Optionally enable OpenAI structured outputs\n * });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: 'Why was the cat sitting on the computer?',\n * punchline: 'Because it wanted to keep an eye on the mouse!',\n * rating: 7\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>JSON Object Response Format</strong></summary>\n *\n * ```typescript\n * const jsonLlm = llm.withConfig({ response_format: { type: \"json_object\" } });\n * const jsonLlmAiMsg = await jsonLlm.invoke(\n * \"Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]\"\n * );\n * console.log(jsonLlmAiMsg.content);\n * ```\n *\n * ```txt\n * {\n * \"randomInts\": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Multimodal</strong></summary>\n *\n * ```typescript\n * import { HumanMessage } from '@langchain/core/messages';\n *\n * const imageUrl = \"https://example.com/image.jpg\";\n * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n * const base64Image = Buffer.from(imageData).toString('base64');\n *\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"describe the weather in this image\" },\n * {\n * type: \"image_url\",\n * image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n * },\n * ]\n * });\n *\n * const imageDescriptionAiMsg = await llm.invoke([message]);\n * console.log(imageDescriptionAiMsg.content);\n * ```\n *\n * ```txt\n * 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.\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 28, output_tokens: 5, total_tokens: 33 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Logprobs</strong></summary>\n *\n * ```typescript\n * const logprobsLlm = new ChatOpenAI({ model: \"gpt-4o-mini\", logprobs: true });\n * const aiMsgForLogprobs = await logprobsLlm.invoke(input);\n * console.log(aiMsgForLogprobs.response_metadata.logprobs);\n * ```\n *\n * ```txt\n * {\n * content: [\n * {\n * token: 'J',\n * logprob: -0.000050616763,\n * bytes: [Array],\n * top_logprobs: []\n * },\n * {\n * token: \"'\",\n * logprob: -0.01868736,\n * bytes: [Array],\n * top_logprobs: []\n * },\n * {\n * token: 'ad',\n * logprob: -0.0000030545007,\n * bytes: [Array],\n * top_logprobs: []\n * },\n * { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },\n * {\n * token: ' la',\n * logprob: -0.515404,\n * bytes: [Array],\n * top_logprobs: []\n * },\n * {\n * token: ' programm',\n * logprob: -0.0000118755715,\n * bytes: [Array],\n * top_logprobs: []\n * },\n * { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },\n * {\n * token: '.',\n * logprob: -0.0000037697225,\n * bytes: [Array],\n * top_logprobs: []\n * }\n * ],\n * refusal: null\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Response Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForResponseMetadata = await llm.invoke(input);\n * console.log(aiMsgForResponseMetadata.response_metadata);\n * ```\n *\n * ```txt\n * {\n * tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },\n * finish_reason: 'stop',\n * system_fingerprint: 'fp_3aa7262c27'\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>JSON Schema Structured Output</strong></summary>\n *\n * ```typescript\n * const llmForJsonSchema = new ChatOpenAI({\n * model: \"gpt-4o-2024-08-06\",\n * }).withStructuredOutput(\n * z.object({\n * command: z.string().describe(\"The command to execute\"),\n * expectedOutput: z.string().describe(\"The expected output of the command\"),\n * options: z\n * .array(z.string())\n * .describe(\"The options you can pass to the command\"),\n * }),\n * {\n * method: \"jsonSchema\",\n * strict: true, // Optional when using the `jsonSchema` method\n * }\n * );\n *\n * const jsonSchemaRes = await llmForJsonSchema.invoke(\n * \"What is the command to list files in a directory?\"\n * );\n * console.log(jsonSchemaRes);\n * ```\n *\n * ```txt\n * {\n * command: 'ls',\n * expectedOutput: 'A list of files and subdirectories within the specified directory.',\n * options: [\n * '-a: include directory entries whose names begin with a dot (.).',\n * '-l: use a long listing format.',\n * '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).',\n * '-t: sort by time, newest first.',\n * '-r: reverse order while sorting.',\n * '-S: sort by file size, largest first.',\n * '-R: list subdirectories recursively.'\n * ]\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Audio Outputs</strong></summary>\n *\n * ```typescript\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * const modelWithAudioOutput = new ChatOpenAI({\n * model: \"gpt-4o-audio-preview\",\n * // You may also pass these fields to `.withConfig` as a call argument.\n * modalities: [\"text\", \"audio\"], // Specifies that the model should output audio.\n * audio: {\n * voice: \"alloy\",\n * format: \"wav\",\n * },\n * });\n *\n * const audioOutputResult = await modelWithAudioOutput.invoke(\"Tell me a joke about cats.\");\n * const castMessageContent = audioOutputResult.content[0] as Record<string, any>;\n *\n * console.log({\n * ...castMessageContent,\n * data: castMessageContent.data.slice(0, 100) // Sliced for brevity\n * })\n * ```\n *\n * ```txt\n * {\n * id: 'audio_67117718c6008190a3afad3e3054b9b6',\n * data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',\n * expires_at: 1729201448,\n * transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Audio Outputs</strong></summary>\n *\n * ```typescript\n * import { ChatOpenAI } from \"@langchain/openai\";\n *\n * const modelWithAudioOutput = new ChatOpenAI({\n * model: \"gpt-4o-audio-preview\",\n * // You may also pass these fields to `.withConfig` as a call argument.\n * modalities: [\"text\", \"audio\"], // Specifies that the model should output audio.\n * audio: {\n * voice: \"alloy\",\n * format: \"wav\",\n * },\n * });\n *\n * const audioOutputResult = await modelWithAudioOutput.invoke(\"Tell me a joke about cats.\");\n * const castAudioContent = audioOutputResult.additional_kwargs.audio as Record<string, any>;\n *\n * console.log({\n * ...castAudioContent,\n * data: castAudioContent.data.slice(0, 100) // Sliced for brevity\n * })\n * ```\n *\n * ```txt\n * {\n * id: 'audio_67117718c6008190a3afad3e3054b9b6',\n * data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg',\n * expires_at: 1729201448,\n * transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!'\n * }\n * ```\n * </details>\n *\n * <br />\n */\nexport class ChatOpenAI<\n CallOptions extends ChatOpenAICallOptions = ChatOpenAICallOptions\n> extends BaseChatOpenAI<CallOptions> {\n /**\n * Whether to use the responses API for all requests. If `false` the responses API will be used\n * only when required in order to fulfill the request.\n */\n useResponsesApi = false;\n\n protected responses: ChatOpenAIResponses;\n\n protected completions: ChatOpenAICompletions;\n\n get lc_serializable_keys(): string[] {\n return [...super.lc_serializable_keys, \"useResponsesApi\"];\n }\n\n get callKeys(): string[] {\n return [...super.callKeys, \"useResponsesApi\"];\n }\n\n constructor(protected fields?: ChatOpenAIFields) {\n super(fields);\n this.useResponsesApi = fields?.useResponsesApi ?? false;\n this.responses = fields?.responses ?? new ChatOpenAIResponses(fields);\n this.completions = fields?.completions ?? new ChatOpenAICompletions(fields);\n }\n\n protected _useResponsesApi(options: this[\"ParsedCallOptions\"] | undefined) {\n const usesBuiltInTools = options?.tools?.some(isBuiltInTool);\n const hasResponsesOnlyKwargs =\n options?.previous_response_id != null ||\n options?.text != null ||\n options?.truncation != null ||\n options?.include != null ||\n options?.reasoning?.summary != null ||\n this.reasoning?.summary != null;\n const hasCustomTools =\n options?.tools?.some(isOpenAICustomTool) ||\n options?.tools?.some(isCustomTool);\n\n return (\n this.useResponsesApi ||\n usesBuiltInTools ||\n hasResponsesOnlyKwargs ||\n hasCustomTools\n );\n }\n\n override getLsParams(options: this[\"ParsedCallOptions\"]) {\n const optionsWithDefaults = this._combineCallOptions(options);\n if (this._useResponsesApi(options)) {\n return this.responses.getLsParams(optionsWithDefaults);\n }\n return this.completions.getLsParams(optionsWithDefaults);\n }\n\n override invocationParams(options?: this[\"ParsedCallOptions\"]) {\n const optionsWithDefaults = this._combineCallOptions(options);\n if (this._useResponsesApi(options)) {\n return this.responses.invocationParams(optionsWithDefaults);\n }\n return this.completions.invocationParams(optionsWithDefaults);\n }\n\n /** @ignore */\n override async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this._useResponsesApi(options)) {\n return this.responses._generate(messages, options);\n }\n return this.completions._generate(messages, options, runManager);\n }\n\n override async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n if (this._useResponsesApi(options)) {\n yield* this.responses._streamResponseChunks(\n messages,\n this._combineCallOptions(options),\n runManager\n );\n return;\n }\n yield* this.completions._streamResponseChunks(\n messages,\n this._combineCallOptions(options),\n runManager\n );\n }\n\n override withConfig(\n config: Partial<CallOptions>\n ): Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions> {\n const newModel = new ChatOpenAI<CallOptions>(this.fields);\n newModel.defaultOptions = { ...this.defaultOptions, ...config };\n return newModel;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4kBA,IAAa,aAAb,MAAa,mBAEHA,4BAA4B;;;;;CAKpC,kBAAkB;CAElB,AAAU;CAEV,AAAU;CAEV,IAAI,uBAAiC;AACnC,SAAO,CAAC,GAAG,MAAM,sBAAsB,iBAAkB;CAC1D;CAED,IAAI,WAAqB;AACvB,SAAO,CAAC,GAAG,MAAM,UAAU,iBAAkB;CAC9C;CAED,YAAsBC,QAA2B;EAC/C,MAAM,OAAO;EADO;EAEpB,KAAK,kBAAkB,QAAQ,mBAAmB;EAClD,KAAK,YAAY,QAAQ,aAAa,IAAIC,sCAAoB;EAC9D,KAAK,cAAc,QAAQ,eAAe,IAAIC,0CAAsB;CACrE;CAED,AAAU,iBAAiBC,SAAgD;EACzE,MAAM,mBAAmB,SAAS,OAAO,KAAKC,4BAAc;EAC5D,MAAM,yBACJ,SAAS,wBAAwB,QACjC,SAAS,QAAQ,QACjB,SAAS,cAAc,QACvB,SAAS,WAAW,QACpB,SAAS,WAAW,WAAW,QAC/B,KAAK,WAAW,WAAW;EAC7B,MAAM,iBACJ,SAAS,OAAO,KAAKC,iCAAmB,IACxC,SAAS,OAAO,KAAKC,2BAAa;AAEpC,SACE,KAAK,mBACL,oBACA,0BACA;CAEH;CAED,AAAS,YAAYC,SAAoC;EACvD,MAAM,sBAAsB,KAAK,oBAAoB,QAAQ;AAC7D,MAAI,KAAK,iBAAiB,QAAQ,CAChC,QAAO,KAAK,UAAU,YAAY,oBAAoB;AAExD,SAAO,KAAK,YAAY,YAAY,oBAAoB;CACzD;CAED,AAAS,iBAAiBC,SAAqC;EAC7D,MAAM,sBAAsB,KAAK,oBAAoB,QAAQ;AAC7D,MAAI,KAAK,iBAAiB,QAAQ,CAChC,QAAO,KAAK,UAAU,iBAAiB,oBAAoB;AAE7D,SAAO,KAAK,YAAY,iBAAiB,oBAAoB;CAC9D;;CAGD,MAAe,UACbC,UACAF,SACAG,YACqB;AACrB,MAAI,KAAK,iBAAiB,QAAQ,CAChC,QAAO,KAAK,UAAU,UAAU,UAAU,QAAQ;AAEpD,SAAO,KAAK,YAAY,UAAU,UAAU,SAAS,WAAW;CACjE;CAED,OAAgB,sBACdD,UACAF,SACAG,YACqC;AACrC,MAAI,KAAK,iBAAiB,QAAQ,EAAE;GAClC,OAAO,KAAK,UAAU,sBACpB,UACA,KAAK,oBAAoB,QAAQ,EACjC,WACD;AACD;EACD;EACD,OAAO,KAAK,YAAY,sBACtB,UACA,KAAK,oBAAoB,QAAQ,EACjC,WACD;CACF;CAED,AAAS,WACPC,QAC+D;EAC/D,MAAM,WAAW,IAAI,WAAwB,KAAK;EAClD,SAAS,iBAAiB;GAAE,GAAG,KAAK;GAAgB,GAAG;EAAQ;AAC/D,SAAO;CACR;AACF"}