@langchain/openai 0.2.6 → 0.2.7

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.
@@ -6,7 +6,8 @@ import { BaseChatModel, BindToolsInput, LangSmithParams, type BaseChatModelParam
6
6
  import { type BaseFunctionCallOptions, type BaseLanguageModelInput, type StructuredOutputMethodOptions, type StructuredOutputMethodParams } from "@langchain/core/language_models/base";
7
7
  import { z } from "zod";
8
8
  import { Runnable } from "@langchain/core/runnables";
9
- import type { AzureOpenAIInput, OpenAICallOptions, OpenAIChatInput, OpenAICoreRequestOptions, LegacyOpenAIInput } from "./types.js";
9
+ import { ParsedChatCompletion } from "openai/resources/beta/chat/completions.mjs";
10
+ import type { AzureOpenAIInput, OpenAICallOptions, OpenAIChatInput, OpenAICoreRequestOptions, LegacyOpenAIInput, ChatOpenAIResponseFormat } from "./types.js";
10
11
  import { OpenAIToolChoice } from "./utils/openai.js";
11
12
  export type { AzureOpenAIInput, OpenAICallOptions, OpenAIChatInput };
12
13
  interface TokenUsage {
@@ -41,9 +42,7 @@ export interface ChatOpenAICallOptions extends OpenAICallOptions, BaseFunctionCa
41
42
  tools?: ChatOpenAIToolType[];
42
43
  tool_choice?: OpenAIToolChoice;
43
44
  promptIndex?: number;
44
- response_format?: {
45
- type: "json_object";
46
- };
45
+ response_format?: ChatOpenAIResponseFormat;
47
46
  seed?: number;
48
47
  /**
49
48
  * Additional options to pass to streamed completions.
@@ -81,37 +80,418 @@ export interface ChatOpenAIFields extends Partial<OpenAIChatInput>, Partial<Azur
81
80
  configuration?: ClientOptions & LegacyOpenAIInput;
82
81
  }
83
82
  /**
84
- * Wrapper around OpenAI large language models that use the Chat endpoint.
85
- *
86
- * To use you should have the `OPENAI_API_KEY` environment variable set.
87
- *
88
- * To use with Azure you should have the:
89
- * `AZURE_OPENAI_API_KEY`,
90
- * `AZURE_OPENAI_API_INSTANCE_NAME`,
91
- * `AZURE_OPENAI_API_DEPLOYMENT_NAME`
92
- * and `AZURE_OPENAI_API_VERSION` environment variables set.
93
- * `AZURE_OPENAI_BASE_PATH` is optional and will override `AZURE_OPENAI_API_INSTANCE_NAME` if you need to use a custom endpoint.
94
- *
95
- * @remarks
96
- * Any parameters that are valid to be passed to {@link
97
- * https://platform.openai.com/docs/api-reference/chat/create |
98
- * `openai.createChatCompletion`} can be passed through {@link modelKwargs}, even
99
- * if not explicitly available on this class.
100
- * @example
83
+ * OpenAI chat model integration.
84
+ *
85
+ * Setup:
86
+ * Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
87
+ *
88
+ * ```bash
89
+ * npm install @langchain/openai
90
+ * export OPENAI_API_KEY="your-api-key"
91
+ * ```
92
+ *
93
+ * ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
94
+ *
95
+ * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
96
+ *
97
+ * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
98
+ * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
99
+ *
101
100
  * ```typescript
102
- * // Create a new instance of ChatOpenAI with specific temperature and model name settings
103
- * const model = new ChatOpenAI({
104
- * temperature: 0.9,
105
- * model: "ft:gpt-3.5-turbo-0613:{ORG_NAME}::{MODEL_ID}",
101
+ * // When calling `.bind`, call options should be passed via the first argument
102
+ * const llmWithArgsBound = llm.bind({
103
+ * stop: ["\n"],
104
+ * tools: [...],
106
105
  * });
107
106
  *
108
- * // Invoke the model with a message and await the response
109
- * const message = await model.invoke("Hi there!");
107
+ * // When calling `.bindTools`, call options should be passed via the second argument
108
+ * const llmWithTools = llm.bindTools(
109
+ * [...],
110
+ * {
111
+ * tool_choice: "auto",
112
+ * }
113
+ * );
114
+ * ```
115
+ *
116
+ * ## Examples
110
117
  *
111
- * // Log the response to the console
112
- * console.log(message);
118
+ * <details open>
119
+ * <summary><strong>Instantiate</strong></summary>
113
120
  *
121
+ * ```typescript
122
+ * import { ChatOpenAI } from '@langchain/openai';
123
+ *
124
+ * const llm = new ChatOpenAI({
125
+ * model: "gpt-4o",
126
+ * temperature: 0,
127
+ * maxTokens: undefined,
128
+ * timeout: undefined,
129
+ * maxRetries: 2,
130
+ * // apiKey: "...",
131
+ * // baseUrl: "...",
132
+ * // organization: "...",
133
+ * // other params...
134
+ * });
114
135
  * ```
136
+ * </details>
137
+ *
138
+ * <br />
139
+ *
140
+ * <details>
141
+ * <summary><strong>Invoking</strong></summary>
142
+ *
143
+ * ```typescript
144
+ * const input = `Translate "I love programming" into French.`;
145
+ *
146
+ * // Models also accept a list of chat messages or a formatted prompt
147
+ * const result = await llm.invoke(input);
148
+ * console.log(result);
149
+ * ```
150
+ *
151
+ * ```txt
152
+ * AIMessage {
153
+ * "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
154
+ * "content": "J'adore la programmation.",
155
+ * "response_metadata": {
156
+ * "tokenUsage": {
157
+ * "completionTokens": 5,
158
+ * "promptTokens": 28,
159
+ * "totalTokens": 33
160
+ * },
161
+ * "finish_reason": "stop",
162
+ * "system_fingerprint": "fp_3aa7262c27"
163
+ * },
164
+ * "usage_metadata": {
165
+ * "input_tokens": 28,
166
+ * "output_tokens": 5,
167
+ * "total_tokens": 33
168
+ * }
169
+ * }
170
+ * ```
171
+ * </details>
172
+ *
173
+ * <br />
174
+ *
175
+ * <details>
176
+ * <summary><strong>Streaming Chunks</strong></summary>
177
+ *
178
+ * ```typescript
179
+ * for await (const chunk of await llm.stream(input)) {
180
+ * console.log(chunk);
181
+ * }
182
+ * ```
183
+ *
184
+ * ```txt
185
+ * AIMessageChunk {
186
+ * "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
187
+ * "content": ""
188
+ * }
189
+ * AIMessageChunk {
190
+ * "content": "J"
191
+ * }
192
+ * AIMessageChunk {
193
+ * "content": "'adore"
194
+ * }
195
+ * AIMessageChunk {
196
+ * "content": " la"
197
+ * }
198
+ * AIMessageChunk {
199
+ * "content": " programmation",,
200
+ * }
201
+ * AIMessageChunk {
202
+ * "content": ".",,
203
+ * }
204
+ * AIMessageChunk {
205
+ * "content": "",
206
+ * "response_metadata": {
207
+ * "finish_reason": "stop",
208
+ * "system_fingerprint": "fp_c9aa9c0491"
209
+ * },
210
+ * }
211
+ * AIMessageChunk {
212
+ * "content": "",
213
+ * "usage_metadata": {
214
+ * "input_tokens": 28,
215
+ * "output_tokens": 5,
216
+ * "total_tokens": 33
217
+ * }
218
+ * }
219
+ * ```
220
+ * </details>
221
+ *
222
+ * <br />
223
+ *
224
+ * <details>
225
+ * <summary><strong>Aggregate Streamed Chunks</strong></summary>
226
+ *
227
+ * ```typescript
228
+ * import { AIMessageChunk } from '@langchain/core/messages';
229
+ * import { concat } from '@langchain/core/utils/stream';
230
+ *
231
+ * const stream = await llm.stream(input);
232
+ * let full: AIMessageChunk | undefined;
233
+ * for await (const chunk of stream) {
234
+ * full = !full ? chunk : concat(full, chunk);
235
+ * }
236
+ * console.log(full);
237
+ * ```
238
+ *
239
+ * ```txt
240
+ * AIMessageChunk {
241
+ * "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
242
+ * "content": "J'adore la programmation.",
243
+ * "response_metadata": {
244
+ * "prompt": 0,
245
+ * "completion": 0,
246
+ * "finish_reason": "stop",
247
+ * },
248
+ * "usage_metadata": {
249
+ * "input_tokens": 28,
250
+ * "output_tokens": 5,
251
+ * "total_tokens": 33
252
+ * }
253
+ * }
254
+ * ```
255
+ * </details>
256
+ *
257
+ * <br />
258
+ *
259
+ * <details>
260
+ * <summary><strong>Bind tools</strong></summary>
261
+ *
262
+ * ```typescript
263
+ * import { z } from 'zod';
264
+ *
265
+ * const GetWeather = {
266
+ * name: "GetWeather",
267
+ * description: "Get the current weather in a given location",
268
+ * schema: z.object({
269
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
270
+ * }),
271
+ * }
272
+ *
273
+ * const GetPopulation = {
274
+ * name: "GetPopulation",
275
+ * description: "Get the current population in a given location",
276
+ * schema: z.object({
277
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
278
+ * }),
279
+ * }
280
+ *
281
+ * const llmWithTools = llm.bindTools(
282
+ * [GetWeather, GetPopulation],
283
+ * {
284
+ * // strict: true // enforce tool args schema is respected
285
+ * }
286
+ * );
287
+ * const aiMsg = await llmWithTools.invoke(
288
+ * "Which city is hotter today and which is bigger: LA or NY?"
289
+ * );
290
+ * console.log(aiMsg.tool_calls);
291
+ * ```
292
+ *
293
+ * ```txt
294
+ * [
295
+ * {
296
+ * name: 'GetWeather',
297
+ * args: { location: 'Los Angeles, CA' },
298
+ * type: 'tool_call',
299
+ * id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
300
+ * },
301
+ * {
302
+ * name: 'GetWeather',
303
+ * args: { location: 'New York, NY' },
304
+ * type: 'tool_call',
305
+ * id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
306
+ * },
307
+ * {
308
+ * name: 'GetPopulation',
309
+ * args: { location: 'Los Angeles, CA' },
310
+ * type: 'tool_call',
311
+ * id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
312
+ * },
313
+ * {
314
+ * name: 'GetPopulation',
315
+ * args: { location: 'New York, NY' },
316
+ * type: 'tool_call',
317
+ * id: 'call_s9KQB1UWj45LLGaEnjz0179q'
318
+ * }
319
+ * ]
320
+ * ```
321
+ * </details>
322
+ *
323
+ * <br />
324
+ *
325
+ * <details>
326
+ * <summary><strong>Structured Output</strong></summary>
327
+ *
328
+ * ```typescript
329
+ * import { z } from 'zod';
330
+ *
331
+ * const Joke = z.object({
332
+ * setup: z.string().describe("The setup of the joke"),
333
+ * punchline: z.string().describe("The punchline to the joke"),
334
+ * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
335
+ * }).describe('Joke to tell user.');
336
+ *
337
+ * const structuredLlm = llm.withStructuredOutput(Joke);
338
+ * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats", { name: "Joke" });
339
+ * console.log(jokeResult);
340
+ * ```
341
+ *
342
+ * ```txt
343
+ * {
344
+ * setup: 'Why was the cat sitting on the computer?',
345
+ * punchline: 'Because it wanted to keep an eye on the mouse!',
346
+ * rating: 7
347
+ * }
348
+ * ```
349
+ * </details>
350
+ *
351
+ * <br />
352
+ *
353
+ * <details>
354
+ * <summary><strong>JSON Object Response Format</strong></summary>
355
+ *
356
+ * ```typescript
357
+ * const jsonLlm = llm.bind({ response_format: { type: "json_object" } });
358
+ * const jsonLlmAiMsg = await jsonLlm.invoke(
359
+ * "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
360
+ * );
361
+ * console.log(jsonLlmAiMsg.content);
362
+ * ```
363
+ *
364
+ * ```txt
365
+ * {
366
+ * "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
367
+ * }
368
+ * ```
369
+ * </details>
370
+ *
371
+ * <br />
372
+ *
373
+ * <details>
374
+ * <summary><strong>Multimodal</strong></summary>
375
+ *
376
+ * ```typescript
377
+ * import { HumanMessage } from '@langchain/core/messages';
378
+ *
379
+ * const imageUrl = "https://example.com/image.jpg";
380
+ * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
381
+ * const base64Image = Buffer.from(imageData).toString('base64');
382
+ *
383
+ * const message = new HumanMessage({
384
+ * content: [
385
+ * { type: "text", text: "describe the weather in this image" },
386
+ * {
387
+ * type: "image_url",
388
+ * image_url: { url: `data:image/jpeg;base64,${base64Image}` },
389
+ * },
390
+ * ]
391
+ * });
392
+ *
393
+ * const imageDescriptionAiMsg = await llm.invoke([message]);
394
+ * console.log(imageDescriptionAiMsg.content);
395
+ * ```
396
+ *
397
+ * ```txt
398
+ * 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.
399
+ * ```
400
+ * </details>
401
+ *
402
+ * <br />
403
+ *
404
+ * <details>
405
+ * <summary><strong>Usage Metadata</strong></summary>
406
+ *
407
+ * ```typescript
408
+ * const aiMsgForMetadata = await llm.invoke(input);
409
+ * console.log(aiMsgForMetadata.usage_metadata);
410
+ * ```
411
+ *
412
+ * ```txt
413
+ * { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
414
+ * ```
415
+ * </details>
416
+ *
417
+ * <br />
418
+ *
419
+ * <details>
420
+ * <summary><strong>Logprobs</strong></summary>
421
+ *
422
+ * ```typescript
423
+ * const logprobsLlm = new ChatOpenAI({ logprobs: true });
424
+ * const aiMsgForLogprobs = await logprobsLlm.invoke(input);
425
+ * console.log(aiMsgForLogprobs.response_metadata.logprobs);
426
+ * ```
427
+ *
428
+ * ```txt
429
+ * {
430
+ * content: [
431
+ * {
432
+ * token: 'J',
433
+ * logprob: -0.000050616763,
434
+ * bytes: [Array],
435
+ * top_logprobs: []
436
+ * },
437
+ * {
438
+ * token: "'",
439
+ * logprob: -0.01868736,
440
+ * bytes: [Array],
441
+ * top_logprobs: []
442
+ * },
443
+ * {
444
+ * token: 'ad',
445
+ * logprob: -0.0000030545007,
446
+ * bytes: [Array],
447
+ * top_logprobs: []
448
+ * },
449
+ * { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
450
+ * {
451
+ * token: ' la',
452
+ * logprob: -0.515404,
453
+ * bytes: [Array],
454
+ * top_logprobs: []
455
+ * },
456
+ * {
457
+ * token: ' programm',
458
+ * logprob: -0.0000118755715,
459
+ * bytes: [Array],
460
+ * top_logprobs: []
461
+ * },
462
+ * { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
463
+ * {
464
+ * token: '.',
465
+ * logprob: -0.0000037697225,
466
+ * bytes: [Array],
467
+ * top_logprobs: []
468
+ * }
469
+ * ],
470
+ * refusal: null
471
+ * }
472
+ * ```
473
+ * </details>
474
+ *
475
+ * <br />
476
+ *
477
+ * <details>
478
+ * <summary><strong>Response Metadata</strong></summary>
479
+ *
480
+ * ```typescript
481
+ * const aiMsgForResponseMetadata = await llm.invoke(input);
482
+ * console.log(aiMsgForResponseMetadata.response_metadata);
483
+ * ```
484
+ *
485
+ * ```txt
486
+ * {
487
+ * tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
488
+ * finish_reason: 'stop',
489
+ * system_fingerprint: 'fp_3aa7262c27'
490
+ * }
491
+ * ```
492
+ * </details>
493
+ *
494
+ * <br />
115
495
  */
116
496
  export declare class ChatOpenAI<CallOptions extends ChatOpenAICallOptions = ChatOpenAICallOptions> extends BaseChatModel<CallOptions, AIMessageChunk> implements OpenAIChatInput, AzureOpenAIInput {
117
497
  static lc_name(): string;
@@ -161,6 +541,7 @@ export declare class ChatOpenAI<CallOptions extends ChatOpenAICallOptions = Chat
161
541
  configuration?: ClientOptions & LegacyOpenAIInput);
162
542
  getLsParams(options: this["ParsedCallOptions"]): LangSmithParams;
163
543
  bindTools(tools: ChatOpenAIToolType[], kwargs?: Partial<CallOptions>): Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions>;
544
+ private createResponseFormat;
164
545
  /**
165
546
  * Get the parameters used to invoke the model
166
547
  */
@@ -202,6 +583,13 @@ export declare class ChatOpenAI<CallOptions extends ChatOpenAICallOptions = Chat
202
583
  */
203
584
  completionWithRetry(request: OpenAIClient.Chat.ChatCompletionCreateParamsStreaming, options?: OpenAICoreRequestOptions): Promise<AsyncIterable<OpenAIClient.Chat.Completions.ChatCompletionChunk>>;
204
585
  completionWithRetry(request: OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming, options?: OpenAICoreRequestOptions): Promise<OpenAIClient.Chat.Completions.ChatCompletion>;
586
+ /**
587
+ * Call the beta chat completions parse endpoint. This should only be called if
588
+ * response_format is set to "json_object".
589
+ * @param {OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming} request
590
+ * @param {OpenAICoreRequestOptions | undefined} options
591
+ */
592
+ betaParsedCompletionWithRetry(request: OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming, options?: OpenAICoreRequestOptions): Promise<ParsedChatCompletion<null>>;
205
593
  protected _getClientOptions(options: OpenAICoreRequestOptions | undefined): OpenAICoreRequestOptions;
206
594
  _llmType(): string;
207
595
  /** @ignore */