@langchain/openai 0.0.26 → 0.0.28

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.
@@ -48,12 +48,30 @@ function messageToOpenAIRole(message) {
48
48
  }
49
49
  exports.messageToOpenAIRole = messageToOpenAIRole;
50
50
  function openAIResponseToChatMessage(message) {
51
+ const rawToolCalls = message.tool_calls;
51
52
  switch (message.role) {
52
- case "assistant":
53
- return new messages_1.AIMessage(message.content || "", {
54
- function_call: message.function_call,
55
- tool_calls: message.tool_calls,
53
+ case "assistant": {
54
+ const toolCalls = [];
55
+ const invalidToolCalls = [];
56
+ for (const rawToolCall of rawToolCalls ?? []) {
57
+ try {
58
+ toolCalls.push((0, openai_tools_1.parseToolCall)(rawToolCall, { returnId: true }));
59
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
+ }
61
+ catch (e) {
62
+ invalidToolCalls.push((0, openai_tools_1.makeInvalidToolCall)(rawToolCall, e.message));
63
+ }
64
+ }
65
+ return new messages_1.AIMessage({
66
+ content: message.content || "",
67
+ tool_calls: toolCalls,
68
+ invalid_tool_calls: invalidToolCalls,
69
+ additional_kwargs: {
70
+ function_call: message.function_call,
71
+ tool_calls: rawToolCalls,
72
+ },
56
73
  });
74
+ }
57
75
  default:
58
76
  return new messages_1.ChatMessage(message.content || "", message.role ?? "unknown");
59
77
  }
@@ -81,7 +99,22 @@ delta, defaultRole) {
81
99
  return new messages_1.HumanMessageChunk({ content });
82
100
  }
83
101
  else if (role === "assistant") {
84
- return new messages_1.AIMessageChunk({ content, additional_kwargs });
102
+ const toolCallChunks = [];
103
+ if (Array.isArray(delta.tool_calls)) {
104
+ for (const rawToolCall of delta.tool_calls) {
105
+ toolCallChunks.push({
106
+ name: rawToolCall.function?.name,
107
+ args: rawToolCall.function?.arguments,
108
+ id: rawToolCall.id,
109
+ index: rawToolCall.index,
110
+ });
111
+ }
112
+ }
113
+ return new messages_1.AIMessageChunk({
114
+ content,
115
+ tool_call_chunks: toolCallChunks,
116
+ additional_kwargs,
117
+ });
85
118
  }
86
119
  else if (role === "system") {
87
120
  return new messages_1.SystemMessageChunk({ content });
@@ -118,11 +151,16 @@ function convertMessagesToOpenAIParams(messages) {
118
151
  if (message.additional_kwargs.function_call != null) {
119
152
  completionParam.function_call = message.additional_kwargs.function_call;
120
153
  }
121
- if (message.additional_kwargs.tool_calls != null) {
122
- completionParam.tool_calls = message.additional_kwargs.tool_calls;
154
+ if ((0, messages_1.isAIMessage)(message) && !!message.tool_calls?.length) {
155
+ completionParam.tool_calls = message.tool_calls.map(openai_tools_1.convertLangChainToolCallToOpenAI);
123
156
  }
124
- if (message.tool_call_id != null) {
125
- completionParam.tool_call_id = message.tool_call_id;
157
+ else {
158
+ if (message.additional_kwargs.tool_calls != null) {
159
+ completionParam.tool_calls = message.additional_kwargs.tool_calls;
160
+ }
161
+ if (message.tool_call_id != null) {
162
+ completionParam.tool_call_id = message.tool_call_id;
163
+ }
126
164
  }
127
165
  return completionParam;
128
166
  });
@@ -150,7 +188,7 @@ function convertMessagesToOpenAIParams(messages) {
150
188
  * // Create a new instance of ChatOpenAI with specific temperature and model name settings
151
189
  * const model = new ChatOpenAI({
152
190
  * temperature: 0.9,
153
- * modelName: "ft:gpt-3.5-turbo-0613:{ORG_NAME}::{MODEL_ID}",
191
+ * model: "ft:gpt-3.5-turbo-0613:{ORG_NAME}::{MODEL_ID}",
154
192
  * });
155
193
  *
156
194
  * // Invoke the model with a message and await the response
@@ -181,6 +219,7 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
181
219
  get lc_secrets() {
182
220
  return {
183
221
  openAIApiKey: "OPENAI_API_KEY",
222
+ apiKey: "OPENAI_API_KEY",
184
223
  azureOpenAIApiKey: "AZURE_OPENAI_API_KEY",
185
224
  organization: "OPENAI_ORGANIZATION",
186
225
  };
@@ -189,6 +228,7 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
189
228
  return {
190
229
  modelName: "model",
191
230
  openAIApiKey: "openai_api_key",
231
+ apiKey: "openai_api_key",
192
232
  azureOpenAIApiVersion: "azure_openai_api_version",
193
233
  azureOpenAIApiKey: "azure_openai_api_key",
194
234
  azureOpenAIApiInstanceName: "azure_openai_api_instance_name",
@@ -247,6 +287,12 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
247
287
  writable: true,
248
288
  value: "gpt-3.5-turbo"
249
289
  });
290
+ Object.defineProperty(this, "model", {
291
+ enumerable: true,
292
+ configurable: true,
293
+ writable: true,
294
+ value: "gpt-3.5-turbo"
295
+ });
250
296
  Object.defineProperty(this, "modelKwargs", {
251
297
  enumerable: true,
252
298
  configurable: true,
@@ -259,6 +305,12 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
259
305
  writable: true,
260
306
  value: void 0
261
307
  });
308
+ Object.defineProperty(this, "stopSequences", {
309
+ enumerable: true,
310
+ configurable: true,
311
+ writable: true,
312
+ value: void 0
313
+ });
262
314
  Object.defineProperty(this, "user", {
263
315
  enumerable: true,
264
316
  configurable: true,
@@ -301,6 +353,12 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
301
353
  writable: true,
302
354
  value: void 0
303
355
  });
356
+ Object.defineProperty(this, "apiKey", {
357
+ enumerable: true,
358
+ configurable: true,
359
+ writable: true,
360
+ value: void 0
361
+ });
304
362
  Object.defineProperty(this, "azureOpenAIApiVersion", {
305
363
  enumerable: true,
306
364
  configurable: true,
@@ -350,11 +408,14 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
350
408
  value: void 0
351
409
  });
352
410
  this.openAIApiKey =
353
- fields?.openAIApiKey ?? (0, env_1.getEnvironmentVariable)("OPENAI_API_KEY");
411
+ fields?.apiKey ??
412
+ fields?.openAIApiKey ??
413
+ (0, env_1.getEnvironmentVariable)("OPENAI_API_KEY");
414
+ this.apiKey = this.openAIApiKey;
354
415
  this.azureOpenAIApiKey =
355
416
  fields?.azureOpenAIApiKey ??
356
417
  (0, env_1.getEnvironmentVariable)("AZURE_OPENAI_API_KEY");
357
- if (!this.azureOpenAIApiKey && !this.openAIApiKey) {
418
+ if (!this.azureOpenAIApiKey && !this.apiKey) {
358
419
  throw new Error("OpenAI or Azure OpenAI API key not found");
359
420
  }
360
421
  this.azureOpenAIApiInstanceName =
@@ -372,7 +433,8 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
372
433
  this.organization =
373
434
  fields?.configuration?.organization ??
374
435
  (0, env_1.getEnvironmentVariable)("OPENAI_ORGANIZATION");
375
- this.modelName = fields?.modelName ?? this.modelName;
436
+ this.modelName = fields?.model ?? fields?.modelName ?? this.model;
437
+ this.model = this.modelName;
376
438
  this.modelKwargs = fields?.modelKwargs ?? {};
377
439
  this.timeout = fields?.timeout;
378
440
  this.temperature = fields?.temperature ?? this.temperature;
@@ -384,7 +446,8 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
384
446
  this.topLogprobs = fields?.topLogprobs;
385
447
  this.n = fields?.n ?? this.n;
386
448
  this.logitBias = fields?.logitBias;
387
- this.stop = fields?.stop;
449
+ this.stop = fields?.stopSequences ?? fields?.stop;
450
+ this.stopSequences = this?.stop;
388
451
  this.user = fields?.user;
389
452
  this.streaming = fields?.streaming ?? false;
390
453
  if (this.azureOpenAIApiKey) {
@@ -397,10 +460,10 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
397
460
  if (!this.azureOpenAIApiVersion) {
398
461
  throw new Error("Azure OpenAI API version not found");
399
462
  }
400
- this.openAIApiKey = this.openAIApiKey ?? "";
463
+ this.apiKey = this.apiKey ?? "";
401
464
  }
402
465
  this.clientConfig = {
403
- apiKey: this.openAIApiKey,
466
+ apiKey: this.apiKey,
404
467
  organization: this.organization,
405
468
  baseURL: configuration?.basePath ?? fields?.configuration?.basePath,
406
469
  dangerouslyAllowBrowser: true,
@@ -412,6 +475,12 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
412
475
  ...fields?.configuration,
413
476
  };
414
477
  }
478
+ bindTools(tools, kwargs) {
479
+ return this.bind({
480
+ tools: tools.map(function_calling_1.convertToOpenAITool),
481
+ ...kwargs,
482
+ });
483
+ }
415
484
  /**
416
485
  * Get the parameters used to invoke the model
417
486
  */
@@ -421,7 +490,7 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
421
490
  tools.every((tool) => Array.isArray(tool.lc_namespace)));
422
491
  }
423
492
  const params = {
424
- model: this.modelName,
493
+ model: this.model,
425
494
  temperature: this.temperature,
426
495
  top_p: this.topP,
427
496
  frequency_penalty: this.frequencyPenalty,
@@ -431,7 +500,7 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
431
500
  top_logprobs: this.topLogprobs,
432
501
  n: this.n,
433
502
  logit_bias: this.logitBias,
434
- stop: options?.stop ?? this.stop,
503
+ stop: options?.stop ?? this.stopSequences,
435
504
  user: this.user,
436
505
  stream: this.streaming,
437
506
  functions: options?.functions,
@@ -449,7 +518,7 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
449
518
  /** @ignore */
450
519
  _identifyingParams() {
451
520
  return {
452
- model_name: this.modelName,
521
+ model_name: this.model,
453
522
  ...this.invocationParams(),
454
523
  ...this.clientConfig,
455
524
  };
@@ -634,7 +703,7 @@ class ChatOpenAI extends chat_models_1.BaseChatModel {
634
703
  let tokensPerMessage = 0;
635
704
  let tokensPerName = 0;
636
705
  // From: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
637
- if (this.modelName === "gpt-3.5-turbo-0301") {
706
+ if (this.model === "gpt-3.5-turbo-0301") {
638
707
  tokensPerMessage = 4;
639
708
  tokensPerName = -1;
640
709
  }
@@ -1,12 +1,12 @@
1
1
  import { type ClientOptions, OpenAI as OpenAIClient } from "openai";
2
2
  import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
3
- import { type BaseMessage } from "@langchain/core/messages";
3
+ import { AIMessageChunk, type BaseMessage } from "@langchain/core/messages";
4
4
  import { ChatGenerationChunk, type ChatResult } from "@langchain/core/outputs";
5
5
  import { type StructuredToolInterface } from "@langchain/core/tools";
6
6
  import { BaseChatModel, type BaseChatModelParams } from "@langchain/core/language_models/chat_models";
7
7
  import type { BaseFunctionCallOptions, BaseLanguageModelInput, StructuredOutputMethodOptions, StructuredOutputMethodParams } from "@langchain/core/language_models/base";
8
8
  import { z } from "zod";
9
- import { Runnable } from "@langchain/core/runnables";
9
+ import { Runnable, RunnableInterface } from "@langchain/core/runnables";
10
10
  import type { AzureOpenAIInput, OpenAICallOptions, OpenAIChatInput, OpenAICoreRequestOptions, LegacyOpenAIInput } from "./types.js";
11
11
  export type { AzureOpenAIInput, OpenAICallOptions, OpenAIChatInput };
12
12
  interface TokenUsage {
@@ -51,7 +51,7 @@ export interface ChatOpenAICallOptions extends OpenAICallOptions, BaseFunctionCa
51
51
  * // Create a new instance of ChatOpenAI with specific temperature and model name settings
52
52
  * const model = new ChatOpenAI({
53
53
  * temperature: 0.9,
54
- * modelName: "ft:gpt-3.5-turbo-0613:{ORG_NAME}::{MODEL_ID}",
54
+ * model: "ft:gpt-3.5-turbo-0613:{ORG_NAME}::{MODEL_ID}",
55
55
  * });
56
56
  *
57
57
  * // Invoke the model with a message and await the response
@@ -62,7 +62,7 @@ export interface ChatOpenAICallOptions extends OpenAICallOptions, BaseFunctionCa
62
62
  *
63
63
  * ```
64
64
  */
65
- export declare class ChatOpenAI<CallOptions extends ChatOpenAICallOptions = ChatOpenAICallOptions> extends BaseChatModel<CallOptions> implements OpenAIChatInput, AzureOpenAIInput {
65
+ export declare class ChatOpenAI<CallOptions extends ChatOpenAICallOptions = ChatOpenAICallOptions> extends BaseChatModel<CallOptions, AIMessageChunk> implements OpenAIChatInput, AzureOpenAIInput {
66
66
  static lc_name(): string;
67
67
  get callKeys(): string[];
68
68
  lc_serializable: boolean;
@@ -77,8 +77,10 @@ export declare class ChatOpenAI<CallOptions extends ChatOpenAICallOptions = Chat
77
77
  n: number;
78
78
  logitBias?: Record<string, number>;
79
79
  modelName: string;
80
+ model: string;
80
81
  modelKwargs?: OpenAIChatInput["modelKwargs"];
81
82
  stop?: string[];
83
+ stopSequences?: string[];
82
84
  user?: string;
83
85
  timeout?: number;
84
86
  streaming: boolean;
@@ -86,6 +88,7 @@ export declare class ChatOpenAI<CallOptions extends ChatOpenAICallOptions = Chat
86
88
  logprobs?: boolean;
87
89
  topLogprobs?: number;
88
90
  openAIApiKey?: string;
91
+ apiKey?: string;
89
92
  azureOpenAIApiVersion?: string;
90
93
  azureOpenAIApiKey?: string;
91
94
  azureOpenAIApiInstanceName?: string;
@@ -99,6 +102,7 @@ export declare class ChatOpenAI<CallOptions extends ChatOpenAICallOptions = Chat
99
102
  },
100
103
  /** @deprecated */
101
104
  configuration?: ClientOptions & LegacyOpenAIInput);
105
+ bindTools(tools: (Record<string, unknown> | StructuredToolInterface)[], kwargs?: Partial<CallOptions>): RunnableInterface<BaseLanguageModelInput, AIMessageChunk, CallOptions>;
102
106
  /**
103
107
  * Get the parameters used to invoke the model
104
108
  */
@@ -1,12 +1,12 @@
1
1
  import { OpenAI as OpenAIClient } from "openai";
2
- import { AIMessage, AIMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessageChunk, HumanMessageChunk, SystemMessageChunk, ToolMessageChunk, } from "@langchain/core/messages";
2
+ import { AIMessage, AIMessageChunk, ChatMessage, ChatMessageChunk, FunctionMessageChunk, HumanMessageChunk, SystemMessageChunk, ToolMessageChunk, isAIMessage, } from "@langchain/core/messages";
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
6
  import { convertToOpenAITool } from "@langchain/core/utils/function_calling";
7
7
  import { RunnablePassthrough, RunnableSequence, } from "@langchain/core/runnables";
8
8
  import { JsonOutputParser, StructuredOutputParser, } from "@langchain/core/output_parsers";
9
- import { JsonOutputKeyToolsParser } from "@langchain/core/output_parsers/openai_tools";
9
+ import { JsonOutputKeyToolsParser, convertLangChainToolCallToOpenAI, makeInvalidToolCall, parseToolCall, } from "@langchain/core/output_parsers/openai_tools";
10
10
  import { zodToJsonSchema } from "zod-to-json-schema";
11
11
  import { getEndpoint } from "./utils/azure.js";
12
12
  import { wrapOpenAIClientError } from "./utils/openai.js";
@@ -44,12 +44,30 @@ export function messageToOpenAIRole(message) {
44
44
  }
45
45
  }
46
46
  function openAIResponseToChatMessage(message) {
47
+ const rawToolCalls = message.tool_calls;
47
48
  switch (message.role) {
48
- case "assistant":
49
- return new AIMessage(message.content || "", {
50
- function_call: message.function_call,
51
- tool_calls: message.tool_calls,
49
+ case "assistant": {
50
+ const toolCalls = [];
51
+ const invalidToolCalls = [];
52
+ for (const rawToolCall of rawToolCalls ?? []) {
53
+ try {
54
+ toolCalls.push(parseToolCall(rawToolCall, { returnId: true }));
55
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
+ }
57
+ catch (e) {
58
+ invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message));
59
+ }
60
+ }
61
+ return new AIMessage({
62
+ content: message.content || "",
63
+ tool_calls: toolCalls,
64
+ invalid_tool_calls: invalidToolCalls,
65
+ additional_kwargs: {
66
+ function_call: message.function_call,
67
+ tool_calls: rawToolCalls,
68
+ },
52
69
  });
70
+ }
53
71
  default:
54
72
  return new ChatMessage(message.content || "", message.role ?? "unknown");
55
73
  }
@@ -77,7 +95,22 @@ delta, defaultRole) {
77
95
  return new HumanMessageChunk({ content });
78
96
  }
79
97
  else if (role === "assistant") {
80
- return new AIMessageChunk({ content, additional_kwargs });
98
+ const toolCallChunks = [];
99
+ if (Array.isArray(delta.tool_calls)) {
100
+ for (const rawToolCall of delta.tool_calls) {
101
+ toolCallChunks.push({
102
+ name: rawToolCall.function?.name,
103
+ args: rawToolCall.function?.arguments,
104
+ id: rawToolCall.id,
105
+ index: rawToolCall.index,
106
+ });
107
+ }
108
+ }
109
+ return new AIMessageChunk({
110
+ content,
111
+ tool_call_chunks: toolCallChunks,
112
+ additional_kwargs,
113
+ });
81
114
  }
82
115
  else if (role === "system") {
83
116
  return new SystemMessageChunk({ content });
@@ -114,11 +147,16 @@ function convertMessagesToOpenAIParams(messages) {
114
147
  if (message.additional_kwargs.function_call != null) {
115
148
  completionParam.function_call = message.additional_kwargs.function_call;
116
149
  }
117
- if (message.additional_kwargs.tool_calls != null) {
118
- completionParam.tool_calls = message.additional_kwargs.tool_calls;
150
+ if (isAIMessage(message) && !!message.tool_calls?.length) {
151
+ completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI);
119
152
  }
120
- if (message.tool_call_id != null) {
121
- completionParam.tool_call_id = message.tool_call_id;
153
+ else {
154
+ if (message.additional_kwargs.tool_calls != null) {
155
+ completionParam.tool_calls = message.additional_kwargs.tool_calls;
156
+ }
157
+ if (message.tool_call_id != null) {
158
+ completionParam.tool_call_id = message.tool_call_id;
159
+ }
122
160
  }
123
161
  return completionParam;
124
162
  });
@@ -146,7 +184,7 @@ function convertMessagesToOpenAIParams(messages) {
146
184
  * // Create a new instance of ChatOpenAI with specific temperature and model name settings
147
185
  * const model = new ChatOpenAI({
148
186
  * temperature: 0.9,
149
- * modelName: "ft:gpt-3.5-turbo-0613:{ORG_NAME}::{MODEL_ID}",
187
+ * model: "ft:gpt-3.5-turbo-0613:{ORG_NAME}::{MODEL_ID}",
150
188
  * });
151
189
  *
152
190
  * // Invoke the model with a message and await the response
@@ -177,6 +215,7 @@ export class ChatOpenAI extends BaseChatModel {
177
215
  get lc_secrets() {
178
216
  return {
179
217
  openAIApiKey: "OPENAI_API_KEY",
218
+ apiKey: "OPENAI_API_KEY",
180
219
  azureOpenAIApiKey: "AZURE_OPENAI_API_KEY",
181
220
  organization: "OPENAI_ORGANIZATION",
182
221
  };
@@ -185,6 +224,7 @@ export class ChatOpenAI extends BaseChatModel {
185
224
  return {
186
225
  modelName: "model",
187
226
  openAIApiKey: "openai_api_key",
227
+ apiKey: "openai_api_key",
188
228
  azureOpenAIApiVersion: "azure_openai_api_version",
189
229
  azureOpenAIApiKey: "azure_openai_api_key",
190
230
  azureOpenAIApiInstanceName: "azure_openai_api_instance_name",
@@ -243,6 +283,12 @@ export class ChatOpenAI extends BaseChatModel {
243
283
  writable: true,
244
284
  value: "gpt-3.5-turbo"
245
285
  });
286
+ Object.defineProperty(this, "model", {
287
+ enumerable: true,
288
+ configurable: true,
289
+ writable: true,
290
+ value: "gpt-3.5-turbo"
291
+ });
246
292
  Object.defineProperty(this, "modelKwargs", {
247
293
  enumerable: true,
248
294
  configurable: true,
@@ -255,6 +301,12 @@ export class ChatOpenAI extends BaseChatModel {
255
301
  writable: true,
256
302
  value: void 0
257
303
  });
304
+ Object.defineProperty(this, "stopSequences", {
305
+ enumerable: true,
306
+ configurable: true,
307
+ writable: true,
308
+ value: void 0
309
+ });
258
310
  Object.defineProperty(this, "user", {
259
311
  enumerable: true,
260
312
  configurable: true,
@@ -297,6 +349,12 @@ export class ChatOpenAI extends BaseChatModel {
297
349
  writable: true,
298
350
  value: void 0
299
351
  });
352
+ Object.defineProperty(this, "apiKey", {
353
+ enumerable: true,
354
+ configurable: true,
355
+ writable: true,
356
+ value: void 0
357
+ });
300
358
  Object.defineProperty(this, "azureOpenAIApiVersion", {
301
359
  enumerable: true,
302
360
  configurable: true,
@@ -346,11 +404,14 @@ export class ChatOpenAI extends BaseChatModel {
346
404
  value: void 0
347
405
  });
348
406
  this.openAIApiKey =
349
- fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY");
407
+ fields?.apiKey ??
408
+ fields?.openAIApiKey ??
409
+ getEnvironmentVariable("OPENAI_API_KEY");
410
+ this.apiKey = this.openAIApiKey;
350
411
  this.azureOpenAIApiKey =
351
412
  fields?.azureOpenAIApiKey ??
352
413
  getEnvironmentVariable("AZURE_OPENAI_API_KEY");
353
- if (!this.azureOpenAIApiKey && !this.openAIApiKey) {
414
+ if (!this.azureOpenAIApiKey && !this.apiKey) {
354
415
  throw new Error("OpenAI or Azure OpenAI API key not found");
355
416
  }
356
417
  this.azureOpenAIApiInstanceName =
@@ -368,7 +429,8 @@ export class ChatOpenAI extends BaseChatModel {
368
429
  this.organization =
369
430
  fields?.configuration?.organization ??
370
431
  getEnvironmentVariable("OPENAI_ORGANIZATION");
371
- this.modelName = fields?.modelName ?? this.modelName;
432
+ this.modelName = fields?.model ?? fields?.modelName ?? this.model;
433
+ this.model = this.modelName;
372
434
  this.modelKwargs = fields?.modelKwargs ?? {};
373
435
  this.timeout = fields?.timeout;
374
436
  this.temperature = fields?.temperature ?? this.temperature;
@@ -380,7 +442,8 @@ export class ChatOpenAI extends BaseChatModel {
380
442
  this.topLogprobs = fields?.topLogprobs;
381
443
  this.n = fields?.n ?? this.n;
382
444
  this.logitBias = fields?.logitBias;
383
- this.stop = fields?.stop;
445
+ this.stop = fields?.stopSequences ?? fields?.stop;
446
+ this.stopSequences = this?.stop;
384
447
  this.user = fields?.user;
385
448
  this.streaming = fields?.streaming ?? false;
386
449
  if (this.azureOpenAIApiKey) {
@@ -393,10 +456,10 @@ export class ChatOpenAI extends BaseChatModel {
393
456
  if (!this.azureOpenAIApiVersion) {
394
457
  throw new Error("Azure OpenAI API version not found");
395
458
  }
396
- this.openAIApiKey = this.openAIApiKey ?? "";
459
+ this.apiKey = this.apiKey ?? "";
397
460
  }
398
461
  this.clientConfig = {
399
- apiKey: this.openAIApiKey,
462
+ apiKey: this.apiKey,
400
463
  organization: this.organization,
401
464
  baseURL: configuration?.basePath ?? fields?.configuration?.basePath,
402
465
  dangerouslyAllowBrowser: true,
@@ -408,6 +471,12 @@ export class ChatOpenAI extends BaseChatModel {
408
471
  ...fields?.configuration,
409
472
  };
410
473
  }
474
+ bindTools(tools, kwargs) {
475
+ return this.bind({
476
+ tools: tools.map(convertToOpenAITool),
477
+ ...kwargs,
478
+ });
479
+ }
411
480
  /**
412
481
  * Get the parameters used to invoke the model
413
482
  */
@@ -417,7 +486,7 @@ export class ChatOpenAI extends BaseChatModel {
417
486
  tools.every((tool) => Array.isArray(tool.lc_namespace)));
418
487
  }
419
488
  const params = {
420
- model: this.modelName,
489
+ model: this.model,
421
490
  temperature: this.temperature,
422
491
  top_p: this.topP,
423
492
  frequency_penalty: this.frequencyPenalty,
@@ -427,7 +496,7 @@ export class ChatOpenAI extends BaseChatModel {
427
496
  top_logprobs: this.topLogprobs,
428
497
  n: this.n,
429
498
  logit_bias: this.logitBias,
430
- stop: options?.stop ?? this.stop,
499
+ stop: options?.stop ?? this.stopSequences,
431
500
  user: this.user,
432
501
  stream: this.streaming,
433
502
  functions: options?.functions,
@@ -445,7 +514,7 @@ export class ChatOpenAI extends BaseChatModel {
445
514
  /** @ignore */
446
515
  _identifyingParams() {
447
516
  return {
448
- model_name: this.modelName,
517
+ model_name: this.model,
449
518
  ...this.invocationParams(),
450
519
  ...this.clientConfig,
451
520
  };
@@ -630,7 +699,7 @@ export class ChatOpenAI extends BaseChatModel {
630
699
  let tokensPerMessage = 0;
631
700
  let tokensPerName = 0;
632
701
  // From: https://github.com/openai/openai-cookbook/blob/main/examples/How_to_format_inputs_to_ChatGPT_models.ipynb
633
- if (this.modelName === "gpt-3.5-turbo-0301") {
702
+ if (this.model === "gpt-3.5-turbo-0301") {
634
703
  tokensPerMessage = 4;
635
704
  tokensPerName = -1;
636
705
  }
@@ -32,6 +32,12 @@ class OpenAIEmbeddings extends embeddings_1.Embeddings {
32
32
  writable: true,
33
33
  value: "text-embedding-ada-002"
34
34
  });
35
+ Object.defineProperty(this, "model", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: "text-embedding-ada-002"
40
+ });
35
41
  Object.defineProperty(this, "batchSize", {
36
42
  enumerable: true,
37
43
  configurable: true,
@@ -109,7 +115,8 @@ class OpenAIEmbeddings extends embeddings_1.Embeddings {
109
115
  writable: true,
110
116
  value: void 0
111
117
  });
112
- let apiKey = fieldsWithDefaults?.openAIApiKey ??
118
+ let apiKey = fieldsWithDefaults?.apiKey ??
119
+ fieldsWithDefaults?.openAIApiKey ??
113
120
  (0, env_1.getEnvironmentVariable)("OPENAI_API_KEY");
114
121
  const azureApiKey = fieldsWithDefaults?.azureOpenAIApiKey ??
115
122
  (0, env_1.getEnvironmentVariable)("AZURE_OPENAI_API_KEY");
@@ -130,7 +137,9 @@ class OpenAIEmbeddings extends embeddings_1.Embeddings {
130
137
  this.organization =
131
138
  fieldsWithDefaults?.configuration?.organization ??
132
139
  (0, env_1.getEnvironmentVariable)("OPENAI_ORGANIZATION");
133
- this.modelName = fieldsWithDefaults?.modelName ?? this.modelName;
140
+ this.modelName =
141
+ fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;
142
+ this.model = this.modelName;
134
143
  this.batchSize =
135
144
  fieldsWithDefaults?.batchSize ?? (azureApiKey ? 1 : this.batchSize);
136
145
  this.stripNewLines =
@@ -175,7 +184,7 @@ class OpenAIEmbeddings extends embeddings_1.Embeddings {
175
184
  const batches = (0, chunk_array_1.chunkArray)(this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts, this.batchSize);
176
185
  const batchRequests = batches.map((batch) => {
177
186
  const params = {
178
- model: this.modelName,
187
+ model: this.model,
179
188
  input: batch,
180
189
  };
181
190
  if (this.dimensions) {
@@ -202,7 +211,7 @@ class OpenAIEmbeddings extends embeddings_1.Embeddings {
202
211
  */
203
212
  async embedQuery(text) {
204
213
  const params = {
205
- model: this.modelName,
214
+ model: this.model,
206
215
  input: this.stripNewLines ? text.replace(/\n/g, " ") : text,
207
216
  };
208
217
  if (this.dimensions) {
@@ -6,8 +6,13 @@ import { AzureOpenAIInput, LegacyOpenAIInput } from "./types.js";
6
6
  * defines additional parameters specific to the OpenAIEmbeddings class.
7
7
  */
8
8
  export interface OpenAIEmbeddingsParams extends EmbeddingsParams {
9
- /** Model name to use */
9
+ /**
10
+ * Model name to use
11
+ * Alias for `model`
12
+ */
10
13
  modelName: string;
14
+ /** Model name to use */
15
+ model: string;
11
16
  /**
12
17
  * The number of dimensions the resulting output embeddings should have.
13
18
  * Only supported in `text-embedding-3` and later models.
@@ -46,6 +51,7 @@ export interface OpenAIEmbeddingsParams extends EmbeddingsParams {
46
51
  */
47
52
  export declare class OpenAIEmbeddings extends Embeddings implements OpenAIEmbeddingsParams, AzureOpenAIInput {
48
53
  modelName: string;
54
+ model: string;
49
55
  batchSize: number;
50
56
  stripNewLines: boolean;
51
57
  /**
@@ -64,7 +70,13 @@ export declare class OpenAIEmbeddings extends Embeddings implements OpenAIEmbedd
64
70
  private clientConfig;
65
71
  constructor(fields?: Partial<OpenAIEmbeddingsParams> & Partial<AzureOpenAIInput> & {
66
72
  verbose?: boolean;
73
+ /**
74
+ * The OpenAI API key to use.
75
+ * Alias for `apiKey`.
76
+ */
67
77
  openAIApiKey?: string;
78
+ /** The OpenAI API key to use. */
79
+ apiKey?: string;
68
80
  configuration?: ClientOptions;
69
81
  }, configuration?: ClientOptions & LegacyOpenAIInput);
70
82
  /**
@@ -29,6 +29,12 @@ export class OpenAIEmbeddings extends Embeddings {
29
29
  writable: true,
30
30
  value: "text-embedding-ada-002"
31
31
  });
32
+ Object.defineProperty(this, "model", {
33
+ enumerable: true,
34
+ configurable: true,
35
+ writable: true,
36
+ value: "text-embedding-ada-002"
37
+ });
32
38
  Object.defineProperty(this, "batchSize", {
33
39
  enumerable: true,
34
40
  configurable: true,
@@ -106,7 +112,8 @@ export class OpenAIEmbeddings extends Embeddings {
106
112
  writable: true,
107
113
  value: void 0
108
114
  });
109
- let apiKey = fieldsWithDefaults?.openAIApiKey ??
115
+ let apiKey = fieldsWithDefaults?.apiKey ??
116
+ fieldsWithDefaults?.openAIApiKey ??
110
117
  getEnvironmentVariable("OPENAI_API_KEY");
111
118
  const azureApiKey = fieldsWithDefaults?.azureOpenAIApiKey ??
112
119
  getEnvironmentVariable("AZURE_OPENAI_API_KEY");
@@ -127,7 +134,9 @@ export class OpenAIEmbeddings extends Embeddings {
127
134
  this.organization =
128
135
  fieldsWithDefaults?.configuration?.organization ??
129
136
  getEnvironmentVariable("OPENAI_ORGANIZATION");
130
- this.modelName = fieldsWithDefaults?.modelName ?? this.modelName;
137
+ this.modelName =
138
+ fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;
139
+ this.model = this.modelName;
131
140
  this.batchSize =
132
141
  fieldsWithDefaults?.batchSize ?? (azureApiKey ? 1 : this.batchSize);
133
142
  this.stripNewLines =
@@ -172,7 +181,7 @@ export class OpenAIEmbeddings extends Embeddings {
172
181
  const batches = chunkArray(this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts, this.batchSize);
173
182
  const batchRequests = batches.map((batch) => {
174
183
  const params = {
175
- model: this.modelName,
184
+ model: this.model,
176
185
  input: batch,
177
186
  };
178
187
  if (this.dimensions) {
@@ -199,7 +208,7 @@ export class OpenAIEmbeddings extends Embeddings {
199
208
  */
200
209
  async embedQuery(text) {
201
210
  const params = {
202
- model: this.modelName,
211
+ model: this.model,
203
212
  input: this.stripNewLines ? text.replace(/\n/g, " ") : text,
204
213
  };
205
214
  if (this.dimensions) {
package/dist/legacy.cjs CHANGED
@@ -130,6 +130,12 @@ class OpenAIChat extends llms_1.LLM {
130
130
  writable: true,
131
131
  value: "gpt-3.5-turbo"
132
132
  });
133
+ Object.defineProperty(this, "model", {
134
+ enumerable: true,
135
+ configurable: true,
136
+ writable: true,
137
+ value: "gpt-3.5-turbo"
138
+ });
133
139
  Object.defineProperty(this, "prefixMessages", {
134
140
  enumerable: true,
135
141
  configurable: true,
package/dist/legacy.d.ts CHANGED
@@ -69,6 +69,7 @@ export declare class OpenAIChat extends LLM<OpenAIChatCallOptions> implements Op
69
69
  logitBias?: Record<string, number>;
70
70
  maxTokens?: number;
71
71
  modelName: string;
72
+ model: string;
72
73
  prefixMessages?: OpenAIClient.Chat.ChatCompletionMessageParam[];
73
74
  modelKwargs?: OpenAIChatInput["modelKwargs"];
74
75
  timeout?: number;
package/dist/legacy.js CHANGED
@@ -127,6 +127,12 @@ export class OpenAIChat extends LLM {
127
127
  writable: true,
128
128
  value: "gpt-3.5-turbo"
129
129
  });
130
+ Object.defineProperty(this, "model", {
131
+ enumerable: true,
132
+ configurable: true,
133
+ writable: true,
134
+ value: "gpt-3.5-turbo"
135
+ });
130
136
  Object.defineProperty(this, "prefixMessages", {
131
137
  enumerable: true,
132
138
  configurable: true,
package/dist/llms.cjs CHANGED
@@ -53,6 +53,7 @@ class OpenAI extends llms_1.BaseLLM {
53
53
  get lc_secrets() {
54
54
  return {
55
55
  openAIApiKey: "OPENAI_API_KEY",
56
+ apiKey: "OPENAI_API_KEY",
56
57
  azureOpenAIApiKey: "AZURE_OPENAI_API_KEY",
57
58
  organization: "OPENAI_ORGANIZATION",
58
59
  };
@@ -61,6 +62,7 @@ class OpenAI extends llms_1.BaseLLM {
61
62
  return {
62
63
  modelName: "model",
63
64
  openAIApiKey: "openai_api_key",
65
+ apiKey: "openai_api_key",
64
66
  azureOpenAIApiVersion: "azure_openai_api_version",
65
67
  azureOpenAIApiKey: "azure_openai_api_key",
66
68
  azureOpenAIApiInstanceName: "azure_openai_api_instance_name",
@@ -70,9 +72,9 @@ class OpenAI extends llms_1.BaseLLM {
70
72
  constructor(fields,
71
73
  /** @deprecated */
72
74
  configuration) {
73
- if ((fields?.modelName?.startsWith("gpt-3.5-turbo") ||
74
- fields?.modelName?.startsWith("gpt-4")) &&
75
- !fields?.modelName?.includes("-instruct")) {
75
+ let model = fields?.model ?? fields?.modelName;
76
+ if ((model?.startsWith("gpt-3.5-turbo") || model?.startsWith("gpt-4")) &&
77
+ !model?.includes("-instruct")) {
76
78
  // eslint-disable-next-line no-constructor-return
77
79
  return new legacy_js_1.OpenAIChat(fields, configuration);
78
80
  }
@@ -137,6 +139,12 @@ class OpenAI extends llms_1.BaseLLM {
137
139
  writable: true,
138
140
  value: "gpt-3.5-turbo-instruct"
139
141
  });
142
+ Object.defineProperty(this, "model", {
143
+ enumerable: true,
144
+ configurable: true,
145
+ writable: true,
146
+ value: "gpt-3.5-turbo-instruct"
147
+ });
140
148
  Object.defineProperty(this, "modelKwargs", {
141
149
  enumerable: true,
142
150
  configurable: true,
@@ -161,6 +169,12 @@ class OpenAI extends llms_1.BaseLLM {
161
169
  writable: true,
162
170
  value: void 0
163
171
  });
172
+ Object.defineProperty(this, "stopSequences", {
173
+ enumerable: true,
174
+ configurable: true,
175
+ writable: true,
176
+ value: void 0
177
+ });
164
178
  Object.defineProperty(this, "user", {
165
179
  enumerable: true,
166
180
  configurable: true,
@@ -179,6 +193,12 @@ class OpenAI extends llms_1.BaseLLM {
179
193
  writable: true,
180
194
  value: void 0
181
195
  });
196
+ Object.defineProperty(this, "apiKey", {
197
+ enumerable: true,
198
+ configurable: true,
199
+ writable: true,
200
+ value: void 0
201
+ });
182
202
  Object.defineProperty(this, "azureOpenAIApiVersion", {
183
203
  enumerable: true,
184
204
  configurable: true,
@@ -227,12 +247,16 @@ class OpenAI extends llms_1.BaseLLM {
227
247
  writable: true,
228
248
  value: void 0
229
249
  });
250
+ model = model ?? this.model;
230
251
  this.openAIApiKey =
231
- fields?.openAIApiKey ?? (0, env_1.getEnvironmentVariable)("OPENAI_API_KEY");
252
+ fields?.apiKey ??
253
+ fields?.openAIApiKey ??
254
+ (0, env_1.getEnvironmentVariable)("OPENAI_API_KEY");
255
+ this.apiKey = this.openAIApiKey;
232
256
  this.azureOpenAIApiKey =
233
257
  fields?.azureOpenAIApiKey ??
234
258
  (0, env_1.getEnvironmentVariable)("AZURE_OPENAI_API_KEY");
235
- if (!this.azureOpenAIApiKey && !this.openAIApiKey) {
259
+ if (!this.azureOpenAIApiKey && !this.apiKey) {
236
260
  throw new Error("OpenAI or Azure OpenAI API key not found");
237
261
  }
238
262
  this.azureOpenAIApiInstanceName =
@@ -252,7 +276,8 @@ class OpenAI extends llms_1.BaseLLM {
252
276
  this.organization =
253
277
  fields?.configuration?.organization ??
254
278
  (0, env_1.getEnvironmentVariable)("OPENAI_ORGANIZATION");
255
- this.modelName = fields?.modelName ?? this.modelName;
279
+ this.modelName = model;
280
+ this.model = model;
256
281
  this.modelKwargs = fields?.modelKwargs ?? {};
257
282
  this.batchSize = fields?.batchSize ?? this.batchSize;
258
283
  this.timeout = fields?.timeout;
@@ -264,7 +289,8 @@ class OpenAI extends llms_1.BaseLLM {
264
289
  this.n = fields?.n ?? this.n;
265
290
  this.bestOf = fields?.bestOf ?? this.bestOf;
266
291
  this.logitBias = fields?.logitBias;
267
- this.stop = fields?.stop;
292
+ this.stop = fields?.stopSequences ?? fields?.stop;
293
+ this.stopSequences = fields?.stopSequences;
268
294
  this.user = fields?.user;
269
295
  this.streaming = fields?.streaming ?? false;
270
296
  if (this.streaming && this.bestOf && this.bestOf > 1) {
@@ -280,10 +306,10 @@ class OpenAI extends llms_1.BaseLLM {
280
306
  if (!this.azureOpenAIApiVersion) {
281
307
  throw new Error("Azure OpenAI API version not found");
282
308
  }
283
- this.openAIApiKey = this.openAIApiKey ?? "";
309
+ this.apiKey = this.apiKey ?? "";
284
310
  }
285
311
  this.clientConfig = {
286
- apiKey: this.openAIApiKey,
312
+ apiKey: this.apiKey,
287
313
  organization: this.organization,
288
314
  baseURL: configuration?.basePath ?? fields?.configuration?.basePath,
289
315
  dangerouslyAllowBrowser: true,
@@ -300,7 +326,7 @@ class OpenAI extends llms_1.BaseLLM {
300
326
  */
301
327
  invocationParams(options) {
302
328
  return {
303
- model: this.modelName,
329
+ model: this.model,
304
330
  temperature: this.temperature,
305
331
  max_tokens: this.maxTokens,
306
332
  top_p: this.topP,
@@ -309,7 +335,7 @@ class OpenAI extends llms_1.BaseLLM {
309
335
  n: this.n,
310
336
  best_of: this.bestOf,
311
337
  logit_bias: this.logitBias,
312
- stop: options?.stop ?? this.stop,
338
+ stop: options?.stop ?? this.stopSequences,
313
339
  user: this.user,
314
340
  stream: this.streaming,
315
341
  ...this.modelKwargs,
@@ -318,7 +344,7 @@ class OpenAI extends llms_1.BaseLLM {
318
344
  /** @ignore */
319
345
  _identifyingParams() {
320
346
  return {
321
- model_name: this.modelName,
347
+ model_name: this.model,
322
348
  ...this.invocationParams(),
323
349
  ...this.clientConfig,
324
350
  };
@@ -357,7 +383,7 @@ class OpenAI extends llms_1.BaseLLM {
357
383
  params.max_tokens = await (0, base_1.calculateMaxTokens)({
358
384
  prompt: prompts[0],
359
385
  // Cast here to allow for other models that may not fit the union
360
- modelName: this.modelName,
386
+ modelName: this.model,
361
387
  });
362
388
  }
363
389
  for (let i = 0; i < subPrompts.length; i += 1) {
package/dist/llms.d.ts CHANGED
@@ -55,13 +55,16 @@ export declare class OpenAI<CallOptions extends OpenAICallOptions = OpenAICallOp
55
55
  bestOf?: number;
56
56
  logitBias?: Record<string, number>;
57
57
  modelName: string;
58
+ model: string;
58
59
  modelKwargs?: OpenAIInput["modelKwargs"];
59
60
  batchSize: number;
60
61
  timeout?: number;
61
62
  stop?: string[];
63
+ stopSequences?: string[];
62
64
  user?: string;
63
65
  streaming: boolean;
64
66
  openAIApiKey?: string;
67
+ apiKey?: string;
65
68
  azureOpenAIApiVersion?: string;
66
69
  azureOpenAIApiKey?: string;
67
70
  azureOpenAIApiInstanceName?: string;
package/dist/llms.js CHANGED
@@ -50,6 +50,7 @@ export class OpenAI extends BaseLLM {
50
50
  get lc_secrets() {
51
51
  return {
52
52
  openAIApiKey: "OPENAI_API_KEY",
53
+ apiKey: "OPENAI_API_KEY",
53
54
  azureOpenAIApiKey: "AZURE_OPENAI_API_KEY",
54
55
  organization: "OPENAI_ORGANIZATION",
55
56
  };
@@ -58,6 +59,7 @@ export class OpenAI extends BaseLLM {
58
59
  return {
59
60
  modelName: "model",
60
61
  openAIApiKey: "openai_api_key",
62
+ apiKey: "openai_api_key",
61
63
  azureOpenAIApiVersion: "azure_openai_api_version",
62
64
  azureOpenAIApiKey: "azure_openai_api_key",
63
65
  azureOpenAIApiInstanceName: "azure_openai_api_instance_name",
@@ -67,9 +69,9 @@ export class OpenAI extends BaseLLM {
67
69
  constructor(fields,
68
70
  /** @deprecated */
69
71
  configuration) {
70
- if ((fields?.modelName?.startsWith("gpt-3.5-turbo") ||
71
- fields?.modelName?.startsWith("gpt-4")) &&
72
- !fields?.modelName?.includes("-instruct")) {
72
+ let model = fields?.model ?? fields?.modelName;
73
+ if ((model?.startsWith("gpt-3.5-turbo") || model?.startsWith("gpt-4")) &&
74
+ !model?.includes("-instruct")) {
73
75
  // eslint-disable-next-line no-constructor-return
74
76
  return new OpenAIChat(fields, configuration);
75
77
  }
@@ -134,6 +136,12 @@ export class OpenAI extends BaseLLM {
134
136
  writable: true,
135
137
  value: "gpt-3.5-turbo-instruct"
136
138
  });
139
+ Object.defineProperty(this, "model", {
140
+ enumerable: true,
141
+ configurable: true,
142
+ writable: true,
143
+ value: "gpt-3.5-turbo-instruct"
144
+ });
137
145
  Object.defineProperty(this, "modelKwargs", {
138
146
  enumerable: true,
139
147
  configurable: true,
@@ -158,6 +166,12 @@ export class OpenAI extends BaseLLM {
158
166
  writable: true,
159
167
  value: void 0
160
168
  });
169
+ Object.defineProperty(this, "stopSequences", {
170
+ enumerable: true,
171
+ configurable: true,
172
+ writable: true,
173
+ value: void 0
174
+ });
161
175
  Object.defineProperty(this, "user", {
162
176
  enumerable: true,
163
177
  configurable: true,
@@ -176,6 +190,12 @@ export class OpenAI extends BaseLLM {
176
190
  writable: true,
177
191
  value: void 0
178
192
  });
193
+ Object.defineProperty(this, "apiKey", {
194
+ enumerable: true,
195
+ configurable: true,
196
+ writable: true,
197
+ value: void 0
198
+ });
179
199
  Object.defineProperty(this, "azureOpenAIApiVersion", {
180
200
  enumerable: true,
181
201
  configurable: true,
@@ -224,12 +244,16 @@ export class OpenAI extends BaseLLM {
224
244
  writable: true,
225
245
  value: void 0
226
246
  });
247
+ model = model ?? this.model;
227
248
  this.openAIApiKey =
228
- fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY");
249
+ fields?.apiKey ??
250
+ fields?.openAIApiKey ??
251
+ getEnvironmentVariable("OPENAI_API_KEY");
252
+ this.apiKey = this.openAIApiKey;
229
253
  this.azureOpenAIApiKey =
230
254
  fields?.azureOpenAIApiKey ??
231
255
  getEnvironmentVariable("AZURE_OPENAI_API_KEY");
232
- if (!this.azureOpenAIApiKey && !this.openAIApiKey) {
256
+ if (!this.azureOpenAIApiKey && !this.apiKey) {
233
257
  throw new Error("OpenAI or Azure OpenAI API key not found");
234
258
  }
235
259
  this.azureOpenAIApiInstanceName =
@@ -249,7 +273,8 @@ export class OpenAI extends BaseLLM {
249
273
  this.organization =
250
274
  fields?.configuration?.organization ??
251
275
  getEnvironmentVariable("OPENAI_ORGANIZATION");
252
- this.modelName = fields?.modelName ?? this.modelName;
276
+ this.modelName = model;
277
+ this.model = model;
253
278
  this.modelKwargs = fields?.modelKwargs ?? {};
254
279
  this.batchSize = fields?.batchSize ?? this.batchSize;
255
280
  this.timeout = fields?.timeout;
@@ -261,7 +286,8 @@ export class OpenAI extends BaseLLM {
261
286
  this.n = fields?.n ?? this.n;
262
287
  this.bestOf = fields?.bestOf ?? this.bestOf;
263
288
  this.logitBias = fields?.logitBias;
264
- this.stop = fields?.stop;
289
+ this.stop = fields?.stopSequences ?? fields?.stop;
290
+ this.stopSequences = fields?.stopSequences;
265
291
  this.user = fields?.user;
266
292
  this.streaming = fields?.streaming ?? false;
267
293
  if (this.streaming && this.bestOf && this.bestOf > 1) {
@@ -277,10 +303,10 @@ export class OpenAI extends BaseLLM {
277
303
  if (!this.azureOpenAIApiVersion) {
278
304
  throw new Error("Azure OpenAI API version not found");
279
305
  }
280
- this.openAIApiKey = this.openAIApiKey ?? "";
306
+ this.apiKey = this.apiKey ?? "";
281
307
  }
282
308
  this.clientConfig = {
283
- apiKey: this.openAIApiKey,
309
+ apiKey: this.apiKey,
284
310
  organization: this.organization,
285
311
  baseURL: configuration?.basePath ?? fields?.configuration?.basePath,
286
312
  dangerouslyAllowBrowser: true,
@@ -297,7 +323,7 @@ export class OpenAI extends BaseLLM {
297
323
  */
298
324
  invocationParams(options) {
299
325
  return {
300
- model: this.modelName,
326
+ model: this.model,
301
327
  temperature: this.temperature,
302
328
  max_tokens: this.maxTokens,
303
329
  top_p: this.topP,
@@ -306,7 +332,7 @@ export class OpenAI extends BaseLLM {
306
332
  n: this.n,
307
333
  best_of: this.bestOf,
308
334
  logit_bias: this.logitBias,
309
- stop: options?.stop ?? this.stop,
335
+ stop: options?.stop ?? this.stopSequences,
310
336
  user: this.user,
311
337
  stream: this.streaming,
312
338
  ...this.modelKwargs,
@@ -315,7 +341,7 @@ export class OpenAI extends BaseLLM {
315
341
  /** @ignore */
316
342
  _identifyingParams() {
317
343
  return {
318
- model_name: this.modelName,
344
+ model_name: this.model,
319
345
  ...this.invocationParams(),
320
346
  ...this.clientConfig,
321
347
  };
@@ -354,7 +380,7 @@ export class OpenAI extends BaseLLM {
354
380
  params.max_tokens = await calculateMaxTokens({
355
381
  prompt: prompts[0],
356
382
  // Cast here to allow for other models that may not fit the union
357
- modelName: this.modelName,
383
+ modelName: this.model,
358
384
  });
359
385
  }
360
386
  for (let i = 0; i < subPrompts.length; i += 1) {
@@ -1,5 +1,5 @@
1
1
  import { test, expect, jest } from "@jest/globals";
2
- import { HumanMessage, ToolMessage } from "@langchain/core/messages";
2
+ import { AIMessage, HumanMessage, ToolMessage } from "@langchain/core/messages";
3
3
  import { InMemoryCache } from "@langchain/core/caches";
4
4
  import { ChatOpenAI } from "../chat_models.js";
5
5
  test("Test ChatOpenAI JSON mode", async () => {
@@ -60,7 +60,10 @@ test("Test ChatOpenAI tool calling", async () => {
60
60
  ["human", "What's the weather like in San Francisco, Tokyo, and Paris?"],
61
61
  ]);
62
62
  console.log(JSON.stringify(res));
63
- expect(res.additional_kwargs.tool_calls?.length).toBeGreaterThan(1);
63
+ expect(res.additional_kwargs.tool_calls?.length).toEqual(3);
64
+ expect(res.tool_calls?.[0].args).toEqual(JSON.parse(res.additional_kwargs.tool_calls?.[0].function.arguments ?? "{}"));
65
+ expect(res.tool_calls?.[1].args).toEqual(JSON.parse(res.additional_kwargs.tool_calls?.[1].function.arguments ?? "{}"));
66
+ expect(res.tool_calls?.[2].args).toEqual(JSON.parse(res.additional_kwargs.tool_calls?.[2].function.arguments ?? "{}"));
64
67
  });
65
68
  test("Test ChatOpenAI streaming logprobs", async () => {
66
69
  const model = new ChatOpenAI({
@@ -203,3 +206,54 @@ test("ChatOpenAI in JSON mode can cache generations", async () => {
203
206
  lookupSpy.mockRestore();
204
207
  updateSpy.mockRestore();
205
208
  });
209
+ test("Few shotting with tool calls", async () => {
210
+ const chat = new ChatOpenAI({
211
+ modelName: "gpt-3.5-turbo-1106",
212
+ temperature: 1,
213
+ }).bind({
214
+ tools: [
215
+ {
216
+ type: "function",
217
+ function: {
218
+ name: "get_current_weather",
219
+ description: "Get the current weather in a given location",
220
+ parameters: {
221
+ type: "object",
222
+ properties: {
223
+ location: {
224
+ type: "string",
225
+ description: "The city and state, e.g. San Francisco, CA",
226
+ },
227
+ unit: { type: "string", enum: ["celsius", "fahrenheit"] },
228
+ },
229
+ required: ["location"],
230
+ },
231
+ },
232
+ },
233
+ ],
234
+ tool_choice: "auto",
235
+ });
236
+ const res = await chat.invoke([
237
+ new HumanMessage("What is the weather in SF?"),
238
+ new AIMessage({
239
+ content: "",
240
+ tool_calls: [
241
+ {
242
+ id: "12345",
243
+ name: "get_current_weather",
244
+ args: {
245
+ location: "SF",
246
+ },
247
+ },
248
+ ],
249
+ }),
250
+ new ToolMessage({
251
+ tool_call_id: "12345",
252
+ content: "It is currently 24 degrees with hail in SF.",
253
+ }),
254
+ new AIMessage("It is currently 24 degrees in SF with hail in SF."),
255
+ new HumanMessage("What did you say the weather was?"),
256
+ ]);
257
+ console.log(res);
258
+ expect(res.content).toContain("24");
259
+ });
@@ -31,7 +31,7 @@ class DallEAPIWrapper extends tools_1.Tool {
31
31
  writable: true,
32
32
  value: void 0
33
33
  });
34
- Object.defineProperty(this, "modelName", {
34
+ Object.defineProperty(this, "model", {
35
35
  enumerable: true,
36
36
  configurable: true,
37
37
  writable: true,
@@ -73,7 +73,9 @@ class DallEAPIWrapper extends tools_1.Tool {
73
73
  writable: true,
74
74
  value: void 0
75
75
  });
76
- const openAIApiKey = fields?.openAIApiKey ?? (0, env_1.getEnvironmentVariable)("OPENAI_API_KEY");
76
+ const openAIApiKey = fields?.apiKey ??
77
+ fields?.openAIApiKey ??
78
+ (0, env_1.getEnvironmentVariable)("OPENAI_API_KEY");
77
79
  const organization = fields?.organization ?? (0, env_1.getEnvironmentVariable)("OPENAI_ORGANIZATION");
78
80
  const clientConfig = {
79
81
  apiKey: openAIApiKey,
@@ -81,7 +83,7 @@ class DallEAPIWrapper extends tools_1.Tool {
81
83
  dangerouslyAllowBrowser: true,
82
84
  };
83
85
  this.client = new openai_1.OpenAI(clientConfig);
84
- this.modelName = fields?.modelName ?? this.modelName;
86
+ this.model = fields?.model ?? fields?.modelName ?? this.model;
85
87
  this.style = fields?.style ?? this.style;
86
88
  this.quality = fields?.quality ?? this.quality;
87
89
  this.n = fields?.n ?? this.n;
@@ -92,7 +94,7 @@ class DallEAPIWrapper extends tools_1.Tool {
92
94
  /** @ignore */
93
95
  async _call(input) {
94
96
  const response = await this.client.images.generate({
95
- model: this.modelName,
97
+ model: this.model,
96
98
  prompt: input,
97
99
  n: this.n,
98
100
  size: this.size,
@@ -6,14 +6,26 @@ import { Tool, ToolParams } from "@langchain/core/tools";
6
6
  export interface DallEAPIWrapperParams extends ToolParams {
7
7
  /**
8
8
  * The OpenAI API key
9
+ * Alias for `apiKey`
9
10
  */
10
11
  openAIApiKey?: string;
12
+ /**
13
+ * The OpenAI API key
14
+ */
15
+ apiKey?: string;
11
16
  /**
12
17
  * The model to use.
18
+ * Alias for `model`
13
19
  * @params "dall-e-2" | "dall-e-3"
14
20
  * @default "dall-e-3"
15
21
  */
16
22
  modelName?: string;
23
+ /**
24
+ * The model to use.
25
+ * @params "dall-e-2" | "dall-e-3"
26
+ * @default "dall-e-3"
27
+ */
28
+ model?: string;
17
29
  /**
18
30
  * The style of the generated images. Must be one of vivid or natural.
19
31
  * Vivid causes the model to lean towards generating hyper-real and dramatic images.
@@ -66,7 +78,7 @@ export declare class DallEAPIWrapper extends Tool {
66
78
  description: string;
67
79
  protected client: OpenAIClient;
68
80
  static readonly toolName = "dalle_api_wrapper";
69
- private modelName;
81
+ private model;
70
82
  private style;
71
83
  private quality;
72
84
  private n;
@@ -28,7 +28,7 @@ export class DallEAPIWrapper extends Tool {
28
28
  writable: true,
29
29
  value: void 0
30
30
  });
31
- Object.defineProperty(this, "modelName", {
31
+ Object.defineProperty(this, "model", {
32
32
  enumerable: true,
33
33
  configurable: true,
34
34
  writable: true,
@@ -70,7 +70,9 @@ export class DallEAPIWrapper extends Tool {
70
70
  writable: true,
71
71
  value: void 0
72
72
  });
73
- const openAIApiKey = fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY");
73
+ const openAIApiKey = fields?.apiKey ??
74
+ fields?.openAIApiKey ??
75
+ getEnvironmentVariable("OPENAI_API_KEY");
74
76
  const organization = fields?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION");
75
77
  const clientConfig = {
76
78
  apiKey: openAIApiKey,
@@ -78,7 +80,7 @@ export class DallEAPIWrapper extends Tool {
78
80
  dangerouslyAllowBrowser: true,
79
81
  };
80
82
  this.client = new OpenAIClient(clientConfig);
81
- this.modelName = fields?.modelName ?? this.modelName;
83
+ this.model = fields?.model ?? fields?.modelName ?? this.model;
82
84
  this.style = fields?.style ?? this.style;
83
85
  this.quality = fields?.quality ?? this.quality;
84
86
  this.n = fields?.n ?? this.n;
@@ -89,7 +91,7 @@ export class DallEAPIWrapper extends Tool {
89
91
  /** @ignore */
90
92
  async _call(input) {
91
93
  const response = await this.client.images.generate({
92
- model: this.modelName,
94
+ model: this.model,
93
95
  prompt: input,
94
96
  n: this.n,
95
97
  size: this.size,
package/dist/types.d.ts CHANGED
@@ -24,15 +24,25 @@ export declare interface OpenAIBaseInput {
24
24
  user?: string;
25
25
  /** Whether to stream the results or not. Enabling disables tokenUsage reporting */
26
26
  streaming: boolean;
27
- /** Model name to use */
27
+ /**
28
+ * Model name to use
29
+ * Alias for `model`
30
+ */
28
31
  modelName: string;
32
+ /** Model name to use */
33
+ model: string;
29
34
  /** Holds any additional parameters that are valid to pass to {@link
30
35
  * https://platform.openai.com/docs/api-reference/completions/create |
31
36
  * `openai.createCompletion`} that are not explicitly specified on this class.
32
37
  */
33
38
  modelKwargs?: Record<string, any>;
34
- /** List of stop words to use when generating */
39
+ /**
40
+ * List of stop words to use when generating
41
+ * Alias for `stopSequences`
42
+ */
35
43
  stop?: string[];
44
+ /** List of stop words to use when generating */
45
+ stopSequences?: string[];
36
46
  /**
37
47
  * Timeout to use when making requests to OpenAI.
38
48
  */
@@ -40,8 +50,14 @@ export declare interface OpenAIBaseInput {
40
50
  /**
41
51
  * API key to use when making requests to OpenAI. Defaults to the value of
42
52
  * `OPENAI_API_KEY` environment variable.
53
+ * Alias for `apiKey`
43
54
  */
44
55
  openAIApiKey?: string;
56
+ /**
57
+ * API key to use when making requests to OpenAI. Defaults to the value of
58
+ * `OPENAI_API_KEY` environment variable.
59
+ */
60
+ apiKey?: string;
45
61
  }
46
62
  export type OpenAICoreRequestOptions<Req extends object = Record<string, unknown>> = {
47
63
  path?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/openai",
3
- "version": "0.0.26",
3
+ "version": "0.0.28",
4
4
  "description": "OpenAI integrations for LangChain.js",
5
5
  "type": "module",
6
6
  "engines": {
@@ -39,7 +39,7 @@
39
39
  "author": "LangChain",
40
40
  "license": "MIT",
41
41
  "dependencies": {
42
- "@langchain/core": "~0.1.45",
42
+ "@langchain/core": "~0.1.56",
43
43
  "js-tiktoken": "^1.0.7",
44
44
  "openai": "^4.32.1",
45
45
  "zod": "^3.22.4",