@langchain/openai 0.5.13 → 0.5.15

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.
@@ -10,7 +10,7 @@ import { JsonOutputParser, StructuredOutputParser, } from "@langchain/core/outpu
10
10
  import { JsonOutputKeyToolsParser, convertLangChainToolCallToOpenAI, makeInvalidToolCall, parseToolCall, } from "@langchain/core/output_parsers/openai_tools";
11
11
  import { zodResponseFormat } from "openai/helpers/zod";
12
12
  import { getSchemaDescription, isInteropZodSchema, isZodSchemaV3, isZodSchemaV4, } from "@langchain/core/utils/types";
13
- import { toJsonSchema } from "@langchain/core/utils/json_schema";
13
+ import { toJsonSchema, } from "@langchain/core/utils/json_schema";
14
14
  import { getEndpoint } from "./utils/azure.js";
15
15
  import { formatToOpenAIToolChoice, wrapOpenAIClientError, } from "./utils/openai.js";
16
16
  import { formatFunctionDefinitions, } from "./utils/openai-format-fndef.js";
@@ -136,7 +136,7 @@ const completionsApiContentBlockConverter = {
136
136
  return {
137
137
  type: "file",
138
138
  file: {
139
- file_data: block.url,
139
+ file_data: block.url, // formatted as base64 data URL
140
140
  ...(block.metadata?.filename || block.metadata?.name
141
141
  ? {
142
142
  filename: (block.metadata?.filename ||
@@ -249,12 +249,8 @@ function _convertReasoningSummaryToOpenAIResponsesParams(reasoning) {
249
249
  };
250
250
  }
251
251
  function _convertMessagesToOpenAIResponsesParams(messages, model, zdrEnabled) {
252
- const lastAIMessage = messages.filter((m) => isAIMessage(m)).pop();
253
- const lastAIMessageId = lastAIMessage?.response_metadata?.id;
254
- const newMessages = lastAIMessageId && lastAIMessageId.startsWith("resp_") && !zdrEnabled
255
- ? messages.slice(messages.indexOf(lastAIMessage) + 1)
256
- : messages;
257
- return newMessages.flatMap((lcMsg) => {
252
+ return messages.flatMap((lcMsg) => {
253
+ const additional_kwargs = lcMsg.additional_kwargs;
258
254
  let role = messageToOpenAIRole(lcMsg);
259
255
  if (role === "system" && isReasoningModel(model))
260
256
  role = "developer";
@@ -264,7 +260,7 @@ function _convertMessagesToOpenAIResponsesParams(messages, model, zdrEnabled) {
264
260
  if (role === "tool") {
265
261
  const toolMessage = lcMsg;
266
262
  // Handle computer call output
267
- if (toolMessage.additional_kwargs?.type === "computer_call_output") {
263
+ if (additional_kwargs?.type === "computer_call_output") {
268
264
  const output = (() => {
269
265
  if (typeof toolMessage.content === "string") {
270
266
  return {
@@ -315,25 +311,19 @@ function _convertMessagesToOpenAIResponsesParams(messages, model, zdrEnabled) {
315
311
  // otherwise, try to reconstruct the response from what we have
316
312
  const input = [];
317
313
  // reasoning items
318
- if (!zdrEnabled && lcMsg.additional_kwargs.reasoning != null) {
319
- const isReasoningItem = (item) => typeof item === "object" &&
320
- item != null &&
321
- "type" in item &&
322
- item.type === "reasoning";
323
- if (isReasoningItem(lcMsg.additional_kwargs.reasoning)) {
324
- const reasoningItem = _convertReasoningSummaryToOpenAIResponsesParams(lcMsg.additional_kwargs.reasoning);
325
- input.push(reasoningItem);
326
- }
314
+ if (additional_kwargs?.reasoning && !zdrEnabled) {
315
+ const reasoningItem = _convertReasoningSummaryToOpenAIResponsesParams(additional_kwargs.reasoning);
316
+ input.push(reasoningItem);
327
317
  }
328
318
  // ai content
329
319
  let { content } = lcMsg;
330
- if (lcMsg.additional_kwargs.refusal != null) {
320
+ if (additional_kwargs?.refusal) {
331
321
  if (typeof content === "string") {
332
322
  content = [{ type: "output_text", text: content, annotations: [] }];
333
323
  }
334
324
  content = [
335
325
  ...content,
336
- { type: "refusal", refusal: lcMsg.additional_kwargs.refusal },
326
+ { type: "refusal", refusal: additional_kwargs.refusal },
337
327
  ];
338
328
  }
339
329
  input.push({
@@ -357,10 +347,7 @@ function _convertMessagesToOpenAIResponsesParams(messages, model, zdrEnabled) {
357
347
  return [];
358
348
  }),
359
349
  });
360
- // function tool calls and computer use tool calls
361
- const functionCallIds =
362
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
363
- lcMsg.additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY];
350
+ const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];
364
351
  if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) {
365
352
  input.push(...lcMsg.tool_calls.map((toolCall) => ({
366
353
  type: "function_call",
@@ -370,44 +357,64 @@ function _convertMessagesToOpenAIResponsesParams(messages, model, zdrEnabled) {
370
357
  ...(zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),
371
358
  })));
372
359
  }
373
- else if (lcMsg.additional_kwargs.tool_calls != null) {
374
- input.push(...lcMsg.additional_kwargs.tool_calls.map((toolCall) => ({
360
+ else if (additional_kwargs?.tool_calls) {
361
+ input.push(...additional_kwargs.tool_calls.map((toolCall) => ({
375
362
  type: "function_call",
376
363
  name: toolCall.function.name,
377
364
  call_id: toolCall.id,
378
- ...(zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),
379
365
  arguments: toolCall.function.arguments,
366
+ ...(zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),
380
367
  })));
381
368
  }
382
369
  const toolOutputs = lcMsg.response_metadata.output?.length
383
370
  ? lcMsg.response_metadata.output
384
- : lcMsg.additional_kwargs.tool_outputs;
385
- let computerCalls = [];
371
+ : additional_kwargs.tool_outputs;
372
+ const fallthroughCallTypes = [
373
+ "computer_call",
374
+ "mcp_call",
375
+ "code_interpreter_call",
376
+ "image_generation_call",
377
+ ];
386
378
  if (toolOutputs != null) {
387
379
  const castToolOutputs = toolOutputs;
388
- computerCalls = castToolOutputs?.filter((item) => item.type === "computer_call");
389
- if (computerCalls.length > 0)
390
- input.push(...computerCalls);
380
+ const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type));
381
+ if (fallthroughCalls.length > 0)
382
+ input.push(...fallthroughCalls);
391
383
  }
392
384
  return input;
393
385
  }
394
- const content = typeof lcMsg.content === "string"
395
- ? lcMsg.content
396
- : lcMsg.content.flatMap((item) => {
386
+ if (role === "user" || role === "system" || role === "developer") {
387
+ if (typeof lcMsg.content === "string") {
388
+ return { type: "message", role, content: lcMsg.content };
389
+ }
390
+ const messages = [];
391
+ const content = lcMsg.content.flatMap((item) => {
392
+ if (item.type === "mcp_approval_response") {
393
+ messages.push({
394
+ type: "mcp_approval_response",
395
+ approval_request_id: item.approval_request_id,
396
+ approve: item.approve,
397
+ });
398
+ }
397
399
  if (isDataContentBlock(item)) {
398
400
  return convertToProviderContentBlock(item, completionsApiContentBlockConverter);
399
401
  }
400
402
  if (item.type === "text") {
401
- return { type: "input_text", text: item.text };
403
+ return {
404
+ type: "input_text",
405
+ text: item.text,
406
+ };
402
407
  }
403
408
  if (item.type === "image_url") {
404
- const image_url = typeof item.image_url === "string"
405
- ? item.image_url
406
- : item.image_url.url;
407
- const detail = typeof item.image_url === "string"
408
- ? "auto"
409
- : item.image_url.detail;
410
- return { type: "input_image", image_url, detail };
409
+ return {
410
+ type: "input_image",
411
+ image_url: typeof item.image_url === "string"
412
+ ? item.image_url
413
+ : item.image_url.url,
414
+ detail: typeof item.image_url === "string"
415
+ ? "auto"
416
+ : item.image_url.detail,
417
+ };
411
418
  }
412
419
  if (item.type === "input_text" ||
413
420
  item.type === "input_image" ||
@@ -416,8 +423,10 @@ function _convertMessagesToOpenAIResponsesParams(messages, model, zdrEnabled) {
416
423
  }
417
424
  return [];
418
425
  });
419
- if (role === "user" || role === "system" || role === "developer") {
420
- return { type: "message", role, content };
426
+ if (content.length > 0) {
427
+ messages.push({ type: "message", role, content });
428
+ }
429
+ return messages;
421
430
  }
422
431
  console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`);
423
432
  return [];
@@ -524,7 +533,7 @@ function _convertOpenAIResponsesDeltaToBaseMessageChunk(chunk) {
524
533
  index: chunk.content_index,
525
534
  });
526
535
  }
527
- else if (chunk.type === "response.output_text.annotation.added") {
536
+ else if (chunk.type === "response.output_text_annotation.added") {
528
537
  content.push({
529
538
  type: "text",
530
539
  text: "",
@@ -550,9 +559,16 @@ function _convertOpenAIResponsesDeltaToBaseMessageChunk(chunk) {
550
559
  };
551
560
  }
552
561
  else if (chunk.type === "response.output_item.done" &&
553
- (chunk.item.type === "web_search_call" ||
554
- chunk.item.type === "file_search_call" ||
555
- chunk.item.type === "computer_call")) {
562
+ [
563
+ "web_search_call",
564
+ "file_search_call",
565
+ "computer_call",
566
+ "code_interpreter_call",
567
+ "mcp_call",
568
+ "mcp_list_tools",
569
+ "mcp_approval_request",
570
+ "image_generation_call",
571
+ ].includes(chunk.item.type)) {
556
572
  additional_kwargs.tool_outputs = [chunk.item];
557
573
  }
558
574
  else if (chunk.type === "response.created") {
@@ -624,6 +640,11 @@ function _convertOpenAIResponsesDeltaToBaseMessageChunk(chunk) {
624
640
  ],
625
641
  };
626
642
  }
643
+ else if (chunk.type === "response.image_generation_call.partial_image") {
644
+ // noop/fixme: retaining partial images in a message chunk means that _all_
645
+ // partial images get kept in history, so we don't do anything here.
646
+ return null;
647
+ }
627
648
  else {
628
649
  return null;
629
650
  }
@@ -650,6 +671,29 @@ function isBuiltInToolChoice(tool_choice) {
650
671
  "type" in tool_choice &&
651
672
  tool_choice.type !== "function");
652
673
  }
674
+ function _reduceChatOpenAIToolsForResponses(tools, fields) {
675
+ const reducedTools = [];
676
+ for (const tool of tools) {
677
+ if (isBuiltInTool(tool)) {
678
+ if (tool.type === "image_generation" && fields?.stream) {
679
+ // OpenAI sends a 400 error if partial_images is not set and we want to stream.
680
+ // We also set it to 1 since we don't support partial images yet.
681
+ tool.partial_images = 1;
682
+ }
683
+ reducedTools.push(tool);
684
+ }
685
+ else if (isOpenAITool(tool)) {
686
+ reducedTools.push({
687
+ type: "function",
688
+ name: tool.function.name,
689
+ parameters: tool.function.parameters,
690
+ description: tool.function.description,
691
+ strict: fields?.strict ?? null,
692
+ });
693
+ }
694
+ }
695
+ return reducedTools;
696
+ }
653
697
  function _convertChatOpenAIToolTypeToOpenAITool(tool, fields) {
654
698
  if (isOpenAITool(tool)) {
655
699
  if (fields?.strict !== undefined) {
@@ -1643,25 +1687,10 @@ export class ChatOpenAI extends BaseChatModel {
1643
1687
  truncation: options?.truncation,
1644
1688
  include: options?.include,
1645
1689
  tools: options?.tools?.length
1646
- ? options.tools
1647
- .map((tool) => {
1648
- if (isBuiltInTool(tool)) {
1649
- return tool;
1650
- }
1651
- else if (isOpenAITool(tool)) {
1652
- return {
1653
- type: "function",
1654
- name: tool.function.name,
1655
- parameters: tool.function.parameters,
1656
- description: tool.function.description,
1657
- strict,
1658
- };
1659
- }
1660
- else {
1661
- return null;
1662
- }
1690
+ ? _reduceChatOpenAIToolsForResponses(options.tools, {
1691
+ stream: this.streaming,
1692
+ strict,
1663
1693
  })
1664
- .filter((tool) => tool !== null)
1665
1694
  : undefined,
1666
1695
  tool_choice: isBuiltInToolChoice(options?.tool_choice)
1667
1696
  ? options?.tool_choice
@@ -1904,17 +1933,10 @@ export class ChatOpenAI extends BaseChatModel {
1904
1933
  }
1905
1934
  async *_streamResponseChunks(messages, options, runManager) {
1906
1935
  if (this._useResponseApi(options)) {
1907
- const lastAIMessage = messages.filter((m) => isAIMessage(m)).pop();
1908
- const lastAIMessageId = lastAIMessage?.response_metadata?.id;
1909
1936
  const streamIterable = await this.responseApiWithRetry({
1910
1937
  ...this.invocationParams(options, { streaming: true }),
1911
1938
  input: _convertMessagesToOpenAIResponsesParams(messages, this.model, this.zdrEnabled),
1912
1939
  stream: true,
1913
- ...(lastAIMessageId &&
1914
- lastAIMessageId.startsWith("resp_") &&
1915
- !this.zdrEnabled
1916
- ? { previous_response_id: lastAIMessageId }
1917
- : {}),
1918
1940
  }, options);
1919
1941
  for await (const data of streamIterable) {
1920
1942
  const chunk = _convertOpenAIResponsesDeltaToBaseMessageChunk(data);
@@ -2048,17 +2070,10 @@ export class ChatOpenAI extends BaseChatModel {
2048
2070
  },
2049
2071
  };
2050
2072
  }
2051
- const lastAIMessage = messages.filter((m) => isAIMessage(m)).pop();
2052
- const lastAIMessageId = lastAIMessage?.response_metadata?.id;
2053
2073
  const input = _convertMessagesToOpenAIResponsesParams(messages, this.model, this.zdrEnabled);
2054
2074
  const data = await this.responseApiWithRetry({
2055
2075
  input,
2056
2076
  ...invocationParams,
2057
- ...(lastAIMessageId &&
2058
- lastAIMessageId.startsWith("resp_") &&
2059
- !this.zdrEnabled
2060
- ? { previous_response_id: lastAIMessageId }
2061
- : {}),
2062
2077
  }, { signal: options?.signal, ...options?.options });
2063
2078
  return {
2064
2079
  generations: [
@@ -2368,7 +2383,7 @@ export class ChatOpenAI extends BaseChatModel {
2368
2383
  const requestOptions = this._getClientOptions(options);
2369
2384
  return this.caller.call(async () => {
2370
2385
  try {
2371
- const res = await this.client.beta.chat.completions.parse(request, requestOptions);
2386
+ const res = await this.client.chat.completions.parse(request, requestOptions);
2372
2387
  return res;
2373
2388
  }
2374
2389
  catch (e) {
@@ -2455,15 +2470,21 @@ export class ChatOpenAI extends BaseChatModel {
2455
2470
  console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);
2456
2471
  }
2457
2472
  if (method === "jsonMode") {
2458
- llm = this.withConfig({
2459
- response_format: { type: "json_object" },
2460
- });
2473
+ let outputFormatSchema;
2461
2474
  if (isInteropZodSchema(schema)) {
2462
2475
  outputParser = StructuredOutputParser.fromZodSchema(schema);
2476
+ outputFormatSchema = toJsonSchema(schema);
2463
2477
  }
2464
2478
  else {
2465
2479
  outputParser = new JsonOutputParser();
2466
2480
  }
2481
+ llm = this.withConfig({
2482
+ response_format: { type: "json_object" },
2483
+ ls_structured_output_format: {
2484
+ kwargs: { method: "jsonMode" },
2485
+ schema: outputFormatSchema,
2486
+ },
2487
+ });
2467
2488
  }
2468
2489
  else if (method === "jsonSchema") {
2469
2490
  llm = this.withConfig({
@@ -2476,6 +2497,10 @@ export class ChatOpenAI extends BaseChatModel {
2476
2497
  strict: config?.strict,
2477
2498
  },
2478
2499
  },
2500
+ ls_structured_output_format: {
2501
+ kwargs: { method: "jsonSchema" },
2502
+ schema: toJsonSchema(schema),
2503
+ },
2479
2504
  });
2480
2505
  if (isInteropZodSchema(schema)) {
2481
2506
  const altParser = StructuredOutputParser.fromZodSchema(schema);
@@ -2512,6 +2537,10 @@ export class ChatOpenAI extends BaseChatModel {
2512
2537
  name: functionName,
2513
2538
  },
2514
2539
  },
2540
+ ls_structured_output_format: {
2541
+ kwargs: { method: "functionCalling" },
2542
+ schema: asJsonSchema,
2543
+ },
2515
2544
  // Do not pass `strict` argument to OpenAI if `config.strict` is undefined
2516
2545
  ...(config?.strict !== undefined ? { strict: config.strict } : {}),
2517
2546
  });
@@ -2550,6 +2579,10 @@ export class ChatOpenAI extends BaseChatModel {
2550
2579
  name: functionName,
2551
2580
  },
2552
2581
  },
2582
+ ls_structured_output_format: {
2583
+ kwargs: { method: "functionCalling" },
2584
+ schema: toJsonSchema(schema),
2585
+ },
2553
2586
  // Do not pass `strict` argument to OpenAI if `config.strict` is undefined
2554
2587
  ...(config?.strict !== undefined ? { strict: config.strict } : {}),
2555
2588
  });
@@ -2610,8 +2643,8 @@ function interopZodResponseFormat(zodSchema, name, props) {
2610
2643
  name,
2611
2644
  strict: true,
2612
2645
  schema: z4.toJSONSchema(zodSchema, {
2613
- cycles: "ref",
2614
- reused: "ref",
2646
+ cycles: "ref", // equivalent to nameStrategy: 'duplicate-ref'
2647
+ reused: "ref", // equivalent to $refStrategy: 'extract-to-root'
2615
2648
  override(ctx) {
2616
2649
  ctx.jsonSchema.title = name; // equivalent to `name` property
2617
2650
  // TODO: implement `nullableStrategy` patch-fix (zod doesn't support openApi3 json schema target)
@@ -1,5 +1,9 @@
1
1
  import { type ClientOptions, OpenAI as OpenAIClient } from "openai";
2
2
  import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
3
+ /**
4
+ * @see https://platform.openai.com/docs/guides/embeddings#embedding-models
5
+ */
6
+ export type OpenAIEmbeddingModelId = OpenAIClient.EmbeddingModel | (string & NonNullable<unknown>);
3
7
  /**
4
8
  * Interface for OpenAIEmbeddings parameters. Extends EmbeddingsParams and
5
9
  * defines additional parameters specific to the OpenAIEmbeddings class.
@@ -10,9 +14,9 @@ export interface OpenAIEmbeddingsParams extends EmbeddingsParams {
10
14
  * Alias for `model`
11
15
  * @deprecated Use "model" instead.
12
16
  */
13
- modelName: string;
17
+ modelName: OpenAIEmbeddingModelId;
14
18
  /** Model name to use */
15
- model: string;
19
+ model: OpenAIEmbeddingModelId;
16
20
  /**
17
21
  * The number of dimensions the resulting output embeddings should have.
18
22
  * Only supported in `text-embedding-3` and later models.
@@ -99,6 +103,6 @@ export declare class OpenAIEmbeddings extends Embeddings implements Partial<Open
99
103
  * @returns Promise that resolves to the response from the API.
100
104
  */
101
105
  protected embeddingWithRetry(request: OpenAIClient.EmbeddingCreateParams): Promise<OpenAIClient.Embeddings.CreateEmbeddingResponse & {
102
- _request_id?: string | null | undefined;
106
+ _request_id?: string | null;
103
107
  }>;
104
108
  }
@@ -1,6 +1,10 @@
1
1
  import { OpenAI as OpenAIClient } from "openai";
2
2
  import { Tool, ToolParams } from "@langchain/core/tools";
3
3
  import { MessageContentComplex } from "@langchain/core/messages";
4
+ /**
5
+ * @see https://platform.openai.com/docs/api-reference/images/create
6
+ */
7
+ export type OpenAIImageModelId = OpenAIClient.ImageModel | (string & NonNullable<unknown>);
4
8
  /**
5
9
  * An interface for the Dall-E API Wrapper.
6
10
  */
@@ -19,14 +23,15 @@ export interface DallEAPIWrapperParams extends ToolParams {
19
23
  * Alias for `model`
20
24
  * @params "dall-e-2" | "dall-e-3"
21
25
  * @default "dall-e-3"
26
+ * @deprecated Use `model` instead.
22
27
  */
23
- modelName?: string;
28
+ modelName?: OpenAIImageModelId;
24
29
  /**
25
30
  * The model to use.
26
31
  * @params "dall-e-2" | "dall-e-3"
27
32
  * @default "dall-e-3"
28
33
  */
29
- model?: string;
34
+ model?: OpenAIImageModelId;
30
35
  /**
31
36
  * The style of the generated images. Must be one of vivid or natural.
32
37
  * Vivid causes the model to lean towards generating hyper-real and dramatic images.
package/dist/types.d.ts CHANGED
@@ -1,10 +1,13 @@
1
1
  import type { OpenAI as OpenAIClient } from "openai";
2
- import type { RequestOptions as _OpenAICoreRequestOptions } from "openai/core";
3
2
  import type { ResponseFormatText, ResponseFormatJSONObject, ResponseFormatJSONSchema } from "openai/resources/shared";
4
3
  import { TiktokenModel } from "js-tiktoken/lite";
5
4
  import type { BaseLanguageModelCallOptions } from "@langchain/core/language_models/base";
6
5
  import { InteropZodObject } from "@langchain/core/utils/types";
7
6
  export type { TiktokenModel };
7
+ /**
8
+ * @see https://platform.openai.com/docs/models
9
+ */
10
+ export type OpenAIChatModelId = OpenAIClient.ChatModel | (string & NonNullable<unknown>);
8
11
  export declare interface OpenAIBaseInput {
9
12
  /** Sampling temperature to use */
10
13
  temperature: number;
@@ -45,7 +48,7 @@ export declare interface OpenAIBaseInput {
45
48
  */
46
49
  modelName: string;
47
50
  /** Model name to use */
48
- model: string;
51
+ model: OpenAIChatModelId;
49
52
  /** Holds any additional parameters that are valid to pass to {@link
50
53
  * https://platform.openai.com/docs/api-reference/completions/create |
51
54
  * `openai.createCompletion`} that are not explicitly specified on this class.
@@ -74,7 +77,7 @@ export declare interface OpenAIBaseInput {
74
77
  */
75
78
  apiKey?: string;
76
79
  }
77
- export type OpenAICoreRequestOptions<Req = Record<string, unknown>> = _OpenAICoreRequestOptions<Req>;
80
+ export type OpenAICoreRequestOptions = OpenAIClient.RequestOptions;
78
81
  export interface OpenAICallOptions extends BaseLanguageModelCallOptions {
79
82
  /**
80
83
  * Additional options to pass to the underlying axios request.
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getEndpoint = void 0;
3
+ exports.getEndpoint = getEndpoint;
4
4
  /**
5
5
  * This function generates an endpoint URL for (Azure) OpenAI
6
6
  * based on the configuration parameters provided.
@@ -48,4 +48,3 @@ function getEndpoint(config) {
48
48
  }
49
49
  return baseURL;
50
50
  }
51
- exports.getEndpoint = getEndpoint;
@@ -2,10 +2,9 @@
2
2
  /* eslint-disable @typescript-eslint/no-explicit-any */
3
3
  /* eslint-disable no-param-reassign */
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.addLangChainErrorFields = void 0;
5
+ exports.addLangChainErrorFields = addLangChainErrorFields;
6
6
  function addLangChainErrorFields(error, lc_error_code) {
7
7
  error.lc_error_code = lc_error_code;
8
8
  error.message = `${error.message}\n\nTroubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${lc_error_code}/\n`;
9
9
  return error;
10
10
  }
11
- exports.addLangChainErrorFields = addLangChainErrorFields;
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isHeaders = isHeaders;
4
+ exports.normalizeHeaders = normalizeHeaders;
5
+ const iife = (fn) => fn();
6
+ function isHeaders(headers) {
7
+ return (typeof Headers !== "undefined" &&
8
+ headers !== null &&
9
+ typeof headers === "object" &&
10
+ Object.prototype.toString.call(headers) === "[object Headers]");
11
+ }
12
+ function normalizeHeaders(headers) {
13
+ const output = iife(() => {
14
+ // If headers is a Headers instance
15
+ if (isHeaders(headers)) {
16
+ return headers;
17
+ }
18
+ // If headers is an array of [key, value] pairs
19
+ else if (Array.isArray(headers)) {
20
+ return new Headers(headers);
21
+ }
22
+ // If headers is a NullableHeaders-like object (has 'values' property that is a Headers)
23
+ else if (typeof headers === "object" &&
24
+ headers !== null &&
25
+ "values" in headers &&
26
+ isHeaders(headers.values)) {
27
+ return headers.values;
28
+ }
29
+ // If headers is a plain object
30
+ else if (typeof headers === "object" && headers !== null) {
31
+ const entries = Object.entries(headers)
32
+ .filter(([, v]) => typeof v === "string")
33
+ .map(([k, v]) => [k, v]);
34
+ return new Headers(entries);
35
+ }
36
+ return new Headers();
37
+ });
38
+ return Object.fromEntries(output.entries());
39
+ }
@@ -0,0 +1,8 @@
1
+ type HeaderValue = string | undefined | null;
2
+ export type HeadersLike = Headers | readonly HeaderValue[][] | Record<string, HeaderValue | readonly HeaderValue[]> | undefined | null | {
3
+ values: Headers;
4
+ [key: string]: unknown;
5
+ };
6
+ export declare function isHeaders(headers: unknown): headers is Headers;
7
+ export declare function normalizeHeaders(headers: HeadersLike): Record<string, HeaderValue | readonly HeaderValue[]>;
8
+ export {};
@@ -0,0 +1,35 @@
1
+ const iife = (fn) => fn();
2
+ export function isHeaders(headers) {
3
+ return (typeof Headers !== "undefined" &&
4
+ headers !== null &&
5
+ typeof headers === "object" &&
6
+ Object.prototype.toString.call(headers) === "[object Headers]");
7
+ }
8
+ export function normalizeHeaders(headers) {
9
+ const output = iife(() => {
10
+ // If headers is a Headers instance
11
+ if (isHeaders(headers)) {
12
+ return headers;
13
+ }
14
+ // If headers is an array of [key, value] pairs
15
+ else if (Array.isArray(headers)) {
16
+ return new Headers(headers);
17
+ }
18
+ // If headers is a NullableHeaders-like object (has 'values' property that is a Headers)
19
+ else if (typeof headers === "object" &&
20
+ headers !== null &&
21
+ "values" in headers &&
22
+ isHeaders(headers.values)) {
23
+ return headers.values;
24
+ }
25
+ // If headers is a plain object
26
+ else if (typeof headers === "object" && headers !== null) {
27
+ const entries = Object.entries(headers)
28
+ .filter(([, v]) => typeof v === "string")
29
+ .map(([k, v]) => [k, v]);
30
+ return new Headers(entries);
31
+ }
32
+ return new Headers();
33
+ });
34
+ return Object.fromEntries(output.entries());
35
+ }
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatFunctionDefinitions = void 0;
3
+ exports.formatFunctionDefinitions = formatFunctionDefinitions;
4
4
  function isAnyOfProp(prop) {
5
5
  return (prop.anyOf !== undefined &&
6
6
  Array.isArray(prop.anyOf));
@@ -26,7 +26,6 @@ function formatFunctionDefinitions(functions) {
26
26
  lines.push("} // namespace functions");
27
27
  return lines.join("\n");
28
28
  }
29
- exports.formatFunctionDefinitions = formatFunctionDefinitions;
30
29
  // Format just the properties of an object (not including the surrounding braces)
31
30
  function formatObjectProperties(obj, indent) {
32
31
  const lines = [];
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatToOpenAIToolChoice = exports.formatToOpenAIAssistantTool = exports.formatToOpenAITool = exports.formatToOpenAIFunction = exports.wrapOpenAIClientError = void 0;
3
+ exports.formatToOpenAITool = exports.formatToOpenAIFunction = void 0;
4
+ exports.wrapOpenAIClientError = wrapOpenAIClientError;
5
+ exports.formatToOpenAIAssistantTool = formatToOpenAIAssistantTool;
6
+ exports.formatToOpenAIToolChoice = formatToOpenAIToolChoice;
4
7
  const openai_1 = require("openai");
5
8
  const function_calling_1 = require("@langchain/core/utils/function_calling");
6
9
  Object.defineProperty(exports, "formatToOpenAIFunction", { enumerable: true, get: function () { return function_calling_1.convertToOpenAIFunction; } });
@@ -36,7 +39,6 @@ function wrapOpenAIClientError(e) {
36
39
  }
37
40
  return error;
38
41
  }
39
- exports.wrapOpenAIClientError = wrapOpenAIClientError;
40
42
  function formatToOpenAIAssistantTool(tool) {
41
43
  return {
42
44
  type: "function",
@@ -49,7 +51,6 @@ function formatToOpenAIAssistantTool(tool) {
49
51
  },
50
52
  };
51
53
  }
52
- exports.formatToOpenAIAssistantTool = formatToOpenAIAssistantTool;
53
54
  function formatToOpenAIToolChoice(toolChoice) {
54
55
  if (!toolChoice) {
55
56
  return undefined;
@@ -75,4 +76,3 @@ function formatToOpenAIToolChoice(toolChoice) {
75
76
  return toolChoice;
76
77
  }
77
78
  }
78
- exports.formatToOpenAIToolChoice = formatToOpenAIToolChoice;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.convertPromptToOpenAI = void 0;
3
+ exports.convertPromptToOpenAI = convertPromptToOpenAI;
4
4
  const chat_models_js_1 = require("../chat_models.cjs");
5
5
  /**
6
6
  * Convert a formatted LangChain prompt (e.g. pulled from the hub) into
@@ -39,4 +39,3 @@ function convertPromptToOpenAI(formattedPrompt) {
39
39
  messages: (0, chat_models_js_1._convertMessagesToOpenAIParams)(messages),
40
40
  };
41
41
  }
42
- exports.convertPromptToOpenAI = convertPromptToOpenAI;