@langchain/openai 0.2.5 → 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.
- package/dist/azure/chat_models.cjs +412 -0
- package/dist/azure/chat_models.d.ts +412 -0
- package/dist/azure/chat_models.js +412 -0
- package/dist/chat_models.cjs +546 -39
- package/dist/chat_models.d.ts +465 -40
- package/dist/chat_models.js +546 -39
- package/dist/types.d.ts +17 -0
- package/dist/utils/tools.cjs +54 -0
- package/dist/utils/tools.d.ts +20 -0
- package/dist/utils/tools.js +50 -0
- package/package.json +7 -7
- package/dist/tools/tests/dalle.int.test.d.ts +0 -1
- package/dist/tools/tests/dalle.int.test.js +0 -57
package/dist/chat_models.js
CHANGED
|
@@ -3,14 +3,16 @@ import { AIMessage, AIMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessa
|
|
|
3
3
|
import { ChatGenerationChunk, } from "@langchain/core/outputs";
|
|
4
4
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
|
|
5
5
|
import { BaseChatModel, } from "@langchain/core/language_models/chat_models";
|
|
6
|
-
import {
|
|
6
|
+
import { isOpenAITool, } from "@langchain/core/language_models/base";
|
|
7
7
|
import { RunnablePassthrough, RunnableSequence, } from "@langchain/core/runnables";
|
|
8
8
|
import { JsonOutputParser, StructuredOutputParser, } from "@langchain/core/output_parsers";
|
|
9
9
|
import { JsonOutputKeyToolsParser, convertLangChainToolCallToOpenAI, makeInvalidToolCall, parseToolCall, } from "@langchain/core/output_parsers/openai_tools";
|
|
10
10
|
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
11
|
+
import { zodResponseFormat } from "openai/helpers/zod";
|
|
11
12
|
import { getEndpoint } from "./utils/azure.js";
|
|
12
13
|
import { formatToOpenAIToolChoice, wrapOpenAIClientError, } from "./utils/openai.js";
|
|
13
14
|
import { formatFunctionDefinitions, } from "./utils/openai-format-fndef.js";
|
|
15
|
+
import { _convertToOpenAITool } from "./utils/tools.js";
|
|
14
16
|
function extractGenericMessageCustomRole(message) {
|
|
15
17
|
if (message.role !== "system" &&
|
|
16
18
|
message.role !== "assistant" &&
|
|
@@ -180,38 +182,434 @@ function convertMessagesToOpenAIParams(messages) {
|
|
|
180
182
|
return completionParam;
|
|
181
183
|
});
|
|
182
184
|
}
|
|
185
|
+
function _convertChatOpenAIToolTypeToOpenAITool(tool, fields) {
|
|
186
|
+
if (isOpenAITool(tool)) {
|
|
187
|
+
if (fields?.strict !== undefined) {
|
|
188
|
+
return {
|
|
189
|
+
...tool,
|
|
190
|
+
function: {
|
|
191
|
+
...tool.function,
|
|
192
|
+
strict: fields.strict,
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
return tool;
|
|
197
|
+
}
|
|
198
|
+
return _convertToOpenAITool(tool, fields);
|
|
199
|
+
}
|
|
183
200
|
/**
|
|
184
|
-
*
|
|
201
|
+
* OpenAI chat model integration.
|
|
202
|
+
*
|
|
203
|
+
* Setup:
|
|
204
|
+
* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
|
|
205
|
+
*
|
|
206
|
+
* ```bash
|
|
207
|
+
* npm install @langchain/openai
|
|
208
|
+
* export OPENAI_API_KEY="your-api-key"
|
|
209
|
+
* ```
|
|
210
|
+
*
|
|
211
|
+
* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
|
|
212
|
+
*
|
|
213
|
+
* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
|
|
214
|
+
*
|
|
215
|
+
* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
|
|
216
|
+
* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
|
|
217
|
+
*
|
|
218
|
+
* ```typescript
|
|
219
|
+
* // When calling `.bind`, call options should be passed via the first argument
|
|
220
|
+
* const llmWithArgsBound = llm.bind({
|
|
221
|
+
* stop: ["\n"],
|
|
222
|
+
* tools: [...],
|
|
223
|
+
* });
|
|
224
|
+
*
|
|
225
|
+
* // When calling `.bindTools`, call options should be passed via the second argument
|
|
226
|
+
* const llmWithTools = llm.bindTools(
|
|
227
|
+
* [...],
|
|
228
|
+
* {
|
|
229
|
+
* tool_choice: "auto",
|
|
230
|
+
* }
|
|
231
|
+
* );
|
|
232
|
+
* ```
|
|
233
|
+
*
|
|
234
|
+
* ## Examples
|
|
235
|
+
*
|
|
236
|
+
* <details open>
|
|
237
|
+
* <summary><strong>Instantiate</strong></summary>
|
|
238
|
+
*
|
|
239
|
+
* ```typescript
|
|
240
|
+
* import { ChatOpenAI } from '@langchain/openai';
|
|
241
|
+
*
|
|
242
|
+
* const llm = new ChatOpenAI({
|
|
243
|
+
* model: "gpt-4o",
|
|
244
|
+
* temperature: 0,
|
|
245
|
+
* maxTokens: undefined,
|
|
246
|
+
* timeout: undefined,
|
|
247
|
+
* maxRetries: 2,
|
|
248
|
+
* // apiKey: "...",
|
|
249
|
+
* // baseUrl: "...",
|
|
250
|
+
* // organization: "...",
|
|
251
|
+
* // other params...
|
|
252
|
+
* });
|
|
253
|
+
* ```
|
|
254
|
+
* </details>
|
|
255
|
+
*
|
|
256
|
+
* <br />
|
|
257
|
+
*
|
|
258
|
+
* <details>
|
|
259
|
+
* <summary><strong>Invoking</strong></summary>
|
|
260
|
+
*
|
|
261
|
+
* ```typescript
|
|
262
|
+
* const input = `Translate "I love programming" into French.`;
|
|
263
|
+
*
|
|
264
|
+
* // Models also accept a list of chat messages or a formatted prompt
|
|
265
|
+
* const result = await llm.invoke(input);
|
|
266
|
+
* console.log(result);
|
|
267
|
+
* ```
|
|
268
|
+
*
|
|
269
|
+
* ```txt
|
|
270
|
+
* AIMessage {
|
|
271
|
+
* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
|
|
272
|
+
* "content": "J'adore la programmation.",
|
|
273
|
+
* "response_metadata": {
|
|
274
|
+
* "tokenUsage": {
|
|
275
|
+
* "completionTokens": 5,
|
|
276
|
+
* "promptTokens": 28,
|
|
277
|
+
* "totalTokens": 33
|
|
278
|
+
* },
|
|
279
|
+
* "finish_reason": "stop",
|
|
280
|
+
* "system_fingerprint": "fp_3aa7262c27"
|
|
281
|
+
* },
|
|
282
|
+
* "usage_metadata": {
|
|
283
|
+
* "input_tokens": 28,
|
|
284
|
+
* "output_tokens": 5,
|
|
285
|
+
* "total_tokens": 33
|
|
286
|
+
* }
|
|
287
|
+
* }
|
|
288
|
+
* ```
|
|
289
|
+
* </details>
|
|
290
|
+
*
|
|
291
|
+
* <br />
|
|
292
|
+
*
|
|
293
|
+
* <details>
|
|
294
|
+
* <summary><strong>Streaming Chunks</strong></summary>
|
|
295
|
+
*
|
|
296
|
+
* ```typescript
|
|
297
|
+
* for await (const chunk of await llm.stream(input)) {
|
|
298
|
+
* console.log(chunk);
|
|
299
|
+
* }
|
|
300
|
+
* ```
|
|
301
|
+
*
|
|
302
|
+
* ```txt
|
|
303
|
+
* AIMessageChunk {
|
|
304
|
+
* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
|
|
305
|
+
* "content": ""
|
|
306
|
+
* }
|
|
307
|
+
* AIMessageChunk {
|
|
308
|
+
* "content": "J"
|
|
309
|
+
* }
|
|
310
|
+
* AIMessageChunk {
|
|
311
|
+
* "content": "'adore"
|
|
312
|
+
* }
|
|
313
|
+
* AIMessageChunk {
|
|
314
|
+
* "content": " la"
|
|
315
|
+
* }
|
|
316
|
+
* AIMessageChunk {
|
|
317
|
+
* "content": " programmation",,
|
|
318
|
+
* }
|
|
319
|
+
* AIMessageChunk {
|
|
320
|
+
* "content": ".",,
|
|
321
|
+
* }
|
|
322
|
+
* AIMessageChunk {
|
|
323
|
+
* "content": "",
|
|
324
|
+
* "response_metadata": {
|
|
325
|
+
* "finish_reason": "stop",
|
|
326
|
+
* "system_fingerprint": "fp_c9aa9c0491"
|
|
327
|
+
* },
|
|
328
|
+
* }
|
|
329
|
+
* AIMessageChunk {
|
|
330
|
+
* "content": "",
|
|
331
|
+
* "usage_metadata": {
|
|
332
|
+
* "input_tokens": 28,
|
|
333
|
+
* "output_tokens": 5,
|
|
334
|
+
* "total_tokens": 33
|
|
335
|
+
* }
|
|
336
|
+
* }
|
|
337
|
+
* ```
|
|
338
|
+
* </details>
|
|
339
|
+
*
|
|
340
|
+
* <br />
|
|
341
|
+
*
|
|
342
|
+
* <details>
|
|
343
|
+
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
|
|
344
|
+
*
|
|
345
|
+
* ```typescript
|
|
346
|
+
* import { AIMessageChunk } from '@langchain/core/messages';
|
|
347
|
+
* import { concat } from '@langchain/core/utils/stream';
|
|
348
|
+
*
|
|
349
|
+
* const stream = await llm.stream(input);
|
|
350
|
+
* let full: AIMessageChunk | undefined;
|
|
351
|
+
* for await (const chunk of stream) {
|
|
352
|
+
* full = !full ? chunk : concat(full, chunk);
|
|
353
|
+
* }
|
|
354
|
+
* console.log(full);
|
|
355
|
+
* ```
|
|
356
|
+
*
|
|
357
|
+
* ```txt
|
|
358
|
+
* AIMessageChunk {
|
|
359
|
+
* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
|
|
360
|
+
* "content": "J'adore la programmation.",
|
|
361
|
+
* "response_metadata": {
|
|
362
|
+
* "prompt": 0,
|
|
363
|
+
* "completion": 0,
|
|
364
|
+
* "finish_reason": "stop",
|
|
365
|
+
* },
|
|
366
|
+
* "usage_metadata": {
|
|
367
|
+
* "input_tokens": 28,
|
|
368
|
+
* "output_tokens": 5,
|
|
369
|
+
* "total_tokens": 33
|
|
370
|
+
* }
|
|
371
|
+
* }
|
|
372
|
+
* ```
|
|
373
|
+
* </details>
|
|
374
|
+
*
|
|
375
|
+
* <br />
|
|
376
|
+
*
|
|
377
|
+
* <details>
|
|
378
|
+
* <summary><strong>Bind tools</strong></summary>
|
|
379
|
+
*
|
|
380
|
+
* ```typescript
|
|
381
|
+
* import { z } from 'zod';
|
|
382
|
+
*
|
|
383
|
+
* const GetWeather = {
|
|
384
|
+
* name: "GetWeather",
|
|
385
|
+
* description: "Get the current weather in a given location",
|
|
386
|
+
* schema: z.object({
|
|
387
|
+
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
388
|
+
* }),
|
|
389
|
+
* }
|
|
390
|
+
*
|
|
391
|
+
* const GetPopulation = {
|
|
392
|
+
* name: "GetPopulation",
|
|
393
|
+
* description: "Get the current population in a given location",
|
|
394
|
+
* schema: z.object({
|
|
395
|
+
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
396
|
+
* }),
|
|
397
|
+
* }
|
|
398
|
+
*
|
|
399
|
+
* const llmWithTools = llm.bindTools(
|
|
400
|
+
* [GetWeather, GetPopulation],
|
|
401
|
+
* {
|
|
402
|
+
* // strict: true // enforce tool args schema is respected
|
|
403
|
+
* }
|
|
404
|
+
* );
|
|
405
|
+
* const aiMsg = await llmWithTools.invoke(
|
|
406
|
+
* "Which city is hotter today and which is bigger: LA or NY?"
|
|
407
|
+
* );
|
|
408
|
+
* console.log(aiMsg.tool_calls);
|
|
409
|
+
* ```
|
|
410
|
+
*
|
|
411
|
+
* ```txt
|
|
412
|
+
* [
|
|
413
|
+
* {
|
|
414
|
+
* name: 'GetWeather',
|
|
415
|
+
* args: { location: 'Los Angeles, CA' },
|
|
416
|
+
* type: 'tool_call',
|
|
417
|
+
* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
|
|
418
|
+
* },
|
|
419
|
+
* {
|
|
420
|
+
* name: 'GetWeather',
|
|
421
|
+
* args: { location: 'New York, NY' },
|
|
422
|
+
* type: 'tool_call',
|
|
423
|
+
* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
|
|
424
|
+
* },
|
|
425
|
+
* {
|
|
426
|
+
* name: 'GetPopulation',
|
|
427
|
+
* args: { location: 'Los Angeles, CA' },
|
|
428
|
+
* type: 'tool_call',
|
|
429
|
+
* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
|
|
430
|
+
* },
|
|
431
|
+
* {
|
|
432
|
+
* name: 'GetPopulation',
|
|
433
|
+
* args: { location: 'New York, NY' },
|
|
434
|
+
* type: 'tool_call',
|
|
435
|
+
* id: 'call_s9KQB1UWj45LLGaEnjz0179q'
|
|
436
|
+
* }
|
|
437
|
+
* ]
|
|
438
|
+
* ```
|
|
439
|
+
* </details>
|
|
440
|
+
*
|
|
441
|
+
* <br />
|
|
442
|
+
*
|
|
443
|
+
* <details>
|
|
444
|
+
* <summary><strong>Structured Output</strong></summary>
|
|
445
|
+
*
|
|
446
|
+
* ```typescript
|
|
447
|
+
* import { z } from 'zod';
|
|
448
|
+
*
|
|
449
|
+
* const Joke = z.object({
|
|
450
|
+
* setup: z.string().describe("The setup of the joke"),
|
|
451
|
+
* punchline: z.string().describe("The punchline to the joke"),
|
|
452
|
+
* rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
|
|
453
|
+
* }).describe('Joke to tell user.');
|
|
454
|
+
*
|
|
455
|
+
* const structuredLlm = llm.withStructuredOutput(Joke);
|
|
456
|
+
* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats", { name: "Joke" });
|
|
457
|
+
* console.log(jokeResult);
|
|
458
|
+
* ```
|
|
459
|
+
*
|
|
460
|
+
* ```txt
|
|
461
|
+
* {
|
|
462
|
+
* setup: 'Why was the cat sitting on the computer?',
|
|
463
|
+
* punchline: 'Because it wanted to keep an eye on the mouse!',
|
|
464
|
+
* rating: 7
|
|
465
|
+
* }
|
|
466
|
+
* ```
|
|
467
|
+
* </details>
|
|
468
|
+
*
|
|
469
|
+
* <br />
|
|
470
|
+
*
|
|
471
|
+
* <details>
|
|
472
|
+
* <summary><strong>JSON Object Response Format</strong></summary>
|
|
473
|
+
*
|
|
474
|
+
* ```typescript
|
|
475
|
+
* const jsonLlm = llm.bind({ response_format: { type: "json_object" } });
|
|
476
|
+
* const jsonLlmAiMsg = await jsonLlm.invoke(
|
|
477
|
+
* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
|
|
478
|
+
* );
|
|
479
|
+
* console.log(jsonLlmAiMsg.content);
|
|
480
|
+
* ```
|
|
481
|
+
*
|
|
482
|
+
* ```txt
|
|
483
|
+
* {
|
|
484
|
+
* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
|
|
485
|
+
* }
|
|
486
|
+
* ```
|
|
487
|
+
* </details>
|
|
185
488
|
*
|
|
186
|
-
*
|
|
489
|
+
* <br />
|
|
187
490
|
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
* `AZURE_OPENAI_API_INSTANCE_NAME`,
|
|
191
|
-
* `AZURE_OPENAI_API_DEPLOYMENT_NAME`
|
|
192
|
-
* and `AZURE_OPENAI_API_VERSION` environment variables set.
|
|
193
|
-
* `AZURE_OPENAI_BASE_PATH` is optional and will override `AZURE_OPENAI_API_INSTANCE_NAME` if you need to use a custom endpoint.
|
|
491
|
+
* <details>
|
|
492
|
+
* <summary><strong>Multimodal</strong></summary>
|
|
194
493
|
*
|
|
195
|
-
* @remarks
|
|
196
|
-
* Any parameters that are valid to be passed to {@link
|
|
197
|
-
* https://platform.openai.com/docs/api-reference/chat/create |
|
|
198
|
-
* `openai.createChatCompletion`} can be passed through {@link modelKwargs}, even
|
|
199
|
-
* if not explicitly available on this class.
|
|
200
|
-
* @example
|
|
201
494
|
* ```typescript
|
|
202
|
-
*
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
*
|
|
495
|
+
* import { HumanMessage } from '@langchain/core/messages';
|
|
496
|
+
*
|
|
497
|
+
* const imageUrl = "https://example.com/image.jpg";
|
|
498
|
+
* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
|
|
499
|
+
* const base64Image = Buffer.from(imageData).toString('base64');
|
|
500
|
+
*
|
|
501
|
+
* const message = new HumanMessage({
|
|
502
|
+
* content: [
|
|
503
|
+
* { type: "text", text: "describe the weather in this image" },
|
|
504
|
+
* {
|
|
505
|
+
* type: "image_url",
|
|
506
|
+
* image_url: { url: `data:image/jpeg;base64,${base64Image}` },
|
|
507
|
+
* },
|
|
508
|
+
* ]
|
|
206
509
|
* });
|
|
207
510
|
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
511
|
+
* const imageDescriptionAiMsg = await llm.invoke([message]);
|
|
512
|
+
* console.log(imageDescriptionAiMsg.content);
|
|
513
|
+
* ```
|
|
514
|
+
*
|
|
515
|
+
* ```txt
|
|
516
|
+
* 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.
|
|
517
|
+
* ```
|
|
518
|
+
* </details>
|
|
519
|
+
*
|
|
520
|
+
* <br />
|
|
521
|
+
*
|
|
522
|
+
* <details>
|
|
523
|
+
* <summary><strong>Usage Metadata</strong></summary>
|
|
524
|
+
*
|
|
525
|
+
* ```typescript
|
|
526
|
+
* const aiMsgForMetadata = await llm.invoke(input);
|
|
527
|
+
* console.log(aiMsgForMetadata.usage_metadata);
|
|
528
|
+
* ```
|
|
529
|
+
*
|
|
530
|
+
* ```txt
|
|
531
|
+
* { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
|
|
532
|
+
* ```
|
|
533
|
+
* </details>
|
|
534
|
+
*
|
|
535
|
+
* <br />
|
|
536
|
+
*
|
|
537
|
+
* <details>
|
|
538
|
+
* <summary><strong>Logprobs</strong></summary>
|
|
539
|
+
*
|
|
540
|
+
* ```typescript
|
|
541
|
+
* const logprobsLlm = new ChatOpenAI({ logprobs: true });
|
|
542
|
+
* const aiMsgForLogprobs = await logprobsLlm.invoke(input);
|
|
543
|
+
* console.log(aiMsgForLogprobs.response_metadata.logprobs);
|
|
544
|
+
* ```
|
|
545
|
+
*
|
|
546
|
+
* ```txt
|
|
547
|
+
* {
|
|
548
|
+
* content: [
|
|
549
|
+
* {
|
|
550
|
+
* token: 'J',
|
|
551
|
+
* logprob: -0.000050616763,
|
|
552
|
+
* bytes: [Array],
|
|
553
|
+
* top_logprobs: []
|
|
554
|
+
* },
|
|
555
|
+
* {
|
|
556
|
+
* token: "'",
|
|
557
|
+
* logprob: -0.01868736,
|
|
558
|
+
* bytes: [Array],
|
|
559
|
+
* top_logprobs: []
|
|
560
|
+
* },
|
|
561
|
+
* {
|
|
562
|
+
* token: 'ad',
|
|
563
|
+
* logprob: -0.0000030545007,
|
|
564
|
+
* bytes: [Array],
|
|
565
|
+
* top_logprobs: []
|
|
566
|
+
* },
|
|
567
|
+
* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
568
|
+
* {
|
|
569
|
+
* token: ' la',
|
|
570
|
+
* logprob: -0.515404,
|
|
571
|
+
* bytes: [Array],
|
|
572
|
+
* top_logprobs: []
|
|
573
|
+
* },
|
|
574
|
+
* {
|
|
575
|
+
* token: ' programm',
|
|
576
|
+
* logprob: -0.0000118755715,
|
|
577
|
+
* bytes: [Array],
|
|
578
|
+
* top_logprobs: []
|
|
579
|
+
* },
|
|
580
|
+
* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
581
|
+
* {
|
|
582
|
+
* token: '.',
|
|
583
|
+
* logprob: -0.0000037697225,
|
|
584
|
+
* bytes: [Array],
|
|
585
|
+
* top_logprobs: []
|
|
586
|
+
* }
|
|
587
|
+
* ],
|
|
588
|
+
* refusal: null
|
|
589
|
+
* }
|
|
590
|
+
* ```
|
|
591
|
+
* </details>
|
|
592
|
+
*
|
|
593
|
+
* <br />
|
|
210
594
|
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
595
|
+
* <details>
|
|
596
|
+
* <summary><strong>Response Metadata</strong></summary>
|
|
213
597
|
*
|
|
598
|
+
* ```typescript
|
|
599
|
+
* const aiMsgForResponseMetadata = await llm.invoke(input);
|
|
600
|
+
* console.log(aiMsgForResponseMetadata.response_metadata);
|
|
214
601
|
* ```
|
|
602
|
+
*
|
|
603
|
+
* ```txt
|
|
604
|
+
* {
|
|
605
|
+
* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
|
|
606
|
+
* finish_reason: 'stop',
|
|
607
|
+
* system_fingerprint: 'fp_3aa7262c27'
|
|
608
|
+
* }
|
|
609
|
+
* ```
|
|
610
|
+
* </details>
|
|
611
|
+
*
|
|
612
|
+
* <br />
|
|
215
613
|
*/
|
|
216
614
|
export class ChatOpenAI extends BaseChatModel {
|
|
217
615
|
static lc_name() {
|
|
@@ -439,6 +837,16 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
439
837
|
writable: true,
|
|
440
838
|
value: void 0
|
|
441
839
|
});
|
|
840
|
+
/**
|
|
841
|
+
* Whether the model supports the `strict` argument when passing in tools.
|
|
842
|
+
* If `undefined` the `strict` argument will not be passed to OpenAI.
|
|
843
|
+
*/
|
|
844
|
+
Object.defineProperty(this, "supportsStrictToolCalling", {
|
|
845
|
+
enumerable: true,
|
|
846
|
+
configurable: true,
|
|
847
|
+
writable: true,
|
|
848
|
+
value: void 0
|
|
849
|
+
});
|
|
442
850
|
this.openAIApiKey =
|
|
443
851
|
fields?.apiKey ??
|
|
444
852
|
fields?.openAIApiKey ??
|
|
@@ -511,6 +919,11 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
511
919
|
...configuration,
|
|
512
920
|
...fields?.configuration,
|
|
513
921
|
};
|
|
922
|
+
// If `supportsStrictToolCalling` is explicitly set, use that value.
|
|
923
|
+
// Else leave undefined so it's not passed to OpenAI.
|
|
924
|
+
if (fields?.supportsStrictToolCalling !== undefined) {
|
|
925
|
+
this.supportsStrictToolCalling = fields.supportsStrictToolCalling;
|
|
926
|
+
}
|
|
514
927
|
}
|
|
515
928
|
getLsParams(options) {
|
|
516
929
|
const params = this.invocationParams(options);
|
|
@@ -524,18 +937,39 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
524
937
|
};
|
|
525
938
|
}
|
|
526
939
|
bindTools(tools, kwargs) {
|
|
940
|
+
let strict;
|
|
941
|
+
if (kwargs?.strict !== undefined) {
|
|
942
|
+
strict = kwargs.strict;
|
|
943
|
+
}
|
|
944
|
+
else if (this.supportsStrictToolCalling !== undefined) {
|
|
945
|
+
strict = this.supportsStrictToolCalling;
|
|
946
|
+
}
|
|
527
947
|
return this.bind({
|
|
528
|
-
tools: tools.map(
|
|
948
|
+
tools: tools.map((tool) => _convertChatOpenAIToolTypeToOpenAITool(tool, { strict })),
|
|
529
949
|
...kwargs,
|
|
530
950
|
});
|
|
531
951
|
}
|
|
952
|
+
createResponseFormat(resFormat) {
|
|
953
|
+
if (resFormat &&
|
|
954
|
+
resFormat.type === "json_schema" &&
|
|
955
|
+
resFormat.json_schema.schema &&
|
|
956
|
+
isZodSchema(resFormat.json_schema.schema)) {
|
|
957
|
+
return zodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, {
|
|
958
|
+
description: resFormat.json_schema.description,
|
|
959
|
+
});
|
|
960
|
+
}
|
|
961
|
+
return resFormat;
|
|
962
|
+
}
|
|
532
963
|
/**
|
|
533
964
|
* Get the parameters used to invoke the model
|
|
534
965
|
*/
|
|
535
966
|
invocationParams(options, extra) {
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
967
|
+
let strict;
|
|
968
|
+
if (options?.strict !== undefined) {
|
|
969
|
+
strict = options.strict;
|
|
970
|
+
}
|
|
971
|
+
else if (this.supportsStrictToolCalling !== undefined) {
|
|
972
|
+
strict = this.supportsStrictToolCalling;
|
|
539
973
|
}
|
|
540
974
|
let streamOptionsConfig = {};
|
|
541
975
|
if (options?.stream_options !== undefined) {
|
|
@@ -561,11 +995,11 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
561
995
|
stream: this.streaming,
|
|
562
996
|
functions: options?.functions,
|
|
563
997
|
function_call: options?.function_call,
|
|
564
|
-
tools:
|
|
565
|
-
? options
|
|
566
|
-
:
|
|
998
|
+
tools: options?.tools?.length
|
|
999
|
+
? options.tools.map((tool) => _convertChatOpenAIToolTypeToOpenAITool(tool, { strict }))
|
|
1000
|
+
: undefined,
|
|
567
1001
|
tool_choice: formatToOpenAIToolChoice(options?.tool_choice),
|
|
568
|
-
response_format: options?.response_format,
|
|
1002
|
+
response_format: this.createResponseFormat(options?.response_format),
|
|
569
1003
|
seed: options?.seed,
|
|
570
1004
|
...streamOptionsConfig,
|
|
571
1005
|
parallel_tool_calls: options?.parallel_tool_calls,
|
|
@@ -591,6 +1025,20 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
591
1025
|
stream: true,
|
|
592
1026
|
};
|
|
593
1027
|
let defaultRole;
|
|
1028
|
+
if (params.response_format &&
|
|
1029
|
+
params.response_format.type === "json_schema") {
|
|
1030
|
+
console.warn(`OpenAI does not yet support streaming with "response_format" set to "json_schema". Falling back to non-streaming mode.`);
|
|
1031
|
+
const res = await this._generate(messages, options, runManager);
|
|
1032
|
+
const chunk = new ChatGenerationChunk({
|
|
1033
|
+
message: new AIMessageChunk({
|
|
1034
|
+
...res.generations[0].message,
|
|
1035
|
+
}),
|
|
1036
|
+
text: res.generations[0].text,
|
|
1037
|
+
generationInfo: res.generations[0].generationInfo,
|
|
1038
|
+
});
|
|
1039
|
+
yield chunk;
|
|
1040
|
+
return runManager?.handleLLMNewToken(res.generations[0].text ?? "", undefined, undefined, undefined, undefined, { chunk });
|
|
1041
|
+
}
|
|
594
1042
|
const streamIterable = await this.completionWithRetry(params, options);
|
|
595
1043
|
let usage;
|
|
596
1044
|
for await (const data of streamIterable) {
|
|
@@ -694,14 +1142,28 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
694
1142
|
return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } };
|
|
695
1143
|
}
|
|
696
1144
|
else {
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
1145
|
+
let data;
|
|
1146
|
+
if (options.response_format &&
|
|
1147
|
+
options.response_format.type === "json_schema") {
|
|
1148
|
+
data = await this.betaParsedCompletionWithRetry({
|
|
1149
|
+
...params,
|
|
1150
|
+
stream: false,
|
|
1151
|
+
messages: messagesMapped,
|
|
1152
|
+
}, {
|
|
1153
|
+
signal: options?.signal,
|
|
1154
|
+
...options?.options,
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
else {
|
|
1158
|
+
data = await this.completionWithRetry({
|
|
1159
|
+
...params,
|
|
1160
|
+
stream: false,
|
|
1161
|
+
messages: messagesMapped,
|
|
1162
|
+
}, {
|
|
1163
|
+
signal: options?.signal,
|
|
1164
|
+
...options?.options,
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
705
1167
|
const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data?.usage ?? {};
|
|
706
1168
|
if (completionTokens) {
|
|
707
1169
|
tokenUsage.completionTokens =
|
|
@@ -846,6 +1308,25 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
846
1308
|
}
|
|
847
1309
|
});
|
|
848
1310
|
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Call the beta chat completions parse endpoint. This should only be called if
|
|
1313
|
+
* response_format is set to "json_object".
|
|
1314
|
+
* @param {OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming} request
|
|
1315
|
+
* @param {OpenAICoreRequestOptions | undefined} options
|
|
1316
|
+
*/
|
|
1317
|
+
async betaParsedCompletionWithRetry(request, options) {
|
|
1318
|
+
const requestOptions = this._getClientOptions(options);
|
|
1319
|
+
return this.caller.call(async () => {
|
|
1320
|
+
try {
|
|
1321
|
+
const res = await this.client.beta.chat.completions.parse(request, requestOptions);
|
|
1322
|
+
return res;
|
|
1323
|
+
}
|
|
1324
|
+
catch (e) {
|
|
1325
|
+
const error = wrapOpenAIClientError(e);
|
|
1326
|
+
throw error;
|
|
1327
|
+
}
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
849
1330
|
_getClientOptions(options) {
|
|
850
1331
|
if (!this.client) {
|
|
851
1332
|
const openAIEndpointConfig = {
|
|
@@ -924,6 +1405,9 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
924
1405
|
}
|
|
925
1406
|
let llm;
|
|
926
1407
|
let outputParser;
|
|
1408
|
+
if (config?.strict !== undefined && method === "jsonMode") {
|
|
1409
|
+
throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");
|
|
1410
|
+
}
|
|
927
1411
|
if (method === "jsonMode") {
|
|
928
1412
|
llm = this.bind({
|
|
929
1413
|
response_format: { type: "json_object" },
|
|
@@ -935,6 +1419,25 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
935
1419
|
outputParser = new JsonOutputParser();
|
|
936
1420
|
}
|
|
937
1421
|
}
|
|
1422
|
+
else if (method === "jsonSchema") {
|
|
1423
|
+
llm = this.bind({
|
|
1424
|
+
response_format: {
|
|
1425
|
+
type: "json_schema",
|
|
1426
|
+
json_schema: {
|
|
1427
|
+
name: name ?? "extract",
|
|
1428
|
+
description: schema.description,
|
|
1429
|
+
schema,
|
|
1430
|
+
strict: config?.strict,
|
|
1431
|
+
},
|
|
1432
|
+
},
|
|
1433
|
+
});
|
|
1434
|
+
if (isZodSchema(schema)) {
|
|
1435
|
+
outputParser = StructuredOutputParser.fromZodSchema(schema);
|
|
1436
|
+
}
|
|
1437
|
+
else {
|
|
1438
|
+
outputParser = new JsonOutputParser();
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
938
1441
|
else {
|
|
939
1442
|
let functionName = name ?? "extract";
|
|
940
1443
|
// Is function calling
|
|
@@ -957,6 +1460,8 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
957
1460
|
name: functionName,
|
|
958
1461
|
},
|
|
959
1462
|
},
|
|
1463
|
+
// Do not pass `strict` argument to OpenAI if `config.strict` is undefined
|
|
1464
|
+
...(config?.strict !== undefined ? { strict: config.strict } : {}),
|
|
960
1465
|
});
|
|
961
1466
|
outputParser = new JsonOutputKeyToolsParser({
|
|
962
1467
|
returnSingle: true,
|
|
@@ -993,6 +1498,8 @@ export class ChatOpenAI extends BaseChatModel {
|
|
|
993
1498
|
name: functionName,
|
|
994
1499
|
},
|
|
995
1500
|
},
|
|
1501
|
+
// Do not pass `strict` argument to OpenAI if `config.strict` is undefined
|
|
1502
|
+
...(config?.strict !== undefined ? { strict: config.strict } : {}),
|
|
996
1503
|
});
|
|
997
1504
|
outputParser = new JsonOutputKeyToolsParser({
|
|
998
1505
|
returnSingle: true,
|