@langchain/openai 0.2.6 → 0.2.8
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 +541 -37
- package/dist/chat_models.d.ts +462 -29
- package/dist/chat_models.js +541 -37
- package/dist/types.d.ts +12 -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 +4 -4
package/dist/chat_models.cjs
CHANGED
|
@@ -7,14 +7,15 @@ const outputs_1 = require("@langchain/core/outputs");
|
|
|
7
7
|
const env_1 = require("@langchain/core/utils/env");
|
|
8
8
|
const chat_models_1 = require("@langchain/core/language_models/chat_models");
|
|
9
9
|
const base_1 = require("@langchain/core/language_models/base");
|
|
10
|
-
const function_calling_1 = require("@langchain/core/utils/function_calling");
|
|
11
10
|
const runnables_1 = require("@langchain/core/runnables");
|
|
12
11
|
const output_parsers_1 = require("@langchain/core/output_parsers");
|
|
13
12
|
const openai_tools_1 = require("@langchain/core/output_parsers/openai_tools");
|
|
14
13
|
const zod_to_json_schema_1 = require("zod-to-json-schema");
|
|
14
|
+
const zod_1 = require("openai/helpers/zod");
|
|
15
15
|
const azure_js_1 = require("./utils/azure.cjs");
|
|
16
16
|
const openai_js_1 = require("./utils/openai.cjs");
|
|
17
17
|
const openai_format_fndef_js_1 = require("./utils/openai-format-fndef.cjs");
|
|
18
|
+
const tools_js_1 = require("./utils/tools.cjs");
|
|
18
19
|
function extractGenericMessageCustomRole(message) {
|
|
19
20
|
if (message.role !== "system" &&
|
|
20
21
|
message.role !== "assistant" &&
|
|
@@ -198,40 +199,466 @@ function _convertChatOpenAIToolTypeToOpenAITool(tool, fields) {
|
|
|
198
199
|
}
|
|
199
200
|
return tool;
|
|
200
201
|
}
|
|
201
|
-
return (0,
|
|
202
|
+
return (0, tools_js_1._convertToOpenAITool)(tool, fields);
|
|
202
203
|
}
|
|
203
204
|
/**
|
|
204
|
-
*
|
|
205
|
-
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
208
|
-
*
|
|
209
|
-
*
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
*
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
*
|
|
217
|
-
*
|
|
218
|
-
*
|
|
219
|
-
*
|
|
220
|
-
*
|
|
205
|
+
* OpenAI chat model integration.
|
|
206
|
+
*
|
|
207
|
+
* Setup:
|
|
208
|
+
* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`.
|
|
209
|
+
*
|
|
210
|
+
* ```bash
|
|
211
|
+
* npm install @langchain/openai
|
|
212
|
+
* export OPENAI_API_KEY="your-api-key"
|
|
213
|
+
* ```
|
|
214
|
+
*
|
|
215
|
+
* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor)
|
|
216
|
+
*
|
|
217
|
+
* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html)
|
|
218
|
+
*
|
|
219
|
+
* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
|
|
220
|
+
* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
|
|
221
|
+
*
|
|
222
|
+
* ```typescript
|
|
223
|
+
* // When calling `.bind`, call options should be passed via the first argument
|
|
224
|
+
* const llmWithArgsBound = llm.bind({
|
|
225
|
+
* stop: ["\n"],
|
|
226
|
+
* tools: [...],
|
|
227
|
+
* });
|
|
228
|
+
*
|
|
229
|
+
* // When calling `.bindTools`, call options should be passed via the second argument
|
|
230
|
+
* const llmWithTools = llm.bindTools(
|
|
231
|
+
* [...],
|
|
232
|
+
* {
|
|
233
|
+
* tool_choice: "auto",
|
|
234
|
+
* }
|
|
235
|
+
* );
|
|
236
|
+
* ```
|
|
237
|
+
*
|
|
238
|
+
* ## Examples
|
|
239
|
+
*
|
|
240
|
+
* <details open>
|
|
241
|
+
* <summary><strong>Instantiate</strong></summary>
|
|
242
|
+
*
|
|
221
243
|
* ```typescript
|
|
222
|
-
*
|
|
223
|
-
*
|
|
224
|
-
*
|
|
225
|
-
* model: "
|
|
244
|
+
* import { ChatOpenAI } from '@langchain/openai';
|
|
245
|
+
*
|
|
246
|
+
* const llm = new ChatOpenAI({
|
|
247
|
+
* model: "gpt-4o",
|
|
248
|
+
* temperature: 0,
|
|
249
|
+
* maxTokens: undefined,
|
|
250
|
+
* timeout: undefined,
|
|
251
|
+
* maxRetries: 2,
|
|
252
|
+
* // apiKey: "...",
|
|
253
|
+
* // baseUrl: "...",
|
|
254
|
+
* // organization: "...",
|
|
255
|
+
* // other params...
|
|
226
256
|
* });
|
|
257
|
+
* ```
|
|
258
|
+
* </details>
|
|
259
|
+
*
|
|
260
|
+
* <br />
|
|
261
|
+
*
|
|
262
|
+
* <details>
|
|
263
|
+
* <summary><strong>Invoking</strong></summary>
|
|
264
|
+
*
|
|
265
|
+
* ```typescript
|
|
266
|
+
* const input = `Translate "I love programming" into French.`;
|
|
267
|
+
*
|
|
268
|
+
* // Models also accept a list of chat messages or a formatted prompt
|
|
269
|
+
* const result = await llm.invoke(input);
|
|
270
|
+
* console.log(result);
|
|
271
|
+
* ```
|
|
272
|
+
*
|
|
273
|
+
* ```txt
|
|
274
|
+
* AIMessage {
|
|
275
|
+
* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz",
|
|
276
|
+
* "content": "J'adore la programmation.",
|
|
277
|
+
* "response_metadata": {
|
|
278
|
+
* "tokenUsage": {
|
|
279
|
+
* "completionTokens": 5,
|
|
280
|
+
* "promptTokens": 28,
|
|
281
|
+
* "totalTokens": 33
|
|
282
|
+
* },
|
|
283
|
+
* "finish_reason": "stop",
|
|
284
|
+
* "system_fingerprint": "fp_3aa7262c27"
|
|
285
|
+
* },
|
|
286
|
+
* "usage_metadata": {
|
|
287
|
+
* "input_tokens": 28,
|
|
288
|
+
* "output_tokens": 5,
|
|
289
|
+
* "total_tokens": 33
|
|
290
|
+
* }
|
|
291
|
+
* }
|
|
292
|
+
* ```
|
|
293
|
+
* </details>
|
|
294
|
+
*
|
|
295
|
+
* <br />
|
|
296
|
+
*
|
|
297
|
+
* <details>
|
|
298
|
+
* <summary><strong>Streaming Chunks</strong></summary>
|
|
299
|
+
*
|
|
300
|
+
* ```typescript
|
|
301
|
+
* for await (const chunk of await llm.stream(input)) {
|
|
302
|
+
* console.log(chunk);
|
|
303
|
+
* }
|
|
304
|
+
* ```
|
|
305
|
+
*
|
|
306
|
+
* ```txt
|
|
307
|
+
* AIMessageChunk {
|
|
308
|
+
* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs",
|
|
309
|
+
* "content": ""
|
|
310
|
+
* }
|
|
311
|
+
* AIMessageChunk {
|
|
312
|
+
* "content": "J"
|
|
313
|
+
* }
|
|
314
|
+
* AIMessageChunk {
|
|
315
|
+
* "content": "'adore"
|
|
316
|
+
* }
|
|
317
|
+
* AIMessageChunk {
|
|
318
|
+
* "content": " la"
|
|
319
|
+
* }
|
|
320
|
+
* AIMessageChunk {
|
|
321
|
+
* "content": " programmation",,
|
|
322
|
+
* }
|
|
323
|
+
* AIMessageChunk {
|
|
324
|
+
* "content": ".",,
|
|
325
|
+
* }
|
|
326
|
+
* AIMessageChunk {
|
|
327
|
+
* "content": "",
|
|
328
|
+
* "response_metadata": {
|
|
329
|
+
* "finish_reason": "stop",
|
|
330
|
+
* "system_fingerprint": "fp_c9aa9c0491"
|
|
331
|
+
* },
|
|
332
|
+
* }
|
|
333
|
+
* AIMessageChunk {
|
|
334
|
+
* "content": "",
|
|
335
|
+
* "usage_metadata": {
|
|
336
|
+
* "input_tokens": 28,
|
|
337
|
+
* "output_tokens": 5,
|
|
338
|
+
* "total_tokens": 33
|
|
339
|
+
* }
|
|
340
|
+
* }
|
|
341
|
+
* ```
|
|
342
|
+
* </details>
|
|
343
|
+
*
|
|
344
|
+
* <br />
|
|
345
|
+
*
|
|
346
|
+
* <details>
|
|
347
|
+
* <summary><strong>Aggregate Streamed Chunks</strong></summary>
|
|
348
|
+
*
|
|
349
|
+
* ```typescript
|
|
350
|
+
* import { AIMessageChunk } from '@langchain/core/messages';
|
|
351
|
+
* import { concat } from '@langchain/core/utils/stream';
|
|
227
352
|
*
|
|
228
|
-
*
|
|
229
|
-
*
|
|
353
|
+
* const stream = await llm.stream(input);
|
|
354
|
+
* let full: AIMessageChunk | undefined;
|
|
355
|
+
* for await (const chunk of stream) {
|
|
356
|
+
* full = !full ? chunk : concat(full, chunk);
|
|
357
|
+
* }
|
|
358
|
+
* console.log(full);
|
|
359
|
+
* ```
|
|
360
|
+
*
|
|
361
|
+
* ```txt
|
|
362
|
+
* AIMessageChunk {
|
|
363
|
+
* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu",
|
|
364
|
+
* "content": "J'adore la programmation.",
|
|
365
|
+
* "response_metadata": {
|
|
366
|
+
* "prompt": 0,
|
|
367
|
+
* "completion": 0,
|
|
368
|
+
* "finish_reason": "stop",
|
|
369
|
+
* },
|
|
370
|
+
* "usage_metadata": {
|
|
371
|
+
* "input_tokens": 28,
|
|
372
|
+
* "output_tokens": 5,
|
|
373
|
+
* "total_tokens": 33
|
|
374
|
+
* }
|
|
375
|
+
* }
|
|
376
|
+
* ```
|
|
377
|
+
* </details>
|
|
378
|
+
*
|
|
379
|
+
* <br />
|
|
380
|
+
*
|
|
381
|
+
* <details>
|
|
382
|
+
* <summary><strong>Bind tools</strong></summary>
|
|
383
|
+
*
|
|
384
|
+
* ```typescript
|
|
385
|
+
* import { z } from 'zod';
|
|
386
|
+
*
|
|
387
|
+
* const GetWeather = {
|
|
388
|
+
* name: "GetWeather",
|
|
389
|
+
* description: "Get the current weather in a given location",
|
|
390
|
+
* schema: z.object({
|
|
391
|
+
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
392
|
+
* }),
|
|
393
|
+
* }
|
|
394
|
+
*
|
|
395
|
+
* const GetPopulation = {
|
|
396
|
+
* name: "GetPopulation",
|
|
397
|
+
* description: "Get the current population in a given location",
|
|
398
|
+
* schema: z.object({
|
|
399
|
+
* location: z.string().describe("The city and state, e.g. San Francisco, CA")
|
|
400
|
+
* }),
|
|
401
|
+
* }
|
|
402
|
+
*
|
|
403
|
+
* const llmWithTools = llm.bindTools(
|
|
404
|
+
* [GetWeather, GetPopulation],
|
|
405
|
+
* {
|
|
406
|
+
* // strict: true // enforce tool args schema is respected
|
|
407
|
+
* }
|
|
408
|
+
* );
|
|
409
|
+
* const aiMsg = await llmWithTools.invoke(
|
|
410
|
+
* "Which city is hotter today and which is bigger: LA or NY?"
|
|
411
|
+
* );
|
|
412
|
+
* console.log(aiMsg.tool_calls);
|
|
413
|
+
* ```
|
|
414
|
+
*
|
|
415
|
+
* ```txt
|
|
416
|
+
* [
|
|
417
|
+
* {
|
|
418
|
+
* name: 'GetWeather',
|
|
419
|
+
* args: { location: 'Los Angeles, CA' },
|
|
420
|
+
* type: 'tool_call',
|
|
421
|
+
* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK'
|
|
422
|
+
* },
|
|
423
|
+
* {
|
|
424
|
+
* name: 'GetWeather',
|
|
425
|
+
* args: { location: 'New York, NY' },
|
|
426
|
+
* type: 'tool_call',
|
|
427
|
+
* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX'
|
|
428
|
+
* },
|
|
429
|
+
* {
|
|
430
|
+
* name: 'GetPopulation',
|
|
431
|
+
* args: { location: 'Los Angeles, CA' },
|
|
432
|
+
* type: 'tool_call',
|
|
433
|
+
* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14'
|
|
434
|
+
* },
|
|
435
|
+
* {
|
|
436
|
+
* name: 'GetPopulation',
|
|
437
|
+
* args: { location: 'New York, NY' },
|
|
438
|
+
* type: 'tool_call',
|
|
439
|
+
* id: 'call_s9KQB1UWj45LLGaEnjz0179q'
|
|
440
|
+
* }
|
|
441
|
+
* ]
|
|
442
|
+
* ```
|
|
443
|
+
* </details>
|
|
444
|
+
*
|
|
445
|
+
* <br />
|
|
446
|
+
*
|
|
447
|
+
* <details>
|
|
448
|
+
* <summary><strong>Structured Output</strong></summary>
|
|
449
|
+
*
|
|
450
|
+
* ```typescript
|
|
451
|
+
* import { z } from 'zod';
|
|
452
|
+
*
|
|
453
|
+
* const Joke = z.object({
|
|
454
|
+
* setup: z.string().describe("The setup of the joke"),
|
|
455
|
+
* punchline: z.string().describe("The punchline to the joke"),
|
|
456
|
+
* rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
|
|
457
|
+
* }).describe('Joke to tell user.');
|
|
230
458
|
*
|
|
231
|
-
*
|
|
232
|
-
*
|
|
459
|
+
* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
|
|
460
|
+
* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
|
|
461
|
+
* console.log(jokeResult);
|
|
462
|
+
* ```
|
|
463
|
+
*
|
|
464
|
+
* ```txt
|
|
465
|
+
* {
|
|
466
|
+
* setup: 'Why was the cat sitting on the computer?',
|
|
467
|
+
* punchline: 'Because it wanted to keep an eye on the mouse!',
|
|
468
|
+
* rating: 7
|
|
469
|
+
* }
|
|
470
|
+
* ```
|
|
471
|
+
* </details>
|
|
472
|
+
*
|
|
473
|
+
* <br />
|
|
474
|
+
*
|
|
475
|
+
* <details>
|
|
476
|
+
* <summary><strong>JSON Object Response Format</strong></summary>
|
|
477
|
+
*
|
|
478
|
+
* ```typescript
|
|
479
|
+
* const jsonLlm = llm.bind({ response_format: { type: "json_object" } });
|
|
480
|
+
* const jsonLlmAiMsg = await jsonLlm.invoke(
|
|
481
|
+
* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]"
|
|
482
|
+
* );
|
|
483
|
+
* console.log(jsonLlmAiMsg.content);
|
|
484
|
+
* ```
|
|
485
|
+
*
|
|
486
|
+
* ```txt
|
|
487
|
+
* {
|
|
488
|
+
* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67]
|
|
489
|
+
* }
|
|
490
|
+
* ```
|
|
491
|
+
* </details>
|
|
492
|
+
*
|
|
493
|
+
* <br />
|
|
494
|
+
*
|
|
495
|
+
* <details>
|
|
496
|
+
* <summary><strong>Multimodal</strong></summary>
|
|
497
|
+
*
|
|
498
|
+
* ```typescript
|
|
499
|
+
* import { HumanMessage } from '@langchain/core/messages';
|
|
500
|
+
*
|
|
501
|
+
* const imageUrl = "https://example.com/image.jpg";
|
|
502
|
+
* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
|
|
503
|
+
* const base64Image = Buffer.from(imageData).toString('base64');
|
|
504
|
+
*
|
|
505
|
+
* const message = new HumanMessage({
|
|
506
|
+
* content: [
|
|
507
|
+
* { type: "text", text: "describe the weather in this image" },
|
|
508
|
+
* {
|
|
509
|
+
* type: "image_url",
|
|
510
|
+
* image_url: { url: `data:image/jpeg;base64,${base64Image}` },
|
|
511
|
+
* },
|
|
512
|
+
* ]
|
|
513
|
+
* });
|
|
233
514
|
*
|
|
515
|
+
* const imageDescriptionAiMsg = await llm.invoke([message]);
|
|
516
|
+
* console.log(imageDescriptionAiMsg.content);
|
|
234
517
|
* ```
|
|
518
|
+
*
|
|
519
|
+
* ```txt
|
|
520
|
+
* 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.
|
|
521
|
+
* ```
|
|
522
|
+
* </details>
|
|
523
|
+
*
|
|
524
|
+
* <br />
|
|
525
|
+
*
|
|
526
|
+
* <details>
|
|
527
|
+
* <summary><strong>Usage Metadata</strong></summary>
|
|
528
|
+
*
|
|
529
|
+
* ```typescript
|
|
530
|
+
* const aiMsgForMetadata = await llm.invoke(input);
|
|
531
|
+
* console.log(aiMsgForMetadata.usage_metadata);
|
|
532
|
+
* ```
|
|
533
|
+
*
|
|
534
|
+
* ```txt
|
|
535
|
+
* { input_tokens: 28, output_tokens: 5, total_tokens: 33 }
|
|
536
|
+
* ```
|
|
537
|
+
* </details>
|
|
538
|
+
*
|
|
539
|
+
* <br />
|
|
540
|
+
*
|
|
541
|
+
* <details>
|
|
542
|
+
* <summary><strong>Logprobs</strong></summary>
|
|
543
|
+
*
|
|
544
|
+
* ```typescript
|
|
545
|
+
* const logprobsLlm = new ChatOpenAI({ logprobs: true });
|
|
546
|
+
* const aiMsgForLogprobs = await logprobsLlm.invoke(input);
|
|
547
|
+
* console.log(aiMsgForLogprobs.response_metadata.logprobs);
|
|
548
|
+
* ```
|
|
549
|
+
*
|
|
550
|
+
* ```txt
|
|
551
|
+
* {
|
|
552
|
+
* content: [
|
|
553
|
+
* {
|
|
554
|
+
* token: 'J',
|
|
555
|
+
* logprob: -0.000050616763,
|
|
556
|
+
* bytes: [Array],
|
|
557
|
+
* top_logprobs: []
|
|
558
|
+
* },
|
|
559
|
+
* {
|
|
560
|
+
* token: "'",
|
|
561
|
+
* logprob: -0.01868736,
|
|
562
|
+
* bytes: [Array],
|
|
563
|
+
* top_logprobs: []
|
|
564
|
+
* },
|
|
565
|
+
* {
|
|
566
|
+
* token: 'ad',
|
|
567
|
+
* logprob: -0.0000030545007,
|
|
568
|
+
* bytes: [Array],
|
|
569
|
+
* top_logprobs: []
|
|
570
|
+
* },
|
|
571
|
+
* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
572
|
+
* {
|
|
573
|
+
* token: ' la',
|
|
574
|
+
* logprob: -0.515404,
|
|
575
|
+
* bytes: [Array],
|
|
576
|
+
* top_logprobs: []
|
|
577
|
+
* },
|
|
578
|
+
* {
|
|
579
|
+
* token: ' programm',
|
|
580
|
+
* logprob: -0.0000118755715,
|
|
581
|
+
* bytes: [Array],
|
|
582
|
+
* top_logprobs: []
|
|
583
|
+
* },
|
|
584
|
+
* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] },
|
|
585
|
+
* {
|
|
586
|
+
* token: '.',
|
|
587
|
+
* logprob: -0.0000037697225,
|
|
588
|
+
* bytes: [Array],
|
|
589
|
+
* top_logprobs: []
|
|
590
|
+
* }
|
|
591
|
+
* ],
|
|
592
|
+
* refusal: null
|
|
593
|
+
* }
|
|
594
|
+
* ```
|
|
595
|
+
* </details>
|
|
596
|
+
*
|
|
597
|
+
* <br />
|
|
598
|
+
*
|
|
599
|
+
* <details>
|
|
600
|
+
* <summary><strong>Response Metadata</strong></summary>
|
|
601
|
+
*
|
|
602
|
+
* ```typescript
|
|
603
|
+
* const aiMsgForResponseMetadata = await llm.invoke(input);
|
|
604
|
+
* console.log(aiMsgForResponseMetadata.response_metadata);
|
|
605
|
+
* ```
|
|
606
|
+
*
|
|
607
|
+
* ```txt
|
|
608
|
+
* {
|
|
609
|
+
* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 },
|
|
610
|
+
* finish_reason: 'stop',
|
|
611
|
+
* system_fingerprint: 'fp_3aa7262c27'
|
|
612
|
+
* }
|
|
613
|
+
* ```
|
|
614
|
+
* </details>
|
|
615
|
+
*
|
|
616
|
+
* <br />
|
|
617
|
+
*
|
|
618
|
+
* <details>
|
|
619
|
+
* <summary><strong>JSON Schema Structured Output</strong></summary>
|
|
620
|
+
*
|
|
621
|
+
* ```typescript
|
|
622
|
+
* const llmForJsonSchema = new ChatOpenAI({
|
|
623
|
+
* model: "gpt-4o-2024-08-06",
|
|
624
|
+
* }).withStructuredOutput(
|
|
625
|
+
* z.object({
|
|
626
|
+
* command: z.string().describe("The command to execute"),
|
|
627
|
+
* expectedOutput: z.string().describe("The expected output of the command"),
|
|
628
|
+
* options: z
|
|
629
|
+
* .array(z.string())
|
|
630
|
+
* .describe("The options you can pass to the command"),
|
|
631
|
+
* }),
|
|
632
|
+
* {
|
|
633
|
+
* method: "jsonSchema",
|
|
634
|
+
* strict: true, // Optional when using the `jsonSchema` method
|
|
635
|
+
* }
|
|
636
|
+
* );
|
|
637
|
+
*
|
|
638
|
+
* const jsonSchemaRes = await llmForJsonSchema.invoke(
|
|
639
|
+
* "What is the command to list files in a directory?"
|
|
640
|
+
* );
|
|
641
|
+
* console.log(jsonSchemaRes);
|
|
642
|
+
* ```
|
|
643
|
+
*
|
|
644
|
+
* ```txt
|
|
645
|
+
* {
|
|
646
|
+
* command: 'ls',
|
|
647
|
+
* expectedOutput: 'A list of files and subdirectories within the specified directory.',
|
|
648
|
+
* options: [
|
|
649
|
+
* '-a: include directory entries whose names begin with a dot (.).',
|
|
650
|
+
* '-l: use a long listing format.',
|
|
651
|
+
* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).',
|
|
652
|
+
* '-t: sort by time, newest first.',
|
|
653
|
+
* '-r: reverse order while sorting.',
|
|
654
|
+
* '-S: sort by file size, largest first.',
|
|
655
|
+
* '-R: list subdirectories recursively.'
|
|
656
|
+
* ]
|
|
657
|
+
* }
|
|
658
|
+
* ```
|
|
659
|
+
* </details>
|
|
660
|
+
*
|
|
661
|
+
* <br />
|
|
235
662
|
*/
|
|
236
663
|
class ChatOpenAI extends chat_models_1.BaseChatModel {
|
|
237
664
|
static lc_name() {
|
|
@@ -571,6 +998,17 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
|
|
|
571
998
|
...kwargs,
|
|
572
999
|
});
|
|
573
1000
|
}
|
|
1001
|
+
createResponseFormat(resFormat) {
|
|
1002
|
+
if (resFormat &&
|
|
1003
|
+
resFormat.type === "json_schema" &&
|
|
1004
|
+
resFormat.json_schema.schema &&
|
|
1005
|
+
isZodSchema(resFormat.json_schema.schema)) {
|
|
1006
|
+
return (0, zod_1.zodResponseFormat)(resFormat.json_schema.schema, resFormat.json_schema.name, {
|
|
1007
|
+
description: resFormat.json_schema.description,
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
return resFormat;
|
|
1011
|
+
}
|
|
574
1012
|
/**
|
|
575
1013
|
* Get the parameters used to invoke the model
|
|
576
1014
|
*/
|
|
@@ -610,7 +1048,7 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
|
|
|
610
1048
|
? options.tools.map((tool) => _convertChatOpenAIToolTypeToOpenAITool(tool, { strict }))
|
|
611
1049
|
: undefined,
|
|
612
1050
|
tool_choice: (0, openai_js_1.formatToOpenAIToolChoice)(options?.tool_choice),
|
|
613
|
-
response_format: options?.response_format,
|
|
1051
|
+
response_format: this.createResponseFormat(options?.response_format),
|
|
614
1052
|
seed: options?.seed,
|
|
615
1053
|
...streamOptionsConfig,
|
|
616
1054
|
parallel_tool_calls: options?.parallel_tool_calls,
|
|
@@ -636,6 +1074,20 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
|
|
|
636
1074
|
stream: true,
|
|
637
1075
|
};
|
|
638
1076
|
let defaultRole;
|
|
1077
|
+
if (params.response_format &&
|
|
1078
|
+
params.response_format.type === "json_schema") {
|
|
1079
|
+
console.warn(`OpenAI does not yet support streaming with "response_format" set to "json_schema". Falling back to non-streaming mode.`);
|
|
1080
|
+
const res = await this._generate(messages, options, runManager);
|
|
1081
|
+
const chunk = new outputs_1.ChatGenerationChunk({
|
|
1082
|
+
message: new messages_1.AIMessageChunk({
|
|
1083
|
+
...res.generations[0].message,
|
|
1084
|
+
}),
|
|
1085
|
+
text: res.generations[0].text,
|
|
1086
|
+
generationInfo: res.generations[0].generationInfo,
|
|
1087
|
+
});
|
|
1088
|
+
yield chunk;
|
|
1089
|
+
return runManager?.handleLLMNewToken(res.generations[0].text ?? "", undefined, undefined, undefined, undefined, { chunk });
|
|
1090
|
+
}
|
|
639
1091
|
const streamIterable = await this.completionWithRetry(params, options);
|
|
640
1092
|
let usage;
|
|
641
1093
|
for await (const data of streamIterable) {
|
|
@@ -662,7 +1114,7 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
|
|
|
662
1114
|
}
|
|
663
1115
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
664
1116
|
const generationInfo = { ...newTokenIndices };
|
|
665
|
-
if (choice.finish_reason
|
|
1117
|
+
if (choice.finish_reason != null) {
|
|
666
1118
|
generationInfo.finish_reason = choice.finish_reason;
|
|
667
1119
|
// Only include system fingerprint in the last chunk for now
|
|
668
1120
|
// to avoid concatenation issues
|
|
@@ -739,14 +1191,28 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
|
|
|
739
1191
|
return { generations, llmOutput: { estimatedTokenUsage: tokenUsage } };
|
|
740
1192
|
}
|
|
741
1193
|
else {
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
1194
|
+
let data;
|
|
1195
|
+
if (options.response_format &&
|
|
1196
|
+
options.response_format.type === "json_schema") {
|
|
1197
|
+
data = await this.betaParsedCompletionWithRetry({
|
|
1198
|
+
...params,
|
|
1199
|
+
stream: false,
|
|
1200
|
+
messages: messagesMapped,
|
|
1201
|
+
}, {
|
|
1202
|
+
signal: options?.signal,
|
|
1203
|
+
...options?.options,
|
|
1204
|
+
});
|
|
1205
|
+
}
|
|
1206
|
+
else {
|
|
1207
|
+
data = await this.completionWithRetry({
|
|
1208
|
+
...params,
|
|
1209
|
+
stream: false,
|
|
1210
|
+
messages: messagesMapped,
|
|
1211
|
+
}, {
|
|
1212
|
+
signal: options?.signal,
|
|
1213
|
+
...options?.options,
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
750
1216
|
const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data?.usage ?? {};
|
|
751
1217
|
if (completionTokens) {
|
|
752
1218
|
tokenUsage.completionTokens =
|
|
@@ -891,6 +1357,25 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
|
|
|
891
1357
|
}
|
|
892
1358
|
});
|
|
893
1359
|
}
|
|
1360
|
+
/**
|
|
1361
|
+
* Call the beta chat completions parse endpoint. This should only be called if
|
|
1362
|
+
* response_format is set to "json_object".
|
|
1363
|
+
* @param {OpenAIClient.Chat.ChatCompletionCreateParamsNonStreaming} request
|
|
1364
|
+
* @param {OpenAICoreRequestOptions | undefined} options
|
|
1365
|
+
*/
|
|
1366
|
+
async betaParsedCompletionWithRetry(request, options) {
|
|
1367
|
+
const requestOptions = this._getClientOptions(options);
|
|
1368
|
+
return this.caller.call(async () => {
|
|
1369
|
+
try {
|
|
1370
|
+
const res = await this.client.beta.chat.completions.parse(request, requestOptions);
|
|
1371
|
+
return res;
|
|
1372
|
+
}
|
|
1373
|
+
catch (e) {
|
|
1374
|
+
const error = (0, openai_js_1.wrapOpenAIClientError)(e);
|
|
1375
|
+
throw error;
|
|
1376
|
+
}
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
894
1379
|
_getClientOptions(options) {
|
|
895
1380
|
if (!this.client) {
|
|
896
1381
|
const openAIEndpointConfig = {
|
|
@@ -983,6 +1468,25 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
|
|
|
983
1468
|
outputParser = new output_parsers_1.JsonOutputParser();
|
|
984
1469
|
}
|
|
985
1470
|
}
|
|
1471
|
+
else if (method === "jsonSchema") {
|
|
1472
|
+
llm = this.bind({
|
|
1473
|
+
response_format: {
|
|
1474
|
+
type: "json_schema",
|
|
1475
|
+
json_schema: {
|
|
1476
|
+
name: name ?? "extract",
|
|
1477
|
+
description: schema.description,
|
|
1478
|
+
schema,
|
|
1479
|
+
strict: config?.strict,
|
|
1480
|
+
},
|
|
1481
|
+
},
|
|
1482
|
+
});
|
|
1483
|
+
if (isZodSchema(schema)) {
|
|
1484
|
+
outputParser = output_parsers_1.StructuredOutputParser.fromZodSchema(schema);
|
|
1485
|
+
}
|
|
1486
|
+
else {
|
|
1487
|
+
outputParser = new output_parsers_1.JsonOutputParser();
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
986
1490
|
else {
|
|
987
1491
|
let functionName = name ?? "extract";
|
|
988
1492
|
// Is function calling
|