@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.
@@ -1,6 +1,418 @@
1
1
  import { AzureOpenAI as AzureOpenAIClient } from "openai";
2
2
  import { ChatOpenAI } from "../chat_models.js";
3
3
  import { getEndpoint } from "../utils/azure.js";
4
+ /**
5
+ * Azure OpenAI chat model integration.
6
+ *
7
+ * Setup:
8
+ * Install `@langchain/openai` and set the following environment variables:
9
+ *
10
+ * ```bash
11
+ * npm install @langchain/openai
12
+ * export AZURE_OPENAI_API_KEY="your-api-key"
13
+ * export AZURE_OPENAI_API_DEPLOYMENT_NAME="your-deployment-name"
14
+ * export AZURE_OPENAI_API_VERSION="your-version"
15
+ * export AZURE_OPENAI_BASE_PATH="your-base-path"
16
+ * ```
17
+ *
18
+ * ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.AzureChatOpenAI.html#constructor)
19
+ *
20
+ * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
21
+ *
22
+ * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
23
+ * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
24
+ *
25
+ * ```typescript
26
+ * // When calling `.bind`, call options should be passed via the first argument
27
+ * const llmWithArgsBound = llm.bind({
28
+ * stop: ["\n"],
29
+ * tools: [...],
30
+ * });
31
+ *
32
+ * // When calling `.bindTools`, call options should be passed via the second argument
33
+ * const llmWithTools = llm.bindTools(
34
+ * [...],
35
+ * {
36
+ * tool_choice: "auto",
37
+ * }
38
+ * );
39
+ * ```
40
+ *
41
+ * ## Examples
42
+ *
43
+ * <details open>
44
+ * <summary><strong>Instantiate</strong></summary>
45
+ *
46
+ * ```typescript
47
+ * import { AzureChatOpenAI } from '@langchain/openai';
48
+ *
49
+ * const llm = new AzureChatOpenAI({
50
+ * azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY, // In Node.js defaults to process.env.AZURE_OPENAI_API_KEY
51
+ * azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_INSTANCE_NAME
52
+ * azureOpenAIApiDeploymentName: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME
53
+ * azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION, // In Node.js defaults to process.env.AZURE_OPENAI_API_VERSION
54
+ * temperature: 0,
55
+ * maxTokens: undefined,
56
+ * timeout: undefined,
57
+ * maxRetries: 2,
58
+ * // apiKey: "...",
59
+ * // baseUrl: "...",
60
+ * // other params...
61
+ * });
62
+ * ```
63
+ * </details>
64
+ *
65
+ * <br />
66
+ *
67
+ * <details>
68
+ * <summary><strong>Invoking</strong></summary>
69
+ *
70
+ * ```typescript
71
+ * const input = `Translate "I love programming" into French.`;
72
+ *
73
+ * // Models also accept a list of chat messages or a formatted prompt
74
+ * const result = await llm.invoke(input);
75
+ * console.log(result);
76
+ * ```
77
+ *
78
+ * ```txt
79
+ * AIMessage {
80
+ * "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
81
+ * "content": "J'adore la programmation.",
82
+ * "response_metadata": {
83
+ * "tokenUsage": {
84
+ * "completionTokens": 5,
85
+ * "promptTokens": 28,
86
+ * "totalTokens": 33
87
+ * },
88
+ * "finish_reason": "stop",
89
+ * "system_fingerprint": "fp_3aa7262c27"
90
+ * },
91
+ * "usage_metadata": {
92
+ * "input_tokens": 28,
93
+ * "output_tokens": 5,
94
+ * "total_tokens": 33
95
+ * }
96
+ * }
97
+ * ```
98
+ * </details>
99
+ *
100
+ * <br />
101
+ *
102
+ * <details>
103
+ * <summary><strong>Streaming Chunks</strong></summary>
104
+ *
105
+ * ```typescript
106
+ * for await (const chunk of await llm.stream(input)) {
107
+ * console.log(chunk);
108
+ * }
109
+ * ```
110
+ *
111
+ * ```txt
112
+ * AIMessageChunk {
113
+ * "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
114
+ * "content": ""
115
+ * }
116
+ * AIMessageChunk {
117
+ * "content": "J"
118
+ * }
119
+ * AIMessageChunk {
120
+ * "content": "'adore"
121
+ * }
122
+ * AIMessageChunk {
123
+ * "content": " la"
124
+ * }
125
+ * AIMessageChunk {
126
+ * "content": " programmation",,
127
+ * }
128
+ * AIMessageChunk {
129
+ * "content": ".",,
130
+ * }
131
+ * AIMessageChunk {
132
+ * "content": "",
133
+ * "response_metadata": {
134
+ * "finish_reason": "stop",
135
+ * "system_fingerprint": "fp_c9aa9c0491"
136
+ * },
137
+ * }
138
+ * AIMessageChunk {
139
+ * "content": "",
140
+ * "usage_metadata": {
141
+ * "input_tokens": 28,
142
+ * "output_tokens": 5,
143
+ * "total_tokens": 33
144
+ * }
145
+ * }
146
+ * ```
147
+ * </details>
148
+ *
149
+ * <br />
150
+ *
151
+ * <details>
152
+ * <summary><strong>Aggregate Streamed Chunks</strong></summary>
153
+ *
154
+ * ```typescript
155
+ * import { AIMessageChunk } from '@langchain/core/messages';
156
+ * import { concat } from '@langchain/core/utils/stream';
157
+ *
158
+ * const stream = await llm.stream(input);
159
+ * let full: AIMessageChunk | undefined;
160
+ * for await (const chunk of stream) {
161
+ * full = !full ? chunk : concat(full, chunk);
162
+ * }
163
+ * console.log(full);
164
+ * ```
165
+ *
166
+ * ```txt
167
+ * AIMessageChunk {
168
+ * "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
169
+ * "content": "J'adore la programmation.",
170
+ * "response_metadata": {
171
+ * "prompt": 0,
172
+ * "completion": 0,
173
+ * "finish_reason": "stop",
174
+ * },
175
+ * "usage_metadata": {
176
+ * "input_tokens": 28,
177
+ * "output_tokens": 5,
178
+ * "total_tokens": 33
179
+ * }
180
+ * }
181
+ * ```
182
+ * </details>
183
+ *
184
+ * <br />
185
+ *
186
+ * <details>
187
+ * <summary><strong>Bind tools</strong></summary>
188
+ *
189
+ * ```typescript
190
+ * import { z } from 'zod';
191
+ *
192
+ * const GetWeather = {
193
+ * name: "GetWeather",
194
+ * description: "Get the current weather in a given location",
195
+ * schema: z.object({
196
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
197
+ * }),
198
+ * }
199
+ *
200
+ * const GetPopulation = {
201
+ * name: "GetPopulation",
202
+ * description: "Get the current population in a given location",
203
+ * schema: z.object({
204
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
205
+ * }),
206
+ * }
207
+ *
208
+ * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
209
+ * const aiMsg = await llmWithTools.invoke(
210
+ * "Which city is hotter today and which is bigger: LA or NY?"
211
+ * );
212
+ * console.log(aiMsg.tool_calls);
213
+ * ```
214
+ *
215
+ * ```txt
216
+ * [
217
+ * {
218
+ * name: 'GetWeather',
219
+ * args: { location: 'Los Angeles, CA' },
220
+ * type: 'tool_call',
221
+ * id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
222
+ * },
223
+ * {
224
+ * name: 'GetWeather',
225
+ * args: { location: 'New York, NY' },
226
+ * type: 'tool_call',
227
+ * id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
228
+ * },
229
+ * {
230
+ * name: 'GetPopulation',
231
+ * args: { location: 'Los Angeles, CA' },
232
+ * type: 'tool_call',
233
+ * id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
234
+ * },
235
+ * {
236
+ * name: 'GetPopulation',
237
+ * args: { location: 'New York, NY' },
238
+ * type: 'tool_call',
239
+ * id: 'call_s9KQB1UWj45LLGaEnjz0179q'
240
+ * }
241
+ * ]
242
+ * ```
243
+ * </details>
244
+ *
245
+ * <br />
246
+ *
247
+ * <details>
248
+ * <summary><strong>Structured Output</strong></summary>
249
+ *
250
+ * ```typescript
251
+ * import { z } from 'zod';
252
+ *
253
+ * const Joke = z.object({
254
+ * setup: z.string().describe("The setup of the joke"),
255
+ * punchline: z.string().describe("The punchline to the joke"),
256
+ * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
257
+ * }).describe('Joke to tell user.');
258
+ *
259
+ * const structuredLlm = llm.withStructuredOutput(Joke);
260
+ * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats", { name: "Joke" });
261
+ * console.log(jokeResult);
262
+ * ```
263
+ *
264
+ * ```txt
265
+ * {
266
+ * setup: 'Why was the cat sitting on the computer?',
267
+ * punchline: 'Because it wanted to keep an eye on the mouse!',
268
+ * rating: 7
269
+ * }
270
+ * ```
271
+ * </details>
272
+ *
273
+ * <br />
274
+ *
275
+ * <details>
276
+ * <summary><strong>JSON Object Response Format</strong></summary>
277
+ *
278
+ * ```typescript
279
+ * const jsonLlm = llm.bind({ response_format: { type: "json_object" } });
280
+ * const jsonLlmAiMsg = await jsonLlm.invoke(
281
+ * "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
282
+ * );
283
+ * console.log(jsonLlmAiMsg.content);
284
+ * ```
285
+ *
286
+ * ```txt
287
+ * {
288
+ * "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
289
+ * }
290
+ * ```
291
+ * </details>
292
+ *
293
+ * <br />
294
+ *
295
+ * <details>
296
+ * <summary><strong>Multimodal</strong></summary>
297
+ *
298
+ * ```typescript
299
+ * import { HumanMessage } from '@langchain/core/messages';
300
+ *
301
+ * const imageUrl = "https://example.com/image.jpg";
302
+ * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
303
+ * const base64Image = Buffer.from(imageData).toString('base64');
304
+ *
305
+ * const message = new HumanMessage({
306
+ * content: [
307
+ * { type: "text", text: "describe the weather in this image" },
308
+ * {
309
+ * type: "image_url",
310
+ * image_url: { url: `data:image/jpeg;base64,${base64Image}` },
311
+ * },
312
+ * ]
313
+ * });
314
+ *
315
+ * const imageDescriptionAiMsg = await llm.invoke([message]);
316
+ * console.log(imageDescriptionAiMsg.content);
317
+ * ```
318
+ *
319
+ * ```txt
320
+ * 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.
321
+ * ```
322
+ * </details>
323
+ *
324
+ * <br />
325
+ *
326
+ * <details>
327
+ * <summary><strong>Usage Metadata</strong></summary>
328
+ *
329
+ * ```typescript
330
+ * const aiMsgForMetadata = await llm.invoke(input);
331
+ * console.log(aiMsgForMetadata.usage_metadata);
332
+ * ```
333
+ *
334
+ * ```txt
335
+ * { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
336
+ * ```
337
+ * </details>
338
+ *
339
+ * <br />
340
+ *
341
+ * <details>
342
+ * <summary><strong>Logprobs</strong></summary>
343
+ *
344
+ * ```typescript
345
+ * const logprobsLlm = new ChatOpenAI({ logprobs: true });
346
+ * const aiMsgForLogprobs = await logprobsLlm.invoke(input);
347
+ * console.log(aiMsgForLogprobs.response_metadata.logprobs);
348
+ * ```
349
+ *
350
+ * ```txt
351
+ * {
352
+ * content: [
353
+ * {
354
+ * token: 'J',
355
+ * logprob: -0.000050616763,
356
+ * bytes: [Array],
357
+ * top_logprobs: []
358
+ * },
359
+ * {
360
+ * token: "'",
361
+ * logprob: -0.01868736,
362
+ * bytes: [Array],
363
+ * top_logprobs: []
364
+ * },
365
+ * {
366
+ * token: 'ad',
367
+ * logprob: -0.0000030545007,
368
+ * bytes: [Array],
369
+ * top_logprobs: []
370
+ * },
371
+ * { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
372
+ * {
373
+ * token: ' la',
374
+ * logprob: -0.515404,
375
+ * bytes: [Array],
376
+ * top_logprobs: []
377
+ * },
378
+ * {
379
+ * token: ' programm',
380
+ * logprob: -0.0000118755715,
381
+ * bytes: [Array],
382
+ * top_logprobs: []
383
+ * },
384
+ * { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
385
+ * {
386
+ * token: '.',
387
+ * logprob: -0.0000037697225,
388
+ * bytes: [Array],
389
+ * top_logprobs: []
390
+ * }
391
+ * ],
392
+ * refusal: null
393
+ * }
394
+ * ```
395
+ * </details>
396
+ *
397
+ * <br />
398
+ *
399
+ * <details>
400
+ * <summary><strong>Response Metadata</strong></summary>
401
+ *
402
+ * ```typescript
403
+ * const aiMsgForResponseMetadata = await llm.invoke(input);
404
+ * console.log(aiMsgForResponseMetadata.response_metadata);
405
+ * ```
406
+ *
407
+ * ```txt
408
+ * {
409
+ * tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
410
+ * finish_reason: 'stop',
411
+ * system_fingerprint: 'fp_3aa7262c27'
412
+ * }
413
+ * ```
414
+ * </details>
415
+ */
4
416
  export class AzureChatOpenAI extends ChatOpenAI {
5
417
  _llmType() {
6
418
  return "azure_openai";