langchain 0.0.74 → 0.0.76
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/client.cjs +1 -0
- package/client.d.ts +1 -0
- package/client.js +1 -0
- package/dist/base_language/count_tokens.cjs +5 -21
- package/dist/base_language/count_tokens.d.ts +1 -6
- package/dist/base_language/count_tokens.js +4 -19
- package/dist/base_language/index.cjs +16 -24
- package/dist/base_language/index.d.ts +22 -3
- package/dist/base_language/index.js +17 -25
- package/dist/cache/redis.d.ts +3 -1
- package/dist/callbacks/base.d.ts +17 -3
- package/dist/callbacks/handlers/console.cjs +15 -28
- package/dist/callbacks/handlers/console.d.ts +11 -20
- package/dist/callbacks/handlers/console.js +14 -27
- package/dist/callbacks/handlers/initialize.cjs +8 -3
- package/dist/callbacks/handlers/initialize.d.ts +4 -2
- package/dist/callbacks/handlers/initialize.js +6 -2
- package/dist/callbacks/handlers/tracer.cjs +193 -0
- package/dist/callbacks/handlers/tracer.d.ts +65 -0
- package/dist/callbacks/handlers/tracer.js +189 -0
- package/dist/callbacks/handlers/tracer_langchain.cjs +163 -0
- package/dist/callbacks/handlers/tracer_langchain.d.ts +39 -0
- package/dist/callbacks/handlers/tracer_langchain.js +159 -0
- package/dist/callbacks/handlers/tracer_langchain_v1.cjs +202 -0
- package/dist/callbacks/handlers/tracer_langchain_v1.d.ts +57 -0
- package/dist/callbacks/handlers/tracer_langchain_v1.js +198 -0
- package/dist/callbacks/index.cjs +10 -5
- package/dist/callbacks/index.d.ts +5 -3
- package/dist/callbacks/index.js +5 -3
- package/dist/callbacks/manager.cjs +39 -9
- package/dist/callbacks/manager.d.ts +5 -2
- package/dist/callbacks/manager.js +40 -10
- package/dist/chains/llm_chain.cjs +17 -5
- package/dist/chains/llm_chain.d.ts +9 -3
- package/dist/chains/llm_chain.js +17 -5
- package/dist/chains/question_answering/map_reduce_prompts.cjs +5 -5
- package/dist/chains/question_answering/map_reduce_prompts.d.ts +1 -1
- package/dist/chains/question_answering/map_reduce_prompts.js +1 -1
- package/dist/chains/question_answering/refine_prompts.cjs +5 -5
- package/dist/chains/question_answering/refine_prompts.d.ts +1 -1
- package/dist/chains/question_answering/refine_prompts.js +1 -1
- package/dist/chains/question_answering/stuff_prompts.cjs +2 -2
- package/dist/chains/question_answering/stuff_prompts.d.ts +1 -1
- package/dist/chains/question_answering/stuff_prompts.js +1 -1
- package/dist/chains/sequential_chain.cjs +2 -2
- package/dist/chains/sequential_chain.d.ts +2 -2
- package/dist/chains/sequential_chain.js +2 -2
- package/dist/chains/sql_db/sql_db_prompt.cjs +20 -1
- package/dist/chains/sql_db/sql_db_prompt.d.ts +1 -0
- package/dist/chains/sql_db/sql_db_prompt.js +19 -0
- package/dist/chains/summarization/load.cjs +14 -5
- package/dist/chains/summarization/load.d.ts +7 -2
- package/dist/chains/summarization/load.js +14 -5
- package/dist/chat_models/anthropic.cjs +36 -9
- package/dist/chat_models/anthropic.d.ts +6 -3
- package/dist/chat_models/anthropic.js +36 -9
- package/dist/chat_models/base.cjs +40 -13
- package/dist/chat_models/base.d.ts +14 -7
- package/dist/chat_models/base.js +41 -14
- package/dist/chat_models/openai.cjs +20 -14
- package/dist/chat_models/openai.d.ts +2 -1
- package/dist/chat_models/openai.js +20 -14
- package/dist/client/index.cjs +5 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.js +1 -0
- package/dist/client/langchainplus.cjs +405 -0
- package/dist/client/langchainplus.d.ts +65 -0
- package/dist/client/langchainplus.js +398 -0
- package/dist/document_loaders/fs/unstructured.cjs +8 -0
- package/dist/document_loaders/fs/unstructured.d.ts +3 -0
- package/dist/document_loaders/fs/unstructured.js +8 -0
- package/dist/document_loaders/web/apify_dataset.cjs +64 -0
- package/dist/document_loaders/web/apify_dataset.d.ts +28 -0
- package/dist/document_loaders/web/apify_dataset.js +60 -0
- package/dist/embeddings/openai.cjs +2 -2
- package/dist/embeddings/openai.js +2 -2
- package/dist/llms/base.cjs +43 -17
- package/dist/llms/base.d.ts +16 -9
- package/dist/llms/base.js +44 -18
- package/dist/llms/cohere.cjs +3 -2
- package/dist/llms/cohere.d.ts +1 -1
- package/dist/llms/cohere.js +3 -2
- package/dist/llms/hf.cjs +2 -2
- package/dist/llms/hf.d.ts +1 -1
- package/dist/llms/hf.js +2 -2
- package/dist/llms/openai-chat.cjs +13 -14
- package/dist/llms/openai-chat.d.ts +2 -1
- package/dist/llms/openai-chat.js +13 -14
- package/dist/llms/openai.cjs +15 -13
- package/dist/llms/openai.d.ts +4 -3
- package/dist/llms/openai.js +15 -13
- package/dist/llms/replicate.cjs +2 -2
- package/dist/llms/replicate.d.ts +1 -1
- package/dist/llms/replicate.js +2 -2
- package/dist/memory/base.cjs +9 -1
- package/dist/memory/base.d.ts +1 -0
- package/dist/memory/base.js +7 -0
- package/dist/memory/entity_memory.cjs +151 -0
- package/dist/memory/entity_memory.d.ts +35 -0
- package/dist/memory/entity_memory.js +147 -0
- package/dist/memory/index.cjs +5 -1
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +2 -0
- package/dist/memory/prompt.cjs +84 -1
- package/dist/memory/prompt.d.ts +6 -0
- package/dist/memory/prompt.js +83 -0
- package/dist/memory/stores/entity/in_memory.cjs +32 -0
- package/dist/memory/stores/entity/in_memory.d.ts +10 -0
- package/dist/memory/stores/entity/in_memory.js +28 -0
- package/dist/prompts/index.cjs +6 -1
- package/dist/prompts/index.d.ts +1 -0
- package/dist/prompts/index.js +1 -0
- package/dist/{chains/prompt_selector.d.ts → prompts/selectors/conditional.d.ts} +4 -4
- package/dist/retrievers/document_compressors/chain_extract.cjs +9 -11
- package/dist/retrievers/document_compressors/chain_extract.js +9 -11
- package/dist/schema/index.cjs +13 -1
- package/dist/schema/index.d.ts +19 -0
- package/dist/schema/index.js +11 -0
- package/dist/stores/message/dynamodb.cjs +8 -6
- package/dist/stores/message/dynamodb.js +8 -6
- package/dist/stores/message/redis.cjs +69 -0
- package/dist/stores/message/redis.d.ts +18 -0
- package/dist/stores/message/redis.js +65 -0
- package/dist/stores/message/utils.cjs +30 -15
- package/dist/stores/message/utils.d.ts +4 -2
- package/dist/stores/message/utils.js +28 -14
- package/dist/text_splitter.cjs +3 -23
- package/dist/text_splitter.d.ts +1 -3
- package/dist/text_splitter.js +3 -23
- package/dist/tools/webbrowser.cjs +5 -7
- package/dist/tools/webbrowser.js +3 -5
- package/dist/types/openai-types.d.ts +3 -2
- package/dist/util/async_caller.cjs +16 -0
- package/dist/util/async_caller.d.ts +4 -0
- package/dist/util/async_caller.js +16 -0
- package/dist/util/axios-fetch-adapter.cjs +6 -0
- package/dist/util/axios-fetch-adapter.js +6 -0
- package/dist/util/env.cjs +39 -7
- package/dist/util/env.d.ts +19 -0
- package/dist/util/env.js +32 -6
- package/dist/util/sql_utils.cjs +18 -0
- package/dist/util/sql_utils.js +19 -1
- package/dist/util/tiktoken.cjs +26 -0
- package/dist/util/tiktoken.d.ts +9 -0
- package/dist/util/tiktoken.js +21 -0
- package/dist/vectorstores/redis.cjs +236 -0
- package/dist/vectorstores/redis.d.ts +80 -0
- package/dist/vectorstores/redis.js +232 -0
- package/document_loaders/web/apify_dataset.cjs +1 -0
- package/document_loaders/web/apify_dataset.d.ts +1 -0
- package/document_loaders/web/apify_dataset.js +1 -0
- package/package.json +41 -5
- package/stores/message/redis.cjs +1 -0
- package/stores/message/redis.d.ts +1 -0
- package/stores/message/redis.js +1 -0
- package/vectorstores/redis.cjs +1 -0
- package/vectorstores/redis.d.ts +1 -0
- package/vectorstores/redis.js +1 -0
- package/dist/callbacks/handlers/tracers.cjs +0 -341
- package/dist/callbacks/handlers/tracers.d.ts +0 -100
- package/dist/callbacks/handlers/tracers.js +0 -336
- /package/dist/{chains/prompt_selector.cjs → prompts/selectors/conditional.cjs} +0 -0
- /package/dist/{chains/prompt_selector.js → prompts/selectors/conditional.js} +0 -0
|
@@ -3,39 +3,48 @@ import { StuffDocumentsChain, MapReduceDocumentsChain, RefineDocumentsChain, } f
|
|
|
3
3
|
import { DEFAULT_PROMPT } from "./stuff_prompts.js";
|
|
4
4
|
import { REFINE_PROMPT } from "./refine_prompts.js";
|
|
5
5
|
export const loadSummarizationChain = (llm, params = { type: "map_reduce" }) => {
|
|
6
|
+
const { verbose } = params;
|
|
6
7
|
if (params.type === "stuff") {
|
|
7
8
|
const { prompt = DEFAULT_PROMPT } = params;
|
|
8
|
-
const llmChain = new LLMChain({ prompt, llm });
|
|
9
|
+
const llmChain = new LLMChain({ prompt, llm, verbose });
|
|
9
10
|
const chain = new StuffDocumentsChain({
|
|
10
11
|
llmChain,
|
|
11
12
|
documentVariableName: "text",
|
|
13
|
+
verbose,
|
|
12
14
|
});
|
|
13
15
|
return chain;
|
|
14
16
|
}
|
|
15
17
|
if (params.type === "map_reduce") {
|
|
16
18
|
const { combineMapPrompt = DEFAULT_PROMPT, combinePrompt = DEFAULT_PROMPT, returnIntermediateSteps, } = params;
|
|
17
|
-
const llmChain = new LLMChain({ prompt: combineMapPrompt, llm });
|
|
18
|
-
const combineLLMChain = new LLMChain({
|
|
19
|
+
const llmChain = new LLMChain({ prompt: combineMapPrompt, llm, verbose });
|
|
20
|
+
const combineLLMChain = new LLMChain({
|
|
21
|
+
prompt: combinePrompt,
|
|
22
|
+
llm,
|
|
23
|
+
verbose,
|
|
24
|
+
});
|
|
19
25
|
const combineDocumentChain = new StuffDocumentsChain({
|
|
20
26
|
llmChain: combineLLMChain,
|
|
21
27
|
documentVariableName: "text",
|
|
28
|
+
verbose,
|
|
22
29
|
});
|
|
23
30
|
const chain = new MapReduceDocumentsChain({
|
|
24
31
|
llmChain,
|
|
25
32
|
combineDocumentChain,
|
|
26
33
|
documentVariableName: "text",
|
|
27
34
|
returnIntermediateSteps,
|
|
35
|
+
verbose,
|
|
28
36
|
});
|
|
29
37
|
return chain;
|
|
30
38
|
}
|
|
31
39
|
if (params.type === "refine") {
|
|
32
40
|
const { refinePrompt = REFINE_PROMPT, questionPrompt = DEFAULT_PROMPT } = params;
|
|
33
|
-
const llmChain = new LLMChain({ prompt: questionPrompt, llm });
|
|
34
|
-
const refineLLMChain = new LLMChain({ prompt: refinePrompt, llm });
|
|
41
|
+
const llmChain = new LLMChain({ prompt: questionPrompt, llm, verbose });
|
|
42
|
+
const refineLLMChain = new LLMChain({ prompt: refinePrompt, llm, verbose });
|
|
35
43
|
const chain = new RefineDocumentsChain({
|
|
36
44
|
llmChain,
|
|
37
45
|
refineLLMChain,
|
|
38
46
|
documentVariableName: "text",
|
|
47
|
+
verbose,
|
|
39
48
|
});
|
|
40
49
|
return chain;
|
|
41
50
|
}
|
|
@@ -31,6 +31,9 @@ const DEFAULT_STOP_SEQUENCES = [sdk_1.HUMAN_PROMPT];
|
|
|
31
31
|
*
|
|
32
32
|
*/
|
|
33
33
|
class ChatAnthropic extends base_js_1.BaseChatModel {
|
|
34
|
+
get callKeys() {
|
|
35
|
+
return ["stop", "signal", "options"];
|
|
36
|
+
}
|
|
34
37
|
constructor(fields) {
|
|
35
38
|
super(fields ?? {});
|
|
36
39
|
Object.defineProperty(this, "apiKey", {
|
|
@@ -160,18 +163,18 @@ class ChatAnthropic extends base_js_1.BaseChatModel {
|
|
|
160
163
|
.join("") + sdk_1.AI_PROMPT);
|
|
161
164
|
}
|
|
162
165
|
/** @ignore */
|
|
163
|
-
async _generate(messages,
|
|
164
|
-
if (this.stopSequences &&
|
|
166
|
+
async _generate(messages, options, runManager) {
|
|
167
|
+
if (this.stopSequences && options.stop) {
|
|
165
168
|
throw new Error(`"stopSequence" parameter found in input and default params`);
|
|
166
169
|
}
|
|
167
170
|
const params = this.invocationParams();
|
|
168
|
-
params.stop_sequences =
|
|
169
|
-
?
|
|
171
|
+
params.stop_sequences = options.stop
|
|
172
|
+
? options.stop.concat(DEFAULT_STOP_SEQUENCES)
|
|
170
173
|
: params.stop_sequences;
|
|
171
174
|
const response = await this.completionWithRetry({
|
|
172
175
|
...params,
|
|
173
176
|
prompt: this.formatMessagesAsPrompt(messages),
|
|
174
|
-
}, runManager);
|
|
177
|
+
}, { signal: options.signal }, runManager);
|
|
175
178
|
const generations = response.completion
|
|
176
179
|
.split(sdk_1.AI_PROMPT)
|
|
177
180
|
.map((message) => ({
|
|
@@ -183,7 +186,7 @@ class ChatAnthropic extends base_js_1.BaseChatModel {
|
|
|
183
186
|
};
|
|
184
187
|
}
|
|
185
188
|
/** @ignore */
|
|
186
|
-
async completionWithRetry(request, runManager) {
|
|
189
|
+
async completionWithRetry(request, options, runManager) {
|
|
187
190
|
if (!this.apiKey) {
|
|
188
191
|
throw new Error("Missing Anthropic API key.");
|
|
189
192
|
}
|
|
@@ -194,7 +197,8 @@ class ChatAnthropic extends base_js_1.BaseChatModel {
|
|
|
194
197
|
}
|
|
195
198
|
makeCompletionRequest = async () => {
|
|
196
199
|
let currentCompletion = "";
|
|
197
|
-
return this.streamingClient
|
|
200
|
+
return (this.streamingClient
|
|
201
|
+
.completeStream(request, {
|
|
198
202
|
onUpdate: (data) => {
|
|
199
203
|
if (data.stop_reason) {
|
|
200
204
|
return;
|
|
@@ -207,14 +211,37 @@ class ChatAnthropic extends base_js_1.BaseChatModel {
|
|
|
207
211
|
void runManager?.handleLLMNewToken(delta ?? "");
|
|
208
212
|
}
|
|
209
213
|
},
|
|
210
|
-
|
|
214
|
+
signal: options.signal,
|
|
215
|
+
})
|
|
216
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
217
|
+
.catch((e) => {
|
|
218
|
+
// Anthropic doesn't actually throw JavaScript error objects at the moment.
|
|
219
|
+
// We convert the error so the async caller can recognize it correctly.
|
|
220
|
+
if (e?.name === "AbortError") {
|
|
221
|
+
throw new Error(`${e.name}: ${e.message}`);
|
|
222
|
+
}
|
|
223
|
+
throw e;
|
|
224
|
+
}));
|
|
211
225
|
};
|
|
212
226
|
}
|
|
213
227
|
else {
|
|
214
228
|
if (!this.batchClient) {
|
|
215
229
|
this.batchClient = new sdk_1.Client(this.apiKey);
|
|
216
230
|
}
|
|
217
|
-
makeCompletionRequest = async () => this.batchClient
|
|
231
|
+
makeCompletionRequest = async () => this.batchClient
|
|
232
|
+
.complete(request, {
|
|
233
|
+
signal: options.signal,
|
|
234
|
+
})
|
|
235
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
236
|
+
.catch((e) => {
|
|
237
|
+
console.log(e);
|
|
238
|
+
// Anthropic doesn't actually throw JavaScript error objects at the moment.
|
|
239
|
+
// We convert the error so the async caller can recognize it correctly.
|
|
240
|
+
if (e?.type === "aborted") {
|
|
241
|
+
throw new Error(`${e.name}: ${e.message}`);
|
|
242
|
+
}
|
|
243
|
+
throw e;
|
|
244
|
+
});
|
|
218
245
|
}
|
|
219
246
|
return this.caller.call(makeCompletionRequest);
|
|
220
247
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { SamplingParameters } from "@anthropic-ai/sdk";
|
|
2
2
|
import { BaseChatModel, BaseChatModelParams } from "./base.js";
|
|
3
3
|
import { BaseChatMessage, ChatResult } from "../schema/index.js";
|
|
4
4
|
import { CallbackManagerForLLMRun } from "../callbacks/manager.js";
|
|
5
|
+
import { BaseLanguageModelCallOptions } from "../base_language/index.js";
|
|
5
6
|
/**
|
|
6
7
|
* Input to AnthropicChat class.
|
|
7
8
|
*/
|
|
@@ -60,6 +61,8 @@ type Kwargs = Record<string, any>;
|
|
|
60
61
|
*
|
|
61
62
|
*/
|
|
62
63
|
export declare class ChatAnthropic extends BaseChatModel implements AnthropicInput {
|
|
64
|
+
CallOptions: BaseLanguageModelCallOptions;
|
|
65
|
+
get callKeys(): string[];
|
|
63
66
|
apiKey?: string;
|
|
64
67
|
temperature: number;
|
|
65
68
|
topK: number;
|
|
@@ -108,9 +111,9 @@ export declare class ChatAnthropic extends BaseChatModel implements AnthropicInp
|
|
|
108
111
|
};
|
|
109
112
|
private formatMessagesAsPrompt;
|
|
110
113
|
/** @ignore */
|
|
111
|
-
_generate(messages: BaseChatMessage[],
|
|
114
|
+
_generate(messages: BaseChatMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
|
|
112
115
|
/** @ignore */
|
|
113
|
-
completionWithRetry
|
|
116
|
+
private completionWithRetry;
|
|
114
117
|
_llmType(): string;
|
|
115
118
|
/** @ignore */
|
|
116
119
|
_combineLLMOutput(): never[];
|
|
@@ -28,6 +28,9 @@ const DEFAULT_STOP_SEQUENCES = [HUMAN_PROMPT];
|
|
|
28
28
|
*
|
|
29
29
|
*/
|
|
30
30
|
export class ChatAnthropic extends BaseChatModel {
|
|
31
|
+
get callKeys() {
|
|
32
|
+
return ["stop", "signal", "options"];
|
|
33
|
+
}
|
|
31
34
|
constructor(fields) {
|
|
32
35
|
super(fields ?? {});
|
|
33
36
|
Object.defineProperty(this, "apiKey", {
|
|
@@ -157,18 +160,18 @@ export class ChatAnthropic extends BaseChatModel {
|
|
|
157
160
|
.join("") + AI_PROMPT);
|
|
158
161
|
}
|
|
159
162
|
/** @ignore */
|
|
160
|
-
async _generate(messages,
|
|
161
|
-
if (this.stopSequences &&
|
|
163
|
+
async _generate(messages, options, runManager) {
|
|
164
|
+
if (this.stopSequences && options.stop) {
|
|
162
165
|
throw new Error(`"stopSequence" parameter found in input and default params`);
|
|
163
166
|
}
|
|
164
167
|
const params = this.invocationParams();
|
|
165
|
-
params.stop_sequences =
|
|
166
|
-
?
|
|
168
|
+
params.stop_sequences = options.stop
|
|
169
|
+
? options.stop.concat(DEFAULT_STOP_SEQUENCES)
|
|
167
170
|
: params.stop_sequences;
|
|
168
171
|
const response = await this.completionWithRetry({
|
|
169
172
|
...params,
|
|
170
173
|
prompt: this.formatMessagesAsPrompt(messages),
|
|
171
|
-
}, runManager);
|
|
174
|
+
}, { signal: options.signal }, runManager);
|
|
172
175
|
const generations = response.completion
|
|
173
176
|
.split(AI_PROMPT)
|
|
174
177
|
.map((message) => ({
|
|
@@ -180,7 +183,7 @@ export class ChatAnthropic extends BaseChatModel {
|
|
|
180
183
|
};
|
|
181
184
|
}
|
|
182
185
|
/** @ignore */
|
|
183
|
-
async completionWithRetry(request, runManager) {
|
|
186
|
+
async completionWithRetry(request, options, runManager) {
|
|
184
187
|
if (!this.apiKey) {
|
|
185
188
|
throw new Error("Missing Anthropic API key.");
|
|
186
189
|
}
|
|
@@ -191,7 +194,8 @@ export class ChatAnthropic extends BaseChatModel {
|
|
|
191
194
|
}
|
|
192
195
|
makeCompletionRequest = async () => {
|
|
193
196
|
let currentCompletion = "";
|
|
194
|
-
return this.streamingClient
|
|
197
|
+
return (this.streamingClient
|
|
198
|
+
.completeStream(request, {
|
|
195
199
|
onUpdate: (data) => {
|
|
196
200
|
if (data.stop_reason) {
|
|
197
201
|
return;
|
|
@@ -204,14 +208,37 @@ export class ChatAnthropic extends BaseChatModel {
|
|
|
204
208
|
void runManager?.handleLLMNewToken(delta ?? "");
|
|
205
209
|
}
|
|
206
210
|
},
|
|
207
|
-
|
|
211
|
+
signal: options.signal,
|
|
212
|
+
})
|
|
213
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
214
|
+
.catch((e) => {
|
|
215
|
+
// Anthropic doesn't actually throw JavaScript error objects at the moment.
|
|
216
|
+
// We convert the error so the async caller can recognize it correctly.
|
|
217
|
+
if (e?.name === "AbortError") {
|
|
218
|
+
throw new Error(`${e.name}: ${e.message}`);
|
|
219
|
+
}
|
|
220
|
+
throw e;
|
|
221
|
+
}));
|
|
208
222
|
};
|
|
209
223
|
}
|
|
210
224
|
else {
|
|
211
225
|
if (!this.batchClient) {
|
|
212
226
|
this.batchClient = new AnthropicApi(this.apiKey);
|
|
213
227
|
}
|
|
214
|
-
makeCompletionRequest = async () => this.batchClient
|
|
228
|
+
makeCompletionRequest = async () => this.batchClient
|
|
229
|
+
.complete(request, {
|
|
230
|
+
signal: options.signal,
|
|
231
|
+
})
|
|
232
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
233
|
+
.catch((e) => {
|
|
234
|
+
console.log(e);
|
|
235
|
+
// Anthropic doesn't actually throw JavaScript error objects at the moment.
|
|
236
|
+
// We convert the error so the async caller can recognize it correctly.
|
|
237
|
+
if (e?.type === "aborted") {
|
|
238
|
+
throw new Error(`${e.name}: ${e.message}`);
|
|
239
|
+
}
|
|
240
|
+
throw e;
|
|
241
|
+
});
|
|
215
242
|
}
|
|
216
243
|
return this.caller.call(makeCompletionRequest);
|
|
217
244
|
}
|
|
@@ -3,20 +3,32 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.SimpleChatModel = exports.BaseChatModel = void 0;
|
|
4
4
|
const index_js_1 = require("../schema/index.cjs");
|
|
5
5
|
const index_js_2 = require("../base_language/index.cjs");
|
|
6
|
-
const base_js_1 = require("../memory/base.cjs");
|
|
7
6
|
const manager_js_1 = require("../callbacks/manager.cjs");
|
|
8
7
|
class BaseChatModel extends index_js_2.BaseLanguageModel {
|
|
9
8
|
constructor(fields) {
|
|
10
9
|
super(fields);
|
|
11
10
|
}
|
|
12
|
-
async generate(messages,
|
|
11
|
+
async generate(messages, options, callbacks) {
|
|
13
12
|
const generations = [];
|
|
14
13
|
const llmOutputs = [];
|
|
15
|
-
|
|
14
|
+
let parsedOptions;
|
|
15
|
+
if (Array.isArray(options)) {
|
|
16
|
+
parsedOptions = { stop: options };
|
|
17
|
+
}
|
|
18
|
+
else if (options?.timeout && !options.signal) {
|
|
19
|
+
parsedOptions = {
|
|
20
|
+
...options,
|
|
21
|
+
signal: AbortSignal.timeout(options.timeout),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
parsedOptions = options ?? {};
|
|
26
|
+
}
|
|
16
27
|
const callbackManager_ = await manager_js_1.CallbackManager.configure(callbacks, this.callbacks, { verbose: this.verbose });
|
|
17
|
-
const
|
|
28
|
+
const invocationParams = { invocation_params: this?.invocationParams() };
|
|
29
|
+
const runManager = await callbackManager_?.handleChatModelStart({ name: this._llmType() }, messages, undefined, undefined, invocationParams);
|
|
18
30
|
try {
|
|
19
|
-
const results = await Promise.all(messages.map((messageList) => this._generate(messageList,
|
|
31
|
+
const results = await Promise.all(messages.map((messageList) => this._generate(messageList, parsedOptions, runManager)));
|
|
20
32
|
for (const result of results) {
|
|
21
33
|
if (result.llmOutput) {
|
|
22
34
|
llmOutputs.push(result.llmOutput);
|
|
@@ -41,27 +53,42 @@ class BaseChatModel extends index_js_2.BaseLanguageModel {
|
|
|
41
53
|
});
|
|
42
54
|
return output;
|
|
43
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* Get the parameters used to invoke the model
|
|
58
|
+
*/
|
|
59
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
60
|
+
invocationParams() {
|
|
61
|
+
return {};
|
|
62
|
+
}
|
|
44
63
|
_modelType() {
|
|
45
64
|
return "base_chat_model";
|
|
46
65
|
}
|
|
47
|
-
async generatePrompt(promptValues,
|
|
66
|
+
async generatePrompt(promptValues, options, callbacks) {
|
|
48
67
|
const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages());
|
|
49
|
-
return this.generate(promptMessages,
|
|
68
|
+
return this.generate(promptMessages, options, callbacks);
|
|
50
69
|
}
|
|
51
|
-
async call(messages,
|
|
52
|
-
const result = await this.generate([messages],
|
|
70
|
+
async call(messages, options, callbacks) {
|
|
71
|
+
const result = await this.generate([messages], options, callbacks);
|
|
53
72
|
const generations = result.generations;
|
|
54
73
|
return generations[0][0].message;
|
|
55
74
|
}
|
|
56
|
-
async callPrompt(promptValue,
|
|
75
|
+
async callPrompt(promptValue, options, callbacks) {
|
|
57
76
|
const promptMessages = promptValue.toChatMessages();
|
|
58
|
-
return this.call(promptMessages,
|
|
77
|
+
return this.call(promptMessages, options, callbacks);
|
|
78
|
+
}
|
|
79
|
+
async predictMessages(messages, options, callbacks) {
|
|
80
|
+
return this.call(messages, options, callbacks);
|
|
81
|
+
}
|
|
82
|
+
async predict(text, options, callbacks) {
|
|
83
|
+
const message = new index_js_1.HumanChatMessage(text);
|
|
84
|
+
const result = await this.call([message], options, callbacks);
|
|
85
|
+
return result.text;
|
|
59
86
|
}
|
|
60
87
|
}
|
|
61
88
|
exports.BaseChatModel = BaseChatModel;
|
|
62
89
|
class SimpleChatModel extends BaseChatModel {
|
|
63
|
-
async _generate(messages,
|
|
64
|
-
const text = await this._call(messages,
|
|
90
|
+
async _generate(messages, options, runManager) {
|
|
91
|
+
const text = await this._call(messages, options, runManager);
|
|
65
92
|
const message = new index_js_1.AIChatMessage(text);
|
|
66
93
|
return {
|
|
67
94
|
generations: [
|
|
@@ -13,17 +13,24 @@ export type BaseChatModelParams = BaseLanguageModelParams;
|
|
|
13
13
|
export type BaseChatModelCallOptions = BaseLanguageModelCallOptions;
|
|
14
14
|
export declare abstract class BaseChatModel extends BaseLanguageModel {
|
|
15
15
|
CallOptions: BaseChatModelCallOptions;
|
|
16
|
+
ParsedCallOptions: Omit<this["CallOptions"], "timeout">;
|
|
16
17
|
constructor(fields: BaseChatModelParams);
|
|
17
18
|
abstract _combineLLMOutput?(...llmOutputs: LLMResult["llmOutput"][]): LLMResult["llmOutput"];
|
|
18
|
-
generate(messages: BaseChatMessage[][],
|
|
19
|
+
generate(messages: BaseChatMessage[][], options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<LLMResult>;
|
|
20
|
+
/**
|
|
21
|
+
* Get the parameters used to invoke the model
|
|
22
|
+
*/
|
|
23
|
+
invocationParams(): any;
|
|
19
24
|
_modelType(): string;
|
|
20
25
|
abstract _llmType(): string;
|
|
21
|
-
generatePrompt(promptValues: BasePromptValue[],
|
|
22
|
-
abstract _generate(messages: BaseChatMessage[],
|
|
23
|
-
call(messages: BaseChatMessage[],
|
|
24
|
-
callPrompt(promptValue: BasePromptValue,
|
|
26
|
+
generatePrompt(promptValues: BasePromptValue[], options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<LLMResult>;
|
|
27
|
+
abstract _generate(messages: BaseChatMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
|
|
28
|
+
call(messages: BaseChatMessage[], options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<BaseChatMessage>;
|
|
29
|
+
callPrompt(promptValue: BasePromptValue, options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<BaseChatMessage>;
|
|
30
|
+
predictMessages(messages: BaseChatMessage[], options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<BaseChatMessage>;
|
|
31
|
+
predict(text: string, options?: string[] | this["CallOptions"], callbacks?: Callbacks): Promise<string>;
|
|
25
32
|
}
|
|
26
33
|
export declare abstract class SimpleChatModel extends BaseChatModel {
|
|
27
|
-
abstract _call(messages: BaseChatMessage[],
|
|
28
|
-
_generate(messages: BaseChatMessage[],
|
|
34
|
+
abstract _call(messages: BaseChatMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<string>;
|
|
35
|
+
_generate(messages: BaseChatMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
|
|
29
36
|
}
|
package/dist/chat_models/base.js
CHANGED
|
@@ -1,19 +1,31 @@
|
|
|
1
|
-
import { AIChatMessage, RUN_KEY, } from "../schema/index.js";
|
|
1
|
+
import { AIChatMessage, HumanChatMessage, RUN_KEY, } from "../schema/index.js";
|
|
2
2
|
import { BaseLanguageModel, } from "../base_language/index.js";
|
|
3
|
-
import { getBufferString } from "../memory/base.js";
|
|
4
3
|
import { CallbackManager, } from "../callbacks/manager.js";
|
|
5
4
|
export class BaseChatModel extends BaseLanguageModel {
|
|
6
5
|
constructor(fields) {
|
|
7
6
|
super(fields);
|
|
8
7
|
}
|
|
9
|
-
async generate(messages,
|
|
8
|
+
async generate(messages, options, callbacks) {
|
|
10
9
|
const generations = [];
|
|
11
10
|
const llmOutputs = [];
|
|
12
|
-
|
|
11
|
+
let parsedOptions;
|
|
12
|
+
if (Array.isArray(options)) {
|
|
13
|
+
parsedOptions = { stop: options };
|
|
14
|
+
}
|
|
15
|
+
else if (options?.timeout && !options.signal) {
|
|
16
|
+
parsedOptions = {
|
|
17
|
+
...options,
|
|
18
|
+
signal: AbortSignal.timeout(options.timeout),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
parsedOptions = options ?? {};
|
|
23
|
+
}
|
|
13
24
|
const callbackManager_ = await CallbackManager.configure(callbacks, this.callbacks, { verbose: this.verbose });
|
|
14
|
-
const
|
|
25
|
+
const invocationParams = { invocation_params: this?.invocationParams() };
|
|
26
|
+
const runManager = await callbackManager_?.handleChatModelStart({ name: this._llmType() }, messages, undefined, undefined, invocationParams);
|
|
15
27
|
try {
|
|
16
|
-
const results = await Promise.all(messages.map((messageList) => this._generate(messageList,
|
|
28
|
+
const results = await Promise.all(messages.map((messageList) => this._generate(messageList, parsedOptions, runManager)));
|
|
17
29
|
for (const result of results) {
|
|
18
30
|
if (result.llmOutput) {
|
|
19
31
|
llmOutputs.push(result.llmOutput);
|
|
@@ -38,26 +50,41 @@ export class BaseChatModel extends BaseLanguageModel {
|
|
|
38
50
|
});
|
|
39
51
|
return output;
|
|
40
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* Get the parameters used to invoke the model
|
|
55
|
+
*/
|
|
56
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
57
|
+
invocationParams() {
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
41
60
|
_modelType() {
|
|
42
61
|
return "base_chat_model";
|
|
43
62
|
}
|
|
44
|
-
async generatePrompt(promptValues,
|
|
63
|
+
async generatePrompt(promptValues, options, callbacks) {
|
|
45
64
|
const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages());
|
|
46
|
-
return this.generate(promptMessages,
|
|
65
|
+
return this.generate(promptMessages, options, callbacks);
|
|
47
66
|
}
|
|
48
|
-
async call(messages,
|
|
49
|
-
const result = await this.generate([messages],
|
|
67
|
+
async call(messages, options, callbacks) {
|
|
68
|
+
const result = await this.generate([messages], options, callbacks);
|
|
50
69
|
const generations = result.generations;
|
|
51
70
|
return generations[0][0].message;
|
|
52
71
|
}
|
|
53
|
-
async callPrompt(promptValue,
|
|
72
|
+
async callPrompt(promptValue, options, callbacks) {
|
|
54
73
|
const promptMessages = promptValue.toChatMessages();
|
|
55
|
-
return this.call(promptMessages,
|
|
74
|
+
return this.call(promptMessages, options, callbacks);
|
|
75
|
+
}
|
|
76
|
+
async predictMessages(messages, options, callbacks) {
|
|
77
|
+
return this.call(messages, options, callbacks);
|
|
78
|
+
}
|
|
79
|
+
async predict(text, options, callbacks) {
|
|
80
|
+
const message = new HumanChatMessage(text);
|
|
81
|
+
const result = await this.call([message], options, callbacks);
|
|
82
|
+
return result.text;
|
|
56
83
|
}
|
|
57
84
|
}
|
|
58
85
|
export class SimpleChatModel extends BaseChatModel {
|
|
59
|
-
async _generate(messages,
|
|
60
|
-
const text = await this._call(messages,
|
|
86
|
+
async _generate(messages, options, runManager) {
|
|
87
|
+
const text = await this._call(messages, options, runManager);
|
|
61
88
|
const message = new AIChatMessage(text);
|
|
62
89
|
return {
|
|
63
90
|
generations: [
|
|
@@ -4,8 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.ChatOpenAI = void 0;
|
|
7
|
-
const browser_or_node_1 = require("browser-or-node");
|
|
8
7
|
const openai_1 = require("openai");
|
|
8
|
+
const env_js_1 = require("../util/env.cjs");
|
|
9
9
|
const axios_fetch_adapter_js_1 = __importDefault(require("../util/axios-fetch-adapter.cjs"));
|
|
10
10
|
const base_js_1 = require("./base.cjs");
|
|
11
11
|
const index_js_1 = require("../schema/index.cjs");
|
|
@@ -53,6 +53,9 @@ function openAIResponseToChatMessage(role, text) {
|
|
|
53
53
|
* if not explicitly available on this class.
|
|
54
54
|
*/
|
|
55
55
|
class ChatOpenAI extends base_js_1.BaseChatModel {
|
|
56
|
+
get callKeys() {
|
|
57
|
+
return ["stop", "signal", "timeout", "options"];
|
|
58
|
+
}
|
|
56
59
|
constructor(fields, configuration) {
|
|
57
60
|
super(fields ?? {});
|
|
58
61
|
Object.defineProperty(this, "temperature", {
|
|
@@ -259,19 +262,13 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
|
|
|
259
262
|
return this._identifyingParams();
|
|
260
263
|
}
|
|
261
264
|
/** @ignore */
|
|
262
|
-
async _generate(messages,
|
|
263
|
-
const stop = Array.isArray(stopOrOptions)
|
|
264
|
-
? stopOrOptions
|
|
265
|
-
: stopOrOptions?.stop;
|
|
266
|
-
const options = Array.isArray(stopOrOptions)
|
|
267
|
-
? {}
|
|
268
|
-
: stopOrOptions?.options ?? {};
|
|
265
|
+
async _generate(messages, options, runManager) {
|
|
269
266
|
const tokenUsage = {};
|
|
270
|
-
if (this.stop && stop) {
|
|
267
|
+
if (this.stop && options?.stop) {
|
|
271
268
|
throw new Error("Stop found in input and default params");
|
|
272
269
|
}
|
|
273
270
|
const params = this.invocationParams();
|
|
274
|
-
params.stop = stop ?? params.stop;
|
|
271
|
+
params.stop = options?.stop ?? params.stop;
|
|
275
272
|
const messagesMapped = messages.map((message) => ({
|
|
276
273
|
role: messageTypeToOpenAIRole(message._getType()),
|
|
277
274
|
content: message.text,
|
|
@@ -286,7 +283,8 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
|
|
|
286
283
|
...params,
|
|
287
284
|
messages: messagesMapped,
|
|
288
285
|
}, {
|
|
289
|
-
|
|
286
|
+
signal: options?.signal,
|
|
287
|
+
...options?.options,
|
|
290
288
|
adapter: axios_fetch_adapter_js_1.default,
|
|
291
289
|
responseType: "stream",
|
|
292
290
|
onmessage: (event) => {
|
|
@@ -352,7 +350,10 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
|
|
|
352
350
|
: await this.completionWithRetry({
|
|
353
351
|
...params,
|
|
354
352
|
messages: messagesMapped,
|
|
355
|
-
},
|
|
353
|
+
}, {
|
|
354
|
+
signal: options?.signal,
|
|
355
|
+
...options?.options,
|
|
356
|
+
});
|
|
356
357
|
const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, } = data.usage ?? {};
|
|
357
358
|
if (completionTokens) {
|
|
358
359
|
tokenUsage.completionTokens =
|
|
@@ -393,10 +394,15 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
|
|
|
393
394
|
}
|
|
394
395
|
const countPerMessage = await Promise.all(messages.map(async (message) => {
|
|
395
396
|
const textCount = await this.getNumTokens(message.text);
|
|
396
|
-
const
|
|
397
|
+
const roleCount = await this.getNumTokens(messageTypeToOpenAIRole(message._getType()));
|
|
398
|
+
const nameCount = message.name !== undefined
|
|
399
|
+
? tokensPerName + (await this.getNumTokens(message.name))
|
|
400
|
+
: 0;
|
|
401
|
+
const count = textCount + tokensPerMessage + roleCount + nameCount;
|
|
397
402
|
totalCount += count;
|
|
398
403
|
return count;
|
|
399
404
|
}));
|
|
405
|
+
totalCount += 3; // every reply is primed with <|start|>assistant<|message|>
|
|
400
406
|
return { totalCount, countPerMessage };
|
|
401
407
|
}
|
|
402
408
|
/** @ignore */
|
|
@@ -416,7 +422,7 @@ class ChatOpenAI extends base_js_1.BaseChatModel {
|
|
|
416
422
|
this.client = new openai_1.OpenAIApi(clientConfig);
|
|
417
423
|
}
|
|
418
424
|
const axiosOptions = {
|
|
419
|
-
adapter:
|
|
425
|
+
adapter: (0, env_js_1.isNode)() ? undefined : axios_fetch_adapter_js_1.default,
|
|
420
426
|
...this.clientConfig.baseOptions,
|
|
421
427
|
...options,
|
|
422
428
|
};
|
|
@@ -33,6 +33,7 @@ interface OpenAILLMOutput {
|
|
|
33
33
|
*/
|
|
34
34
|
export declare class ChatOpenAI extends BaseChatModel implements OpenAIChatInput, AzureOpenAIInput {
|
|
35
35
|
CallOptions: OpenAICallOptions;
|
|
36
|
+
get callKeys(): (keyof OpenAICallOptions)[];
|
|
36
37
|
temperature: number;
|
|
37
38
|
topP: number;
|
|
38
39
|
frequencyPenalty: number;
|
|
@@ -109,7 +110,7 @@ export declare class ChatOpenAI extends BaseChatModel implements OpenAIChatInput
|
|
|
109
110
|
model_name: string;
|
|
110
111
|
};
|
|
111
112
|
/** @ignore */
|
|
112
|
-
_generate(messages: BaseChatMessage[],
|
|
113
|
+
_generate(messages: BaseChatMessage[], options?: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
|
|
113
114
|
getNumTokensFromMessages(messages: BaseChatMessage[]): Promise<{
|
|
114
115
|
totalCount: number;
|
|
115
116
|
countPerMessage: number[];
|