@langchain/anthropic 0.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) Harrison Chase
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # langchain-anthropic
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/chat_models.cjs');
@@ -0,0 +1 @@
1
+ export * from './dist/chat_models.js'
package/chat_models.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/chat_models.js'
@@ -0,0 +1,351 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ChatAnthropic = exports.DEFAULT_STOP_SEQUENCES = void 0;
4
+ const sdk_1 = require("@anthropic-ai/sdk");
5
+ const messages_1 = require("langchain-core/messages");
6
+ const outputs_1 = require("langchain-core/outputs");
7
+ const env_1 = require("langchain-core/utils/env");
8
+ const chat_models_1 = require("langchain-core/language_models/chat_models");
9
+ /**
10
+ * Extracts the custom role of a generic chat message.
11
+ * @param message The chat message from which to extract the custom role.
12
+ * @returns The custom role of the chat message.
13
+ */
14
+ function extractGenericMessageCustomRole(message) {
15
+ if (message.role !== sdk_1.AI_PROMPT &&
16
+ message.role !== sdk_1.HUMAN_PROMPT &&
17
+ message.role !== "") {
18
+ console.warn(`Unknown message role: ${message.role}`);
19
+ }
20
+ return message.role;
21
+ }
22
+ /**
23
+ * Gets the Anthropic prompt from a base message.
24
+ * @param message The base message from which to get the Anthropic prompt.
25
+ * @returns The Anthropic prompt from the base message.
26
+ */
27
+ function getAnthropicPromptFromMessage(message) {
28
+ const type = message._getType();
29
+ switch (type) {
30
+ case "ai":
31
+ return sdk_1.AI_PROMPT;
32
+ case "human":
33
+ return sdk_1.HUMAN_PROMPT;
34
+ case "system":
35
+ return "";
36
+ case "generic": {
37
+ if (!messages_1.ChatMessage.isInstance(message))
38
+ throw new Error("Invalid generic chat message");
39
+ return extractGenericMessageCustomRole(message);
40
+ }
41
+ default:
42
+ throw new Error(`Unknown message type: ${type}`);
43
+ }
44
+ }
45
+ exports.DEFAULT_STOP_SEQUENCES = [sdk_1.HUMAN_PROMPT];
46
+ /**
47
+ * Wrapper around Anthropic large language models.
48
+ *
49
+ * To use you should have the `@anthropic-ai/sdk` package installed, with the
50
+ * `ANTHROPIC_API_KEY` environment variable set.
51
+ *
52
+ * @remarks
53
+ * Any parameters that are valid to be passed to {@link
54
+ * https://console.anthropic.com/docs/api/reference |
55
+ * `anthropic.complete`} can be passed through {@link invocationKwargs},
56
+ * even if not explicitly available on this class.
57
+ * @example
58
+ * ```typescript
59
+ * const model = new ChatAnthropic({
60
+ * temperature: 0.9,
61
+ * anthropicApiKey: 'YOUR-API-KEY',
62
+ * });
63
+ * const res = await model.invoke({ input: 'Hello!' });
64
+ * console.log(res);
65
+ * ```
66
+ */
67
+ class ChatAnthropic extends chat_models_1.BaseChatModel {
68
+ static lc_name() {
69
+ return "ChatAnthropic";
70
+ }
71
+ get lc_secrets() {
72
+ return {
73
+ anthropicApiKey: "ANTHROPIC_API_KEY",
74
+ };
75
+ }
76
+ get lc_aliases() {
77
+ return {
78
+ modelName: "model",
79
+ };
80
+ }
81
+ constructor(fields) {
82
+ super(fields ?? {});
83
+ Object.defineProperty(this, "lc_serializable", {
84
+ enumerable: true,
85
+ configurable: true,
86
+ writable: true,
87
+ value: true
88
+ });
89
+ Object.defineProperty(this, "anthropicApiKey", {
90
+ enumerable: true,
91
+ configurable: true,
92
+ writable: true,
93
+ value: void 0
94
+ });
95
+ Object.defineProperty(this, "apiUrl", {
96
+ enumerable: true,
97
+ configurable: true,
98
+ writable: true,
99
+ value: void 0
100
+ });
101
+ Object.defineProperty(this, "temperature", {
102
+ enumerable: true,
103
+ configurable: true,
104
+ writable: true,
105
+ value: 1
106
+ });
107
+ Object.defineProperty(this, "topK", {
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true,
111
+ value: -1
112
+ });
113
+ Object.defineProperty(this, "topP", {
114
+ enumerable: true,
115
+ configurable: true,
116
+ writable: true,
117
+ value: -1
118
+ });
119
+ Object.defineProperty(this, "maxTokensToSample", {
120
+ enumerable: true,
121
+ configurable: true,
122
+ writable: true,
123
+ value: 2048
124
+ });
125
+ Object.defineProperty(this, "modelName", {
126
+ enumerable: true,
127
+ configurable: true,
128
+ writable: true,
129
+ value: "claude-2"
130
+ });
131
+ Object.defineProperty(this, "invocationKwargs", {
132
+ enumerable: true,
133
+ configurable: true,
134
+ writable: true,
135
+ value: void 0
136
+ });
137
+ Object.defineProperty(this, "stopSequences", {
138
+ enumerable: true,
139
+ configurable: true,
140
+ writable: true,
141
+ value: void 0
142
+ });
143
+ Object.defineProperty(this, "streaming", {
144
+ enumerable: true,
145
+ configurable: true,
146
+ writable: true,
147
+ value: false
148
+ });
149
+ Object.defineProperty(this, "clientOptions", {
150
+ enumerable: true,
151
+ configurable: true,
152
+ writable: true,
153
+ value: void 0
154
+ });
155
+ // Used for non-streaming requests
156
+ Object.defineProperty(this, "batchClient", {
157
+ enumerable: true,
158
+ configurable: true,
159
+ writable: true,
160
+ value: void 0
161
+ });
162
+ // Used for streaming requests
163
+ Object.defineProperty(this, "streamingClient", {
164
+ enumerable: true,
165
+ configurable: true,
166
+ writable: true,
167
+ value: void 0
168
+ });
169
+ this.anthropicApiKey =
170
+ fields?.anthropicApiKey ?? (0, env_1.getEnvironmentVariable)("ANTHROPIC_API_KEY");
171
+ if (!this.anthropicApiKey) {
172
+ throw new Error("Anthropic API key not found");
173
+ }
174
+ // Support overriding the default API URL (i.e., https://api.anthropic.com)
175
+ this.apiUrl = fields?.anthropicApiUrl;
176
+ this.modelName = fields?.modelName ?? this.modelName;
177
+ this.invocationKwargs = fields?.invocationKwargs ?? {};
178
+ this.temperature = fields?.temperature ?? this.temperature;
179
+ this.topK = fields?.topK ?? this.topK;
180
+ this.topP = fields?.topP ?? this.topP;
181
+ this.maxTokensToSample =
182
+ fields?.maxTokensToSample ?? this.maxTokensToSample;
183
+ this.stopSequences = fields?.stopSequences ?? this.stopSequences;
184
+ this.streaming = fields?.streaming ?? false;
185
+ this.clientOptions = fields?.clientOptions ?? {};
186
+ }
187
+ /**
188
+ * Get the parameters used to invoke the model
189
+ */
190
+ invocationParams(options) {
191
+ return {
192
+ model: this.modelName,
193
+ temperature: this.temperature,
194
+ top_k: this.topK,
195
+ top_p: this.topP,
196
+ stop_sequences: options?.stop?.concat(exports.DEFAULT_STOP_SEQUENCES) ??
197
+ this.stopSequences ??
198
+ exports.DEFAULT_STOP_SEQUENCES,
199
+ max_tokens_to_sample: this.maxTokensToSample,
200
+ stream: this.streaming,
201
+ ...this.invocationKwargs,
202
+ };
203
+ }
204
+ /** @ignore */
205
+ _identifyingParams() {
206
+ return {
207
+ model_name: this.modelName,
208
+ ...this.invocationParams(),
209
+ };
210
+ }
211
+ /**
212
+ * Get the identifying parameters for the model
213
+ */
214
+ identifyingParams() {
215
+ return {
216
+ model_name: this.modelName,
217
+ ...this.invocationParams(),
218
+ };
219
+ }
220
+ async *_streamResponseChunks(messages, options, runManager) {
221
+ const params = this.invocationParams(options);
222
+ const stream = await this.createStreamWithRetry({
223
+ ...params,
224
+ prompt: this.formatMessagesAsPrompt(messages),
225
+ });
226
+ let modelSent = false;
227
+ let stopReasonSent = false;
228
+ for await (const data of stream) {
229
+ if (options.signal?.aborted) {
230
+ stream.controller.abort();
231
+ throw new Error("AbortError: User aborted the request.");
232
+ }
233
+ const additional_kwargs = {};
234
+ if (data.model && !modelSent) {
235
+ additional_kwargs.model = data.model;
236
+ modelSent = true;
237
+ }
238
+ else if (data.stop_reason && !stopReasonSent) {
239
+ additional_kwargs.stop_reason = data.stop_reason;
240
+ stopReasonSent = true;
241
+ }
242
+ const delta = data.completion ?? "";
243
+ yield new outputs_1.ChatGenerationChunk({
244
+ message: new messages_1.AIMessageChunk({
245
+ content: delta,
246
+ additional_kwargs,
247
+ }),
248
+ text: delta,
249
+ });
250
+ await runManager?.handleLLMNewToken(delta);
251
+ if (data.stop_reason) {
252
+ break;
253
+ }
254
+ }
255
+ }
256
+ /**
257
+ * Formats messages as a prompt for the model.
258
+ * @param messages The base messages to format as a prompt.
259
+ * @returns The formatted prompt.
260
+ */
261
+ formatMessagesAsPrompt(messages) {
262
+ return (messages
263
+ .map((message) => {
264
+ const messagePrompt = getAnthropicPromptFromMessage(message);
265
+ return `${messagePrompt} ${message.content}`;
266
+ })
267
+ .join("") + sdk_1.AI_PROMPT);
268
+ }
269
+ /** @ignore */
270
+ async _generate(messages, options, runManager) {
271
+ if (this.stopSequences && options.stop) {
272
+ throw new Error(`"stopSequence" parameter found in input and default params`);
273
+ }
274
+ const params = this.invocationParams(options);
275
+ let response;
276
+ if (params.stream) {
277
+ response = {
278
+ completion: "",
279
+ model: "",
280
+ stop_reason: "",
281
+ };
282
+ const stream = await this._streamResponseChunks(messages, options, runManager);
283
+ for await (const chunk of stream) {
284
+ response.completion += chunk.message.content;
285
+ response.model =
286
+ chunk.message.additional_kwargs.model ?? response.model;
287
+ response.stop_reason =
288
+ chunk.message.additional_kwargs.stop_reason ??
289
+ response.stop_reason;
290
+ }
291
+ }
292
+ else {
293
+ response = await this.completionWithRetry({
294
+ ...params,
295
+ prompt: this.formatMessagesAsPrompt(messages),
296
+ }, { signal: options.signal });
297
+ }
298
+ const generations = (response.completion ?? "")
299
+ .split(sdk_1.AI_PROMPT)
300
+ .map((message) => ({
301
+ text: message,
302
+ message: new messages_1.AIMessage(message),
303
+ }));
304
+ return {
305
+ generations,
306
+ };
307
+ }
308
+ /**
309
+ * Creates a streaming request with retry.
310
+ * @param request The parameters for creating a completion.
311
+ * @returns A streaming request.
312
+ */
313
+ async createStreamWithRetry(request) {
314
+ if (!this.streamingClient) {
315
+ const options = this.apiUrl ? { baseURL: this.apiUrl } : undefined;
316
+ this.streamingClient = new sdk_1.Anthropic({
317
+ ...this.clientOptions,
318
+ ...options,
319
+ apiKey: this.anthropicApiKey,
320
+ maxRetries: 0,
321
+ });
322
+ }
323
+ const makeCompletionRequest = async () => this.streamingClient.completions.create({ ...request, stream: true }, { headers: request.headers });
324
+ return this.caller.call(makeCompletionRequest);
325
+ }
326
+ /** @ignore */
327
+ async completionWithRetry(request, options) {
328
+ if (!this.anthropicApiKey) {
329
+ throw new Error("Missing Anthropic API key.");
330
+ }
331
+ if (!this.batchClient) {
332
+ const options = this.apiUrl ? { baseURL: this.apiUrl } : undefined;
333
+ this.batchClient = new sdk_1.Anthropic({
334
+ ...this.clientOptions,
335
+ ...options,
336
+ apiKey: this.anthropicApiKey,
337
+ maxRetries: 0,
338
+ });
339
+ }
340
+ const makeCompletionRequest = async () => this.batchClient.completions.create({ ...request, stream: false }, { headers: request.headers });
341
+ return this.caller.callWithOptions({ signal: options.signal }, makeCompletionRequest);
342
+ }
343
+ _llmType() {
344
+ return "anthropic";
345
+ }
346
+ /** @ignore */
347
+ _combineLLMOutput() {
348
+ return [];
349
+ }
350
+ }
351
+ exports.ChatAnthropic = ChatAnthropic;
@@ -0,0 +1,157 @@
1
+ import { Anthropic, ClientOptions } from "@anthropic-ai/sdk";
2
+ import type { CompletionCreateParams } from "@anthropic-ai/sdk/resources/completions";
3
+ import type { Stream } from "@anthropic-ai/sdk/streaming";
4
+ import { CallbackManagerForLLMRun } from "langchain-core/callbacks/manager";
5
+ import { type BaseMessage } from "langchain-core/messages";
6
+ import { ChatGenerationChunk, type ChatResult } from "langchain-core/outputs";
7
+ import { BaseChatModel, type BaseChatModelParams } from "langchain-core/language_models/chat_models";
8
+ import { type BaseLanguageModelCallOptions } from "langchain-core/language_models/base";
9
+ export declare const DEFAULT_STOP_SEQUENCES: string[];
10
+ /**
11
+ * Input to AnthropicChat class.
12
+ */
13
+ export interface AnthropicInput {
14
+ /** Amount of randomness injected into the response. Ranges
15
+ * from 0 to 1. Use temp closer to 0 for analytical /
16
+ * multiple choice, and temp closer to 1 for creative
17
+ * and generative tasks.
18
+ */
19
+ temperature?: number;
20
+ /** Only sample from the top K options for each subsequent
21
+ * token. Used to remove "long tail" low probability
22
+ * responses. Defaults to -1, which disables it.
23
+ */
24
+ topK?: number;
25
+ /** Does nucleus sampling, in which we compute the
26
+ * cumulative distribution over all the options for each
27
+ * subsequent token in decreasing probability order and
28
+ * cut it off once it reaches a particular probability
29
+ * specified by top_p. Defaults to -1, which disables it.
30
+ * Note that you should either alter temperature or top_p,
31
+ * but not both.
32
+ */
33
+ topP?: number;
34
+ /** A maximum number of tokens to generate before stopping. */
35
+ maxTokensToSample: number;
36
+ /** A list of strings upon which to stop generating.
37
+ * You probably want `["\n\nHuman:"]`, as that's the cue for
38
+ * the next turn in the dialog agent.
39
+ */
40
+ stopSequences?: string[];
41
+ /** Whether to stream the results or not */
42
+ streaming?: boolean;
43
+ /** Anthropic API key */
44
+ anthropicApiKey?: string;
45
+ /** Anthropic API URL */
46
+ anthropicApiUrl?: string;
47
+ /** Model name to use */
48
+ modelName: string;
49
+ /** Overridable Anthropic ClientOptions */
50
+ clientOptions: ClientOptions;
51
+ /** Holds any additional parameters that are valid to pass to {@link
52
+ * https://console.anthropic.com/docs/api/reference |
53
+ * `anthropic.complete`} that are not explicitly specified on this class.
54
+ */
55
+ invocationKwargs?: Kwargs;
56
+ }
57
+ /**
58
+ * A type representing additional parameters that can be passed to the
59
+ * Anthropic API.
60
+ */
61
+ type Kwargs = Record<string, any>;
62
+ /**
63
+ * Wrapper around Anthropic large language models.
64
+ *
65
+ * To use you should have the `@anthropic-ai/sdk` package installed, with the
66
+ * `ANTHROPIC_API_KEY` environment variable set.
67
+ *
68
+ * @remarks
69
+ * Any parameters that are valid to be passed to {@link
70
+ * https://console.anthropic.com/docs/api/reference |
71
+ * `anthropic.complete`} can be passed through {@link invocationKwargs},
72
+ * even if not explicitly available on this class.
73
+ * @example
74
+ * ```typescript
75
+ * const model = new ChatAnthropic({
76
+ * temperature: 0.9,
77
+ * anthropicApiKey: 'YOUR-API-KEY',
78
+ * });
79
+ * const res = await model.invoke({ input: 'Hello!' });
80
+ * console.log(res);
81
+ * ```
82
+ */
83
+ export declare class ChatAnthropic<CallOptions extends BaseLanguageModelCallOptions = BaseLanguageModelCallOptions> extends BaseChatModel<CallOptions> implements AnthropicInput {
84
+ static lc_name(): string;
85
+ get lc_secrets(): {
86
+ [key: string]: string;
87
+ } | undefined;
88
+ get lc_aliases(): Record<string, string>;
89
+ lc_serializable: boolean;
90
+ anthropicApiKey?: string;
91
+ apiUrl?: string;
92
+ temperature: number;
93
+ topK: number;
94
+ topP: number;
95
+ maxTokensToSample: number;
96
+ modelName: string;
97
+ invocationKwargs?: Kwargs;
98
+ stopSequences?: string[];
99
+ streaming: boolean;
100
+ clientOptions: ClientOptions;
101
+ protected batchClient: Anthropic;
102
+ protected streamingClient: Anthropic;
103
+ constructor(fields?: Partial<AnthropicInput> & BaseChatModelParams);
104
+ /**
105
+ * Get the parameters used to invoke the model
106
+ */
107
+ invocationParams(options?: this["ParsedCallOptions"]): Omit<CompletionCreateParams, "prompt"> & Kwargs;
108
+ /** @ignore */
109
+ _identifyingParams(): {
110
+ metadata?: Anthropic.Completions.CompletionCreateParams.Metadata | undefined;
111
+ stream?: boolean | undefined;
112
+ max_tokens_to_sample: number;
113
+ model: "claude-2" | (string & {}) | "claude-instant-1";
114
+ stop_sequences?: string[] | undefined;
115
+ temperature?: number | undefined;
116
+ top_k?: number | undefined;
117
+ top_p?: number | undefined;
118
+ model_name: string;
119
+ };
120
+ /**
121
+ * Get the identifying parameters for the model
122
+ */
123
+ identifyingParams(): {
124
+ metadata?: Anthropic.Completions.CompletionCreateParams.Metadata | undefined;
125
+ stream?: boolean | undefined;
126
+ max_tokens_to_sample: number;
127
+ model: "claude-2" | (string & {}) | "claude-instant-1";
128
+ stop_sequences?: string[] | undefined;
129
+ temperature?: number | undefined;
130
+ top_k?: number | undefined;
131
+ top_p?: number | undefined;
132
+ model_name: string;
133
+ };
134
+ _streamResponseChunks(messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
135
+ /**
136
+ * Formats messages as a prompt for the model.
137
+ * @param messages The base messages to format as a prompt.
138
+ * @returns The formatted prompt.
139
+ */
140
+ protected formatMessagesAsPrompt(messages: BaseMessage[]): string;
141
+ /** @ignore */
142
+ _generate(messages: BaseMessage[], options: this["ParsedCallOptions"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;
143
+ /**
144
+ * Creates a streaming request with retry.
145
+ * @param request The parameters for creating a completion.
146
+ * @returns A streaming request.
147
+ */
148
+ protected createStreamWithRetry(request: CompletionCreateParams & Kwargs): Promise<Stream<Anthropic.Completions.Completion>>;
149
+ /** @ignore */
150
+ protected completionWithRetry(request: CompletionCreateParams & Kwargs, options: {
151
+ signal?: AbortSignal;
152
+ }): Promise<Anthropic.Completions.Completion>;
153
+ _llmType(): string;
154
+ /** @ignore */
155
+ _combineLLMOutput(): never[];
156
+ }
157
+ export {};
@@ -0,0 +1,347 @@
1
+ import { Anthropic, AI_PROMPT, HUMAN_PROMPT, } from "@anthropic-ai/sdk";
2
+ import { AIMessage, AIMessageChunk, ChatMessage, } from "langchain-core/messages";
3
+ import { ChatGenerationChunk, } from "langchain-core/outputs";
4
+ import { getEnvironmentVariable } from "langchain-core/utils/env";
5
+ import { BaseChatModel, } from "langchain-core/language_models/chat_models";
6
+ /**
7
+ * Extracts the custom role of a generic chat message.
8
+ * @param message The chat message from which to extract the custom role.
9
+ * @returns The custom role of the chat message.
10
+ */
11
+ function extractGenericMessageCustomRole(message) {
12
+ if (message.role !== AI_PROMPT &&
13
+ message.role !== HUMAN_PROMPT &&
14
+ message.role !== "") {
15
+ console.warn(`Unknown message role: ${message.role}`);
16
+ }
17
+ return message.role;
18
+ }
19
+ /**
20
+ * Gets the Anthropic prompt from a base message.
21
+ * @param message The base message from which to get the Anthropic prompt.
22
+ * @returns The Anthropic prompt from the base message.
23
+ */
24
+ function getAnthropicPromptFromMessage(message) {
25
+ const type = message._getType();
26
+ switch (type) {
27
+ case "ai":
28
+ return AI_PROMPT;
29
+ case "human":
30
+ return HUMAN_PROMPT;
31
+ case "system":
32
+ return "";
33
+ case "generic": {
34
+ if (!ChatMessage.isInstance(message))
35
+ throw new Error("Invalid generic chat message");
36
+ return extractGenericMessageCustomRole(message);
37
+ }
38
+ default:
39
+ throw new Error(`Unknown message type: ${type}`);
40
+ }
41
+ }
42
+ export const DEFAULT_STOP_SEQUENCES = [HUMAN_PROMPT];
43
+ /**
44
+ * Wrapper around Anthropic large language models.
45
+ *
46
+ * To use you should have the `@anthropic-ai/sdk` package installed, with the
47
+ * `ANTHROPIC_API_KEY` environment variable set.
48
+ *
49
+ * @remarks
50
+ * Any parameters that are valid to be passed to {@link
51
+ * https://console.anthropic.com/docs/api/reference |
52
+ * `anthropic.complete`} can be passed through {@link invocationKwargs},
53
+ * even if not explicitly available on this class.
54
+ * @example
55
+ * ```typescript
56
+ * const model = new ChatAnthropic({
57
+ * temperature: 0.9,
58
+ * anthropicApiKey: 'YOUR-API-KEY',
59
+ * });
60
+ * const res = await model.invoke({ input: 'Hello!' });
61
+ * console.log(res);
62
+ * ```
63
+ */
64
+ export class ChatAnthropic extends BaseChatModel {
65
+ static lc_name() {
66
+ return "ChatAnthropic";
67
+ }
68
+ get lc_secrets() {
69
+ return {
70
+ anthropicApiKey: "ANTHROPIC_API_KEY",
71
+ };
72
+ }
73
+ get lc_aliases() {
74
+ return {
75
+ modelName: "model",
76
+ };
77
+ }
78
+ constructor(fields) {
79
+ super(fields ?? {});
80
+ Object.defineProperty(this, "lc_serializable", {
81
+ enumerable: true,
82
+ configurable: true,
83
+ writable: true,
84
+ value: true
85
+ });
86
+ Object.defineProperty(this, "anthropicApiKey", {
87
+ enumerable: true,
88
+ configurable: true,
89
+ writable: true,
90
+ value: void 0
91
+ });
92
+ Object.defineProperty(this, "apiUrl", {
93
+ enumerable: true,
94
+ configurable: true,
95
+ writable: true,
96
+ value: void 0
97
+ });
98
+ Object.defineProperty(this, "temperature", {
99
+ enumerable: true,
100
+ configurable: true,
101
+ writable: true,
102
+ value: 1
103
+ });
104
+ Object.defineProperty(this, "topK", {
105
+ enumerable: true,
106
+ configurable: true,
107
+ writable: true,
108
+ value: -1
109
+ });
110
+ Object.defineProperty(this, "topP", {
111
+ enumerable: true,
112
+ configurable: true,
113
+ writable: true,
114
+ value: -1
115
+ });
116
+ Object.defineProperty(this, "maxTokensToSample", {
117
+ enumerable: true,
118
+ configurable: true,
119
+ writable: true,
120
+ value: 2048
121
+ });
122
+ Object.defineProperty(this, "modelName", {
123
+ enumerable: true,
124
+ configurable: true,
125
+ writable: true,
126
+ value: "claude-2"
127
+ });
128
+ Object.defineProperty(this, "invocationKwargs", {
129
+ enumerable: true,
130
+ configurable: true,
131
+ writable: true,
132
+ value: void 0
133
+ });
134
+ Object.defineProperty(this, "stopSequences", {
135
+ enumerable: true,
136
+ configurable: true,
137
+ writable: true,
138
+ value: void 0
139
+ });
140
+ Object.defineProperty(this, "streaming", {
141
+ enumerable: true,
142
+ configurable: true,
143
+ writable: true,
144
+ value: false
145
+ });
146
+ Object.defineProperty(this, "clientOptions", {
147
+ enumerable: true,
148
+ configurable: true,
149
+ writable: true,
150
+ value: void 0
151
+ });
152
+ // Used for non-streaming requests
153
+ Object.defineProperty(this, "batchClient", {
154
+ enumerable: true,
155
+ configurable: true,
156
+ writable: true,
157
+ value: void 0
158
+ });
159
+ // Used for streaming requests
160
+ Object.defineProperty(this, "streamingClient", {
161
+ enumerable: true,
162
+ configurable: true,
163
+ writable: true,
164
+ value: void 0
165
+ });
166
+ this.anthropicApiKey =
167
+ fields?.anthropicApiKey ?? getEnvironmentVariable("ANTHROPIC_API_KEY");
168
+ if (!this.anthropicApiKey) {
169
+ throw new Error("Anthropic API key not found");
170
+ }
171
+ // Support overriding the default API URL (i.e., https://api.anthropic.com)
172
+ this.apiUrl = fields?.anthropicApiUrl;
173
+ this.modelName = fields?.modelName ?? this.modelName;
174
+ this.invocationKwargs = fields?.invocationKwargs ?? {};
175
+ this.temperature = fields?.temperature ?? this.temperature;
176
+ this.topK = fields?.topK ?? this.topK;
177
+ this.topP = fields?.topP ?? this.topP;
178
+ this.maxTokensToSample =
179
+ fields?.maxTokensToSample ?? this.maxTokensToSample;
180
+ this.stopSequences = fields?.stopSequences ?? this.stopSequences;
181
+ this.streaming = fields?.streaming ?? false;
182
+ this.clientOptions = fields?.clientOptions ?? {};
183
+ }
184
+ /**
185
+ * Get the parameters used to invoke the model
186
+ */
187
+ invocationParams(options) {
188
+ return {
189
+ model: this.modelName,
190
+ temperature: this.temperature,
191
+ top_k: this.topK,
192
+ top_p: this.topP,
193
+ stop_sequences: options?.stop?.concat(DEFAULT_STOP_SEQUENCES) ??
194
+ this.stopSequences ??
195
+ DEFAULT_STOP_SEQUENCES,
196
+ max_tokens_to_sample: this.maxTokensToSample,
197
+ stream: this.streaming,
198
+ ...this.invocationKwargs,
199
+ };
200
+ }
201
+ /** @ignore */
202
+ _identifyingParams() {
203
+ return {
204
+ model_name: this.modelName,
205
+ ...this.invocationParams(),
206
+ };
207
+ }
208
+ /**
209
+ * Get the identifying parameters for the model
210
+ */
211
+ identifyingParams() {
212
+ return {
213
+ model_name: this.modelName,
214
+ ...this.invocationParams(),
215
+ };
216
+ }
217
+ async *_streamResponseChunks(messages, options, runManager) {
218
+ const params = this.invocationParams(options);
219
+ const stream = await this.createStreamWithRetry({
220
+ ...params,
221
+ prompt: this.formatMessagesAsPrompt(messages),
222
+ });
223
+ let modelSent = false;
224
+ let stopReasonSent = false;
225
+ for await (const data of stream) {
226
+ if (options.signal?.aborted) {
227
+ stream.controller.abort();
228
+ throw new Error("AbortError: User aborted the request.");
229
+ }
230
+ const additional_kwargs = {};
231
+ if (data.model && !modelSent) {
232
+ additional_kwargs.model = data.model;
233
+ modelSent = true;
234
+ }
235
+ else if (data.stop_reason && !stopReasonSent) {
236
+ additional_kwargs.stop_reason = data.stop_reason;
237
+ stopReasonSent = true;
238
+ }
239
+ const delta = data.completion ?? "";
240
+ yield new ChatGenerationChunk({
241
+ message: new AIMessageChunk({
242
+ content: delta,
243
+ additional_kwargs,
244
+ }),
245
+ text: delta,
246
+ });
247
+ await runManager?.handleLLMNewToken(delta);
248
+ if (data.stop_reason) {
249
+ break;
250
+ }
251
+ }
252
+ }
253
+ /**
254
+ * Formats messages as a prompt for the model.
255
+ * @param messages The base messages to format as a prompt.
256
+ * @returns The formatted prompt.
257
+ */
258
+ formatMessagesAsPrompt(messages) {
259
+ return (messages
260
+ .map((message) => {
261
+ const messagePrompt = getAnthropicPromptFromMessage(message);
262
+ return `${messagePrompt} ${message.content}`;
263
+ })
264
+ .join("") + AI_PROMPT);
265
+ }
266
+ /** @ignore */
267
+ async _generate(messages, options, runManager) {
268
+ if (this.stopSequences && options.stop) {
269
+ throw new Error(`"stopSequence" parameter found in input and default params`);
270
+ }
271
+ const params = this.invocationParams(options);
272
+ let response;
273
+ if (params.stream) {
274
+ response = {
275
+ completion: "",
276
+ model: "",
277
+ stop_reason: "",
278
+ };
279
+ const stream = await this._streamResponseChunks(messages, options, runManager);
280
+ for await (const chunk of stream) {
281
+ response.completion += chunk.message.content;
282
+ response.model =
283
+ chunk.message.additional_kwargs.model ?? response.model;
284
+ response.stop_reason =
285
+ chunk.message.additional_kwargs.stop_reason ??
286
+ response.stop_reason;
287
+ }
288
+ }
289
+ else {
290
+ response = await this.completionWithRetry({
291
+ ...params,
292
+ prompt: this.formatMessagesAsPrompt(messages),
293
+ }, { signal: options.signal });
294
+ }
295
+ const generations = (response.completion ?? "")
296
+ .split(AI_PROMPT)
297
+ .map((message) => ({
298
+ text: message,
299
+ message: new AIMessage(message),
300
+ }));
301
+ return {
302
+ generations,
303
+ };
304
+ }
305
+ /**
306
+ * Creates a streaming request with retry.
307
+ * @param request The parameters for creating a completion.
308
+ * @returns A streaming request.
309
+ */
310
+ async createStreamWithRetry(request) {
311
+ if (!this.streamingClient) {
312
+ const options = this.apiUrl ? { baseURL: this.apiUrl } : undefined;
313
+ this.streamingClient = new Anthropic({
314
+ ...this.clientOptions,
315
+ ...options,
316
+ apiKey: this.anthropicApiKey,
317
+ maxRetries: 0,
318
+ });
319
+ }
320
+ const makeCompletionRequest = async () => this.streamingClient.completions.create({ ...request, stream: true }, { headers: request.headers });
321
+ return this.caller.call(makeCompletionRequest);
322
+ }
323
+ /** @ignore */
324
+ async completionWithRetry(request, options) {
325
+ if (!this.anthropicApiKey) {
326
+ throw new Error("Missing Anthropic API key.");
327
+ }
328
+ if (!this.batchClient) {
329
+ const options = this.apiUrl ? { baseURL: this.apiUrl } : undefined;
330
+ this.batchClient = new Anthropic({
331
+ ...this.clientOptions,
332
+ ...options,
333
+ apiKey: this.anthropicApiKey,
334
+ maxRetries: 0,
335
+ });
336
+ }
337
+ const makeCompletionRequest = async () => this.batchClient.completions.create({ ...request, stream: false }, { headers: request.headers });
338
+ return this.caller.callWithOptions({ signal: options.signal }, makeCompletionRequest);
339
+ }
340
+ _llmType() {
341
+ return "anthropic";
342
+ }
343
+ /** @ignore */
344
+ _combineLLMOutput() {
345
+ return [];
346
+ }
347
+ }
package/index.cjs ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/index.cjs');
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/index.js'
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/index.js'
package/package.json ADDED
@@ -0,0 +1,96 @@
1
+ {
2
+ "name": "@langchain/anthropic",
3
+ "version": "0.0.0",
4
+ "description": "Anthropic integrations for LangChain.js",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=18"
8
+ },
9
+ "main": "./index.js",
10
+ "types": "./index.d.ts",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git@github.com:langchain-ai/langchainjs.git"
14
+ },
15
+ "scripts": {
16
+ "build": "yarn clean && yarn build:esm && yarn build:cjs && yarn build:scripts",
17
+ "build:esm": "NODE_OPTIONS=--max-old-space-size=4096 tsc --outDir dist/",
18
+ "build:cjs": "NODE_OPTIONS=--max-old-space-size=4096 tsc --outDir dist-cjs/ -p tsconfig.cjs.json && node scripts/move-cjs-to-dist.js && rimraf dist-cjs",
19
+ "build:watch": "node scripts/create-entrypoints.js && tsc --outDir dist/ --watch",
20
+ "build:scripts": "node scripts/create-entrypoints.js && node scripts/check-tree-shaking.js",
21
+ "lint": "NODE_OPTIONS=--max-old-space-size=4096 eslint src && dpdm --exit-code circular:1 --no-warning --no-tree src/*.ts src/**/*.ts",
22
+ "lint:fix": "yarn lint --fix",
23
+ "clean": "rimraf dist/ && NODE_OPTIONS=--max-old-space-size=4096 node scripts/create-entrypoints.js pre",
24
+ "prepack": "yarn build",
25
+ "release": "release-it --only-version --config .release-it.json",
26
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest --testPathIgnorePatterns=\\.int\\.test.ts --testTimeout 30000 --maxWorkers=50%",
27
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch --testPathIgnorePatterns=\\.int\\.test.ts",
28
+ "test:single": "NODE_OPTIONS=--experimental-vm-modules yarn run jest --config jest.config.cjs --testTimeout 100000",
29
+ "format": "prettier --write \"src\"",
30
+ "format:check": "prettier --check \"src\""
31
+ },
32
+ "author": "LangChain",
33
+ "license": "MIT",
34
+ "dependencies": {
35
+ "@anthropic-ai/sdk": "^0.10.0",
36
+ "langchain-core": "^0.0.3"
37
+ },
38
+ "devDependencies": {
39
+ "@jest/globals": "^29.5.0",
40
+ "@swc/core": "^1.3.90",
41
+ "@swc/jest": "^0.2.29",
42
+ "dpdm": "^3.12.0",
43
+ "eslint": "^8.33.0",
44
+ "eslint-config-airbnb-base": "^15.0.0",
45
+ "eslint-config-prettier": "^8.6.0",
46
+ "eslint-plugin-import": "^2.27.5",
47
+ "eslint-plugin-no-instanceof": "^1.0.1",
48
+ "eslint-plugin-prettier": "^4.2.1",
49
+ "jest": "^29.5.0",
50
+ "jest-environment-node": "^29.6.4",
51
+ "langchain-core": "workspace:*",
52
+ "prettier": "^2.8.3",
53
+ "release-it": "^15.10.1",
54
+ "rimraf": "^5.0.1",
55
+ "typescript": "^5.0.0"
56
+ },
57
+ "peerDependenciesMeta": {
58
+ "fast-xml-parser": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "publishConfig": {
63
+ "access": "public"
64
+ },
65
+ "keywords": [
66
+ "llm",
67
+ "ai",
68
+ "gpt3",
69
+ "chain",
70
+ "prompt",
71
+ "prompt engineering",
72
+ "chatgpt",
73
+ "machine learning",
74
+ "ml",
75
+ "openai",
76
+ "embeddings",
77
+ "vectorstores"
78
+ ],
79
+ "exports": {
80
+ "./chat_models": {
81
+ "types": "./chat_models.d.ts",
82
+ "import": "./chat_models.js",
83
+ "require": "./chat_models.cjs"
84
+ },
85
+ "./package.json": "./package.json"
86
+ },
87
+ "files": [
88
+ "dist/",
89
+ "chat_models.cjs",
90
+ "chat_models.js",
91
+ "chat_models.d.ts",
92
+ "index.cjs",
93
+ "index.js",
94
+ "index.d.ts"
95
+ ]
96
+ }