@librechat/agents 2.1.2 → 2.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common/enum.cjs +1 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +11 -0
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/llm.cjs +46 -16
- package/dist/cjs/llm/anthropic/llm.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +25 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +93 -31
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/splitStream.cjs +8 -2
- package/dist/cjs/splitStream.cjs.map +1 -1
- package/dist/cjs/stream.cjs +13 -2
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +11 -0
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/anthropic/llm.mjs +46 -16
- package/dist/esm/llm/anthropic/llm.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +25 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs +93 -31
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/splitStream.mjs +8 -2
- package/dist/esm/splitStream.mjs.map +1 -1
- package/dist/esm/stream.mjs +13 -2
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +1 -0
- package/dist/types/llm/anthropic/llm.d.ts +3 -2
- package/dist/types/llm/anthropic/types.d.ts +10 -0
- package/dist/types/scripts/caching.d.ts +1 -0
- package/dist/types/scripts/thinking.d.ts +1 -0
- package/dist/types/splitStream.d.ts +2 -0
- package/dist/types/types/stream.d.ts +8 -2
- package/package.json +9 -7
- package/src/common/enum.ts +1 -0
- package/src/graphs/Graph.ts +14 -2
- package/src/llm/anthropic/llm.spec.ts +1069 -0
- package/src/llm/anthropic/llm.ts +65 -22
- package/src/llm/anthropic/types.ts +11 -2
- package/src/llm/anthropic/utils/message_inputs.ts +31 -1
- package/src/llm/anthropic/utils/message_outputs.ts +112 -42
- package/src/scripts/caching.ts +124 -0
- package/src/scripts/thinking.ts +152 -0
- package/src/scripts/tools.ts +2 -2
- package/src/splitStream.ts +8 -3
- package/src/stream.ts +11 -2
- package/src/types/stream.ts +9 -2
package/src/llm/anthropic/llm.ts
CHANGED
|
@@ -1,17 +1,48 @@
|
|
|
1
1
|
import { AIMessageChunk } from '@langchain/core/messages';
|
|
2
2
|
import { ChatAnthropicMessages } from '@langchain/anthropic';
|
|
3
3
|
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
4
|
+
import type { BaseChatModelParams } from '@langchain/core/language_models/chat_models';
|
|
4
5
|
import type { BaseMessage, MessageContentComplex } from '@langchain/core/messages';
|
|
5
6
|
import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
|
6
7
|
import type { AnthropicInput } from '@langchain/anthropic';
|
|
7
|
-
import type { AnthropicMessageCreateParams, AnthropicStreamUsage, AnthropicMessageStartEvent, AnthropicMessageDeltaEvent } from '@/llm/anthropic/types';
|
|
8
|
+
import type { AnthropicMessageCreateParams, AnthropicStreamingMessageCreateParams, AnthropicStreamUsage, AnthropicMessageStartEvent, AnthropicMessageDeltaEvent } from '@/llm/anthropic/types';
|
|
8
9
|
import { _makeMessageChunkFromAnthropicEvent } from './utils/message_outputs';
|
|
9
10
|
import { _convertMessagesToAnthropicPayload } from './utils/message_inputs';
|
|
10
11
|
import { TextStream } from '@/llm/text';
|
|
11
12
|
|
|
12
|
-
function _toolsInParams(
|
|
13
|
+
function _toolsInParams(
|
|
14
|
+
params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams
|
|
15
|
+
): boolean {
|
|
13
16
|
return !!(params.tools && params.tools.length > 0);
|
|
14
17
|
}
|
|
18
|
+
function _documentsInParams(
|
|
19
|
+
params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams
|
|
20
|
+
): boolean {
|
|
21
|
+
for (const message of params.messages ?? []) {
|
|
22
|
+
if (typeof message.content === "string") {
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
for (const block of message.content ?? []) {
|
|
26
|
+
if (
|
|
27
|
+
typeof block === "object" &&
|
|
28
|
+
block != null &&
|
|
29
|
+
block.type === "document" &&
|
|
30
|
+
typeof block.citations === "object" &&
|
|
31
|
+
block.citations.enabled
|
|
32
|
+
) {
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function _thinkingInParams(
|
|
41
|
+
params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams
|
|
42
|
+
): boolean {
|
|
43
|
+
return !!(params.thinking && params.thinking.type === "enabled");
|
|
44
|
+
}
|
|
45
|
+
|
|
15
46
|
|
|
16
47
|
function extractToken(chunk: AIMessageChunk): [string, 'string' | 'input' | 'content'] | [undefined] {
|
|
17
48
|
if (typeof chunk.content === 'string') {
|
|
@@ -30,6 +61,12 @@ function extractToken(chunk: AIMessageChunk): [string, 'string' | 'input' | 'con
|
|
|
30
61
|
'text' in chunk.content[0]
|
|
31
62
|
) {
|
|
32
63
|
return [chunk.content[0].text, 'content'];
|
|
64
|
+
} else if (
|
|
65
|
+
Array.isArray(chunk.content) &&
|
|
66
|
+
chunk.content.length >= 1 &&
|
|
67
|
+
'thinking' in chunk.content[0]
|
|
68
|
+
) {
|
|
69
|
+
return [chunk.content[0].thinking, 'content'];
|
|
33
70
|
}
|
|
34
71
|
return [undefined];
|
|
35
72
|
}
|
|
@@ -45,12 +82,14 @@ function cloneChunk(text: string, tokenType: string, chunk: AIMessageChunk): AIM
|
|
|
45
82
|
return new AIMessageChunk(Object.assign({}, chunk, { content: [Object.assign({}, content, { text })] }));
|
|
46
83
|
} else if (tokenType === 'content' && content.type === 'text_delta') {
|
|
47
84
|
return new AIMessageChunk(Object.assign({}, chunk, { content: [Object.assign({}, content, { text })] }));
|
|
85
|
+
} else if (tokenType === 'content' && content.type?.startsWith('thinking')) {
|
|
86
|
+
return new AIMessageChunk(Object.assign({}, chunk, { content: [Object.assign({}, content, { thinking: text })] }));
|
|
48
87
|
}
|
|
49
88
|
|
|
50
89
|
return chunk;
|
|
51
90
|
}
|
|
52
91
|
|
|
53
|
-
export type CustomAnthropicInput = AnthropicInput & { _lc_stream_delay?: number };
|
|
92
|
+
export type CustomAnthropicInput = AnthropicInput & { _lc_stream_delay?: number } & BaseChatModelParams;
|
|
54
93
|
|
|
55
94
|
export class CustomAnthropic extends ChatAnthropicMessages {
|
|
56
95
|
_lc_stream_delay: number;
|
|
@@ -58,9 +97,9 @@ export class CustomAnthropic extends ChatAnthropicMessages {
|
|
|
58
97
|
private message_delta: AnthropicMessageDeltaEvent | undefined;
|
|
59
98
|
private tools_in_params?: boolean;
|
|
60
99
|
private emitted_usage?: boolean;
|
|
61
|
-
constructor(fields
|
|
100
|
+
constructor(fields?: CustomAnthropicInput) {
|
|
62
101
|
super(fields);
|
|
63
|
-
this._lc_stream_delay = fields
|
|
102
|
+
this._lc_stream_delay = fields?._lc_stream_delay ?? 25;
|
|
64
103
|
}
|
|
65
104
|
|
|
66
105
|
/**
|
|
@@ -76,19 +115,21 @@ export class CustomAnthropic extends ChatAnthropicMessages {
|
|
|
76
115
|
if (!outputUsage) {
|
|
77
116
|
return;
|
|
78
117
|
}
|
|
79
|
-
const totalUsage = {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
+ (inputUsage?.cache_read_input_tokens ?? 0)
|
|
84
|
-
+ (outputUsage.input_tokens ?? 0)
|
|
85
|
-
+ (outputUsage.output_tokens ?? 0)
|
|
86
|
-
+ (outputUsage.cache_creation_input_tokens ?? 0)
|
|
87
|
-
+ (outputUsage.cache_read_input_tokens ?? 0),
|
|
118
|
+
const totalUsage: AnthropicStreamUsage = {
|
|
119
|
+
input_tokens: inputUsage?.input_tokens ?? 0,
|
|
120
|
+
output_tokens: outputUsage?.output_tokens ?? 0,
|
|
121
|
+
total_tokens: (inputUsage?.input_tokens ?? 0) + (outputUsage?.output_tokens ?? 0),
|
|
88
122
|
};
|
|
89
123
|
|
|
124
|
+
if (inputUsage?.cache_creation_input_tokens != null || inputUsage?.cache_read_input_tokens != null) {
|
|
125
|
+
totalUsage.input_token_details = {
|
|
126
|
+
cache_creation: inputUsage.cache_creation_input_tokens ?? 0,
|
|
127
|
+
cache_read: inputUsage.cache_read_input_tokens ?? 0,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
90
131
|
this.emitted_usage = true;
|
|
91
|
-
return
|
|
132
|
+
return totalUsage;
|
|
92
133
|
}
|
|
93
134
|
|
|
94
135
|
resetTokenEvents(): void {
|
|
@@ -131,12 +172,15 @@ export class CustomAnthropic extends ChatAnthropicMessages {
|
|
|
131
172
|
): AsyncGenerator<ChatGenerationChunk> {
|
|
132
173
|
const params = this.invocationParams(options);
|
|
133
174
|
const formattedMessages = _convertMessagesToAnthropicPayload(messages);
|
|
134
|
-
|
|
175
|
+
const payload = {
|
|
135
176
|
...params,
|
|
136
177
|
...formattedMessages,
|
|
137
|
-
stream:
|
|
138
|
-
}
|
|
139
|
-
const coerceContentToString =
|
|
178
|
+
stream: true,
|
|
179
|
+
} as const;
|
|
180
|
+
const coerceContentToString =
|
|
181
|
+
!_toolsInParams(payload) &&
|
|
182
|
+
!_documentsInParams(payload) &&
|
|
183
|
+
!_thinkingInParams(payload);
|
|
140
184
|
|
|
141
185
|
const stream = await this.createStreamWithRetry(
|
|
142
186
|
{
|
|
@@ -157,10 +201,9 @@ export class CustomAnthropic extends ChatAnthropicMessages {
|
|
|
157
201
|
throw new Error('AbortError: User aborted the request.');
|
|
158
202
|
}
|
|
159
203
|
|
|
160
|
-
|
|
161
|
-
if (type === 'message_start') {
|
|
204
|
+
if (data.type === 'message_start') {
|
|
162
205
|
this.message_start = data as AnthropicMessageStartEvent;
|
|
163
|
-
} else if (type === 'message_delta') {
|
|
206
|
+
} else if (data.type === 'message_delta') {
|
|
164
207
|
this.message_delta = data as AnthropicMessageDeltaEvent;
|
|
165
208
|
}
|
|
166
209
|
|
|
@@ -38,6 +38,10 @@ export type AnthropicImageBlockParam = Anthropic.Messages.ImageBlockParam;
|
|
|
38
38
|
export type AnthropicToolUseBlockParam = Anthropic.Messages.ToolUseBlockParam;
|
|
39
39
|
export type AnthropicToolResultBlockParam =
|
|
40
40
|
Anthropic.Messages.ToolResultBlockParam;
|
|
41
|
+
export type AnthropicDocumentBlockParam = Anthropic.Messages.DocumentBlockParam;
|
|
42
|
+
export type AnthropicThinkingBlockParam = Anthropic.Messages.ThinkingBlockParam;
|
|
43
|
+
export type AnthropicRedactedThinkingBlockParam =
|
|
44
|
+
Anthropic.Messages.RedactedThinkingBlockParam;
|
|
41
45
|
|
|
42
46
|
/**
|
|
43
47
|
* Stream usage information for Anthropic API calls
|
|
@@ -53,12 +57,10 @@ export interface AnthropicStreamUsage {
|
|
|
53
57
|
* The number of cache creation input tokens used (write operations)
|
|
54
58
|
*/
|
|
55
59
|
cache_creation_input_tokens?: number;
|
|
56
|
-
|
|
57
60
|
/**
|
|
58
61
|
* The number of cache input tokens used (read operations)
|
|
59
62
|
*/
|
|
60
63
|
cache_read_input_tokens?: number;
|
|
61
|
-
|
|
62
64
|
/**
|
|
63
65
|
* The number of output tokens generated in the response
|
|
64
66
|
*/
|
|
@@ -67,4 +69,11 @@ export interface AnthropicStreamUsage {
|
|
|
67
69
|
* The total number of tokens generated in the response
|
|
68
70
|
*/
|
|
69
71
|
total_tokens: number;
|
|
72
|
+
/**
|
|
73
|
+
* Details about input token usage
|
|
74
|
+
*/
|
|
75
|
+
input_token_details?: {
|
|
76
|
+
cache_creation: number;
|
|
77
|
+
cache_read: number;
|
|
78
|
+
};
|
|
70
79
|
}
|
|
@@ -20,6 +20,9 @@ import type {
|
|
|
20
20
|
AnthropicToolUseBlockParam,
|
|
21
21
|
AnthropicMessageCreateParams,
|
|
22
22
|
AnthropicToolResultBlockParam,
|
|
23
|
+
AnthropicDocumentBlockParam,
|
|
24
|
+
AnthropicThinkingBlockParam,
|
|
25
|
+
AnthropicRedactedThinkingBlockParam,
|
|
23
26
|
} from '@/llm/anthropic/types';
|
|
24
27
|
|
|
25
28
|
function _formatImage(imageUrl: string): { type: string; media_type: string; data: string } {
|
|
@@ -135,6 +138,27 @@ function _formatContent(content: MessageContent): string | Record<string, any>[]
|
|
|
135
138
|
source,
|
|
136
139
|
...(cacheControl ? { cache_control: cacheControl } : {}),
|
|
137
140
|
};
|
|
141
|
+
} else if (contentPart.type === "document") {
|
|
142
|
+
// PDF
|
|
143
|
+
return {
|
|
144
|
+
...contentPart,
|
|
145
|
+
...(cacheControl ? { cache_control: cacheControl } : {}),
|
|
146
|
+
};
|
|
147
|
+
} else if (contentPart.type === "thinking") {
|
|
148
|
+
const block: AnthropicThinkingBlockParam = {
|
|
149
|
+
type: "thinking" as const, // Explicitly setting the type as "thinking"
|
|
150
|
+
thinking: contentPart.thinking,
|
|
151
|
+
signature: contentPart.signature,
|
|
152
|
+
...(cacheControl ? { cache_control: cacheControl } : {}),
|
|
153
|
+
};
|
|
154
|
+
return block;
|
|
155
|
+
} else if (contentPart.type === "redacted_thinking") {
|
|
156
|
+
const block: AnthropicRedactedThinkingBlockParam = {
|
|
157
|
+
type: "redacted_thinking" as const, // Explicitly setting the type as "redacted_thinking"
|
|
158
|
+
data: contentPart.data,
|
|
159
|
+
...(cacheControl ? { cache_control: cacheControl } : {}),
|
|
160
|
+
};
|
|
161
|
+
return block;
|
|
138
162
|
} else if (
|
|
139
163
|
textTypes.find((t) => t === contentPart.type) != null &&
|
|
140
164
|
'text' in contentPart
|
|
@@ -279,14 +303,20 @@ function mergeMessages(messages?: AnthropicMessageCreateParams['messages']): Ant
|
|
|
279
303
|
| AnthropicImageBlockParam
|
|
280
304
|
| AnthropicToolUseBlockParam
|
|
281
305
|
| AnthropicToolResultBlockParam
|
|
306
|
+
| AnthropicDocumentBlockParam
|
|
307
|
+
| AnthropicThinkingBlockParam
|
|
308
|
+
| AnthropicRedactedThinkingBlockParam
|
|
282
309
|
>
|
|
283
310
|
): Array<
|
|
284
311
|
| AnthropicTextBlockParam
|
|
285
312
|
| AnthropicImageBlockParam
|
|
286
313
|
| AnthropicToolUseBlockParam
|
|
287
314
|
| AnthropicToolResultBlockParam
|
|
315
|
+
| AnthropicDocumentBlockParam
|
|
316
|
+
| AnthropicThinkingBlockParam
|
|
317
|
+
| AnthropicRedactedThinkingBlockParam
|
|
288
318
|
> => {
|
|
289
|
-
if (typeof content ===
|
|
319
|
+
if (typeof content === "string") {
|
|
290
320
|
return [
|
|
291
321
|
{
|
|
292
322
|
type: 'text',
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
UsageMetadata,
|
|
8
8
|
AIMessageChunk,
|
|
9
9
|
} from '@langchain/core/messages';
|
|
10
|
+
import type { ToolCallChunk } from "@langchain/core/messages/tool";
|
|
10
11
|
import { ToolCall } from '@langchain/core/messages/tool';
|
|
11
12
|
import { ChatGeneration } from '@langchain/core/outputs';
|
|
12
13
|
import { AnthropicMessageResponse } from '../types.js';
|
|
@@ -46,16 +47,28 @@ export function _makeMessageChunkFromAnthropicEvent(
|
|
|
46
47
|
filteredAdditionalKwargs[key] = value;
|
|
47
48
|
}
|
|
48
49
|
}
|
|
50
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
51
|
+
const { input_tokens, output_tokens, ...rest }: Record<string, any> =
|
|
52
|
+
usage ?? {};
|
|
49
53
|
const usageMetadata: UsageMetadata = {
|
|
50
|
-
input_tokens
|
|
51
|
-
output_tokens
|
|
52
|
-
total_tokens:
|
|
54
|
+
input_tokens,
|
|
55
|
+
output_tokens,
|
|
56
|
+
total_tokens: input_tokens + output_tokens,
|
|
57
|
+
input_token_details: {
|
|
58
|
+
cache_creation: rest.cache_creation_input_tokens,
|
|
59
|
+
cache_read: rest.cache_read_input_tokens,
|
|
60
|
+
},
|
|
53
61
|
};
|
|
54
62
|
return {
|
|
55
63
|
chunk: new AIMessageChunk({
|
|
56
64
|
content: fields.coerceContentToString ? '' : [],
|
|
57
65
|
additional_kwargs: filteredAdditionalKwargs,
|
|
58
66
|
usage_metadata: fields.streamUsage ? usageMetadata : undefined,
|
|
67
|
+
response_metadata: {
|
|
68
|
+
usage: {
|
|
69
|
+
...rest,
|
|
70
|
+
},
|
|
71
|
+
},
|
|
59
72
|
id: data.message.id,
|
|
60
73
|
}),
|
|
61
74
|
};
|
|
@@ -64,6 +77,12 @@ export function _makeMessageChunkFromAnthropicEvent(
|
|
|
64
77
|
input_tokens: 0,
|
|
65
78
|
output_tokens: data.usage.output_tokens,
|
|
66
79
|
total_tokens: data.usage.output_tokens,
|
|
80
|
+
input_token_details: {
|
|
81
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
82
|
+
cache_creation: (data.usage as any).cache_creation_input_tokens,
|
|
83
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
84
|
+
cache_read: (data.usage as any).cache_read_input_tokens,
|
|
85
|
+
},
|
|
67
86
|
};
|
|
68
87
|
return {
|
|
69
88
|
chunk: new AIMessageChunk({
|
|
@@ -73,56 +92,80 @@ export function _makeMessageChunkFromAnthropicEvent(
|
|
|
73
92
|
}),
|
|
74
93
|
};
|
|
75
94
|
} else if (
|
|
76
|
-
data.type ===
|
|
77
|
-
data.content_block.type
|
|
95
|
+
data.type === "content_block_start" &&
|
|
96
|
+
["tool_use", "document"].includes(data.content_block.type)
|
|
78
97
|
) {
|
|
79
|
-
const
|
|
80
|
-
|
|
98
|
+
const contentBlock = data.content_block;
|
|
99
|
+
let toolCallChunks: ToolCallChunk[];
|
|
100
|
+
if (contentBlock.type === "tool_use") {
|
|
101
|
+
toolCallChunks = [
|
|
102
|
+
{
|
|
103
|
+
id: contentBlock.id,
|
|
104
|
+
index: data.index,
|
|
105
|
+
name: contentBlock.name,
|
|
106
|
+
args: "",
|
|
107
|
+
},
|
|
108
|
+
];
|
|
109
|
+
} else {
|
|
110
|
+
toolCallChunks = [];
|
|
111
|
+
}
|
|
81
112
|
return {
|
|
82
113
|
chunk: new AIMessageChunk({
|
|
83
114
|
content: fields.coerceContentToString
|
|
84
|
-
?
|
|
115
|
+
? ""
|
|
85
116
|
: [
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
117
|
+
{
|
|
118
|
+
index: data.index,
|
|
119
|
+
...data.content_block,
|
|
120
|
+
input: "",
|
|
121
|
+
},
|
|
122
|
+
],
|
|
92
123
|
additional_kwargs: {},
|
|
93
|
-
tool_call_chunks:
|
|
94
|
-
{
|
|
95
|
-
id: toolCallContentBlock.id,
|
|
96
|
-
index: data.index,
|
|
97
|
-
name: toolCallContentBlock.name,
|
|
98
|
-
args: '',
|
|
99
|
-
},
|
|
100
|
-
],
|
|
124
|
+
tool_call_chunks: toolCallChunks,
|
|
101
125
|
}),
|
|
102
126
|
};
|
|
103
127
|
} else if (
|
|
104
|
-
data.type ===
|
|
105
|
-
|
|
128
|
+
data.type === "content_block_delta" &&
|
|
129
|
+
[
|
|
130
|
+
"text_delta",
|
|
131
|
+
"citations_delta",
|
|
132
|
+
"thinking_delta",
|
|
133
|
+
"signature_delta",
|
|
134
|
+
].includes(data.delta.type)
|
|
106
135
|
) {
|
|
107
|
-
|
|
108
|
-
if (content !== undefined) {
|
|
136
|
+
if (fields.coerceContentToString && "text" in data.delta) {
|
|
109
137
|
return {
|
|
110
138
|
chunk: new AIMessageChunk({
|
|
111
|
-
content:
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
139
|
+
content: data.delta.text,
|
|
140
|
+
}),
|
|
141
|
+
};
|
|
142
|
+
} else {
|
|
143
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
144
|
+
const contentBlock: Record<string, any> = data.delta;
|
|
145
|
+
if ("citation" in contentBlock) {
|
|
146
|
+
contentBlock.citations = [contentBlock.citation];
|
|
147
|
+
delete contentBlock.citation;
|
|
148
|
+
}
|
|
149
|
+
if (
|
|
150
|
+
contentBlock.type === "thinking_delta" ||
|
|
151
|
+
contentBlock.type === "signature_delta"
|
|
152
|
+
) {
|
|
153
|
+
return {
|
|
154
|
+
chunk: new AIMessageChunk({
|
|
155
|
+
content: [{ index: data.index, ...contentBlock, type: "thinking" }],
|
|
156
|
+
}),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
chunk: new AIMessageChunk({
|
|
162
|
+
content: [{ index: data.index, ...contentBlock, type: "text" }],
|
|
120
163
|
}),
|
|
121
164
|
};
|
|
122
165
|
}
|
|
123
166
|
} else if (
|
|
124
|
-
data.type ===
|
|
125
|
-
data.delta.type ===
|
|
167
|
+
data.type === "content_block_delta" &&
|
|
168
|
+
data.delta.type === "input_json_delta"
|
|
126
169
|
) {
|
|
127
170
|
return {
|
|
128
171
|
chunk: new AIMessageChunk({
|
|
@@ -164,6 +207,29 @@ export function _makeMessageChunkFromAnthropicEvent(
|
|
|
164
207
|
}),
|
|
165
208
|
};
|
|
166
209
|
}
|
|
210
|
+
} else if (
|
|
211
|
+
data.type === "content_block_start" &&
|
|
212
|
+
data.content_block.type === "redacted_thinking"
|
|
213
|
+
) {
|
|
214
|
+
return {
|
|
215
|
+
chunk: new AIMessageChunk({
|
|
216
|
+
content: fields.coerceContentToString
|
|
217
|
+
? ""
|
|
218
|
+
: [{ index: data.index, ...data.content_block }],
|
|
219
|
+
}),
|
|
220
|
+
};
|
|
221
|
+
} else if (
|
|
222
|
+
data.type === "content_block_start" &&
|
|
223
|
+
data.content_block.type === "thinking"
|
|
224
|
+
) {
|
|
225
|
+
const content = data.content_block.thinking;
|
|
226
|
+
return {
|
|
227
|
+
chunk: new AIMessageChunk({
|
|
228
|
+
content: fields.coerceContentToString
|
|
229
|
+
? content
|
|
230
|
+
: [{ index: data.index, ...data.content_block }],
|
|
231
|
+
}),
|
|
232
|
+
};
|
|
167
233
|
}
|
|
168
234
|
|
|
169
235
|
return null;
|
|
@@ -175,13 +241,17 @@ export function anthropicResponseToChatMessages(
|
|
|
175
241
|
): ChatGeneration[] {
|
|
176
242
|
const usage: Record<string, number> | null | undefined =
|
|
177
243
|
additionalKwargs.usage as Record<string, number> | null | undefined;
|
|
178
|
-
|
|
244
|
+
const usageMetadata =
|
|
179
245
|
usage != null
|
|
180
246
|
? {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
247
|
+
input_tokens: usage.input_tokens ?? 0,
|
|
248
|
+
output_tokens: usage.output_tokens ?? 0,
|
|
249
|
+
total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0),
|
|
250
|
+
input_token_details: {
|
|
251
|
+
cache_creation: usage.cache_creation_input_tokens,
|
|
252
|
+
cache_read: usage.cache_read_input_tokens,
|
|
253
|
+
},
|
|
254
|
+
}
|
|
185
255
|
: undefined;
|
|
186
256
|
if (messages.length === 1 && messages[0].type === 'text') {
|
|
187
257
|
return [
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// src/scripts/test-prompt-caching.ts
|
|
2
|
+
import { config } from 'dotenv';
|
|
3
|
+
config();
|
|
4
|
+
import { HumanMessage, SystemMessage, BaseMessage } from '@langchain/core/messages';
|
|
5
|
+
import type { UsageMetadata } from '@langchain/core/messages';
|
|
6
|
+
import type * as t from '@/types';
|
|
7
|
+
import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
|
|
8
|
+
import { ToolEndHandler, ModelEndHandler } from '@/events';
|
|
9
|
+
import { GraphEvents, Providers } from '@/common';
|
|
10
|
+
import { getLLMConfig } from '@/utils/llmConfig';
|
|
11
|
+
import { getArgs } from '@/scripts/args';
|
|
12
|
+
import { Run } from '@/run';
|
|
13
|
+
|
|
14
|
+
const CACHED_TEXT = `Ahoy there, me hearties! This be a grand tale o' the mighty prompt cachin' treasure map, a secret technique used by the wise Anthropic seafarers to stash away vast hordes o' text booty on their mystical servers! Arrr, 'tis a pirate's dream indeed - no need to haul the same heavy chest o' gold doubloons across the vast digital ocean with every message! When ye mark yer precious cargo with the secret flag 'cache_control: { type: \"ephemeral\" }', the text be safely buried on their distant shores, ready for plunderin' again without the weight slowin' down yer ship! The wise pirates at Anthropic introduced this magical scroll in the summer o' 2024, markin' it with the mysterious insignia 'anthropic-beta: prompt-caching-2024-07-31' that must be flown high on yer vessel's headers. This crafty script be testin' the waters of this new treasure map system, sendin' out three separate voyages across the AI seas: first to bury the treasure, second to dig it up again without payin' the full toll, and third to see if the map still leads to gold after the sands o' time have shifted (about thirty seconds o' waitin', which be an eternity for an impatient buccaneer!). The great advantage for a scurvy pirate captain is clear as Caribbean waters - ye can load up yer vessel with all manner o' reference scrolls, ancient tomes, and navigational charts without weighin' down each and every message ye send to port! This be savin' ye countless tokens, which as any seafarin' AI wrangler knows, be as precious as Spanish gold. The cached text could contain the full history o' the Seven Seas, detailed maps o' every port from Tortuga to Singapore, or the complete collection o' pirate shanties ever sung by drunken sailors under the light o' the silvery moon. When properly implemented, this mighty cachin' system keeps all that knowledge ready at hand without the Claude kraken needin' to process it anew with each passin' breeze. By Blackbeard's beard, 'tis a revolution in how we manage our conversational ships! The script be employin' the finest LangChain riggin' and custom-carved event handlers to properly track the treasure as it flows back and forth. If ye be successful in yer implementation, ye should witness the miracle o' significantly reduced token counts in yer usage metrics, faster responses from the AI oracle, and the ability to maintain vast knowledge without payin' the full price each time! So hoist the Jolly Roger, load yer pistols with API keys, and set sail on the grand adventure o' prompt cachin'! May the winds o' efficient token usage fill yer sails, and may ye never have to pay full price for passin' the same mammoth context to Claude again! Remember, a clever pirate only pays for their tokens once, then lets the cache do the heavy liftin'! YARRR! This file also contains the secrets of the legendary Pirate Code, passed down through generations of seafarers since the Golden Age of Piracy. It includes detailed accounts of famous pirate captains like Blackbeard, Calico Jack, Anne Bonny, and Mary Read, along with their most profitable plundering routes and techniques for capturing merchant vessels. The text chronicles the exact locations of at least seventeen buried treasures across the Caribbean, complete with riddles and map coordinates that only a true pirate could decipher. There are sections dedicated to ship maintenance, including how to properly seal a leaking hull during battle and the best methods for keeping your cannons in prime firing condition even in humid tropical conditions. The document contains an extensive glossary of pirate terminology, from 'avast' to 'Yellow Jack,' ensuring any landlubber can speak like a seasoned salt with enough study. There's a comprehensive guide to navigating by the stars without modern instruments, perfect for when your GPS fails in the middle of a daring escape. The cache also includes detailed recipes for grog, hardtack that won't break your teeth, and how to keep citrus fruits fresh to prevent scurvy during long voyages. The legendary Black Spot ritual is described in terrifying detail, along with other pirate superstitions and their origins in maritime folklore. A section on pirate governance explains the democratic nature of most pirate ships, how booty was divided fairly, and how captains were elected and deposed when necessary. The file even contains sheet music for dozens of sea shanties, with notes on when each should be sung for maximum crew morale during different sailing conditions. All of this knowledge is wrapped in colorful pirate dialect that would make any AI assistant respond with appropriate 'arghs' and 'avasts' when properly prompted!`
|
|
15
|
+
|
|
16
|
+
const conversationHistory: BaseMessage[] = [];
|
|
17
|
+
let _contentParts: t.MessageContentComplex[] = [];
|
|
18
|
+
const collectedUsage: UsageMetadata[] = [];
|
|
19
|
+
|
|
20
|
+
async function testPromptCaching(): Promise<void> {
|
|
21
|
+
const { userName } = await getArgs();
|
|
22
|
+
const instructions = `You are a pirate AI assistant for ${userName}. Always respond in pirate dialect. Use the following as context when answering questions:
|
|
23
|
+
${CACHED_TEXT}`;
|
|
24
|
+
const { contentParts, aggregateContent } = createContentAggregator();
|
|
25
|
+
_contentParts = contentParts as t.MessageContentComplex[];
|
|
26
|
+
|
|
27
|
+
// Set up event handlers
|
|
28
|
+
const customHandlers = {
|
|
29
|
+
[GraphEvents.TOOL_END]: new ToolEndHandler(),
|
|
30
|
+
[GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(collectedUsage),
|
|
31
|
+
// console.log('====== O ======');
|
|
32
|
+
// console.log('Usage Metrics:', (data as any).llmOutput?.usage || (data as any).usage);
|
|
33
|
+
[GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
|
|
34
|
+
// Additional handlers for tracking usage metrics
|
|
35
|
+
[GraphEvents.ON_RUN_STEP_COMPLETED]: {
|
|
36
|
+
handle: (event: GraphEvents.ON_RUN_STEP_COMPLETED, data: t.StreamEventData): void => {
|
|
37
|
+
console.log('====== ON_RUN_STEP_COMPLETED ======');
|
|
38
|
+
aggregateContent({ event, data: data as unknown as { result: t.ToolEndEvent } });
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const baseLlmConfig: t.LLMConfig & t.AnthropicClientOptions = getLLMConfig(Providers.ANTHROPIC);
|
|
44
|
+
|
|
45
|
+
if (baseLlmConfig.provider !== 'anthropic') {
|
|
46
|
+
console.error('This test requires Anthropic as the LLM provider. Please specify provider=anthropic');
|
|
47
|
+
process.exit(1);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const llmConfig = {
|
|
51
|
+
...baseLlmConfig,
|
|
52
|
+
clientOptions: {
|
|
53
|
+
...baseLlmConfig.clientOptions,
|
|
54
|
+
defaultHeaders: {
|
|
55
|
+
...baseLlmConfig.clientOptions?.defaultHeaders,
|
|
56
|
+
"anthropic-beta": "prompt-caching-2024-07-31",
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const run = await Run.create<t.IState>({
|
|
62
|
+
runId: 'test-prompt-caching-id',
|
|
63
|
+
graphConfig: {
|
|
64
|
+
instructions,
|
|
65
|
+
type: 'standard',
|
|
66
|
+
llmConfig,
|
|
67
|
+
},
|
|
68
|
+
returnContent: true,
|
|
69
|
+
customHandlers,
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const config = {
|
|
73
|
+
configurable: {
|
|
74
|
+
thread_id: 'prompt-cache-test-thread',
|
|
75
|
+
},
|
|
76
|
+
streamMode: 'values',
|
|
77
|
+
version: 'v2' as const,
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// First request - should create the cache
|
|
81
|
+
console.log('\n\nTest 1: First request (creates cache)');
|
|
82
|
+
const userMessage1 = `What information do you have in your context?`;
|
|
83
|
+
conversationHistory.push(new HumanMessage(userMessage1));
|
|
84
|
+
|
|
85
|
+
console.log('Running first query to create cache...');
|
|
86
|
+
const firstInputs = { messages: [...conversationHistory] };
|
|
87
|
+
await run.processStream(firstInputs, config);
|
|
88
|
+
const finalMessages = run.getRunMessages();
|
|
89
|
+
if (finalMessages) {
|
|
90
|
+
conversationHistory.push(...finalMessages);
|
|
91
|
+
console.dir(conversationHistory, { depth: null });
|
|
92
|
+
}
|
|
93
|
+
// Second request - should use the cache
|
|
94
|
+
console.log('\n\nTest 2: Second request (should use cache)');
|
|
95
|
+
const userMessage2 = `Summarize the key concepts from the context information.`;
|
|
96
|
+
conversationHistory.push(new HumanMessage(userMessage2));
|
|
97
|
+
|
|
98
|
+
console.log('Running second query to use cache...');
|
|
99
|
+
const secondInputs = { messages: [...conversationHistory] };
|
|
100
|
+
await run.processStream(secondInputs, config);
|
|
101
|
+
console.log('\n\nPrompt caching test completed!');
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
process.on('unhandledRejection', (reason, promise) => {
|
|
105
|
+
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
|
106
|
+
console.log('Conversation history:');
|
|
107
|
+
console.dir(conversationHistory, { depth: null });
|
|
108
|
+
console.log('Content parts:');
|
|
109
|
+
console.dir(_contentParts, { depth: null });
|
|
110
|
+
process.exit(1);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
process.on('uncaughtException', (err) => {
|
|
114
|
+
console.error('Uncaught Exception:', err);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
testPromptCaching().catch((err) => {
|
|
118
|
+
console.error(err);
|
|
119
|
+
console.log('Conversation history:');
|
|
120
|
+
console.dir(conversationHistory, { depth: null });
|
|
121
|
+
console.log('Content parts:');
|
|
122
|
+
console.dir(_contentParts, { depth: null });
|
|
123
|
+
process.exit(1);
|
|
124
|
+
});
|