@librechat/agents 3.0.76 → 3.0.78

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.
@@ -1,7 +1,11 @@
1
1
  // src/scripts/test-prompt-caching.ts
2
2
  import { config } from 'dotenv';
3
3
  config();
4
- import { HumanMessage, SystemMessage, BaseMessage } from '@langchain/core/messages';
4
+ import {
5
+ HumanMessage,
6
+ SystemMessage,
7
+ BaseMessage,
8
+ } from '@langchain/core/messages';
5
9
  import type { UsageMetadata } from '@langchain/core/messages';
6
10
  import type * as t from '@/types';
7
11
  import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
@@ -11,7 +15,7 @@ import { getLLMConfig } from '@/utils/llmConfig';
11
15
  import { getArgs } from '@/scripts/args';
12
16
  import { Run } from '@/run';
13
17
 
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!`
18
+ 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
19
 
16
20
  const conversationHistory: BaseMessage[] = [];
17
21
  let _contentParts: t.MessageContentComplex[] = [];
@@ -23,7 +27,7 @@ async function testPromptCaching(): Promise<void> {
23
27
  ${CACHED_TEXT}`;
24
28
  const { contentParts, aggregateContent } = createContentAggregator();
25
29
  _contentParts = contentParts as t.MessageContentComplex[];
26
-
30
+
27
31
  // Set up event handlers
28
32
  const customHandlers = {
29
33
  [GraphEvents.TOOL_END]: new ToolEndHandler(),
@@ -33,29 +37,33 @@ ${CACHED_TEXT}`;
33
37
  [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
34
38
  // Additional handlers for tracking usage metrics
35
39
  [GraphEvents.ON_RUN_STEP_COMPLETED]: {
36
- handle: (event: GraphEvents.ON_RUN_STEP_COMPLETED, data: t.StreamEventData): void => {
40
+ handle: (
41
+ event: GraphEvents.ON_RUN_STEP_COMPLETED,
42
+ data: t.StreamEventData
43
+ ): void => {
37
44
  console.log('====== ON_RUN_STEP_COMPLETED ======');
38
- aggregateContent({ event, data: data as unknown as { result: t.ToolEndEvent } });
39
- }
45
+ aggregateContent({
46
+ event,
47
+ data: data as unknown as { result: t.ToolEndEvent },
48
+ });
49
+ },
40
50
  },
41
51
  };
42
52
 
43
- const baseLlmConfig: t.LLMConfig & t.AnthropicClientOptions = getLLMConfig(Providers.ANTHROPIC);
44
-
53
+ const baseLlmConfig: t.LLMConfig & t.AnthropicClientOptions = getLLMConfig(
54
+ Providers.ANTHROPIC
55
+ );
56
+
45
57
  if (baseLlmConfig.provider !== 'anthropic') {
46
- console.error('This test requires Anthropic as the LLM provider. Please specify provider=anthropic');
58
+ console.error(
59
+ 'This test requires Anthropic as the LLM provider. Please specify provider=anthropic'
60
+ );
47
61
  process.exit(1);
48
62
  }
49
-
63
+
50
64
  const llmConfig = {
51
65
  ...baseLlmConfig,
52
- clientOptions: {
53
- ...baseLlmConfig.clientOptions,
54
- defaultHeaders: {
55
- ...baseLlmConfig.clientOptions?.defaultHeaders,
56
- "anthropic-beta": "prompt-caching-2024-07-31",
57
- }
58
- }
66
+ promptCache: true,
59
67
  };
60
68
 
61
69
  const run = await Run.create<t.IState>({
@@ -94,7 +102,7 @@ ${CACHED_TEXT}`;
94
102
  console.log('\n\nTest 2: Second request (should use cache)');
95
103
  const userMessage2 = `Summarize the key concepts from the context information.`;
96
104
  conversationHistory.push(new HumanMessage(userMessage2));
97
-
105
+
98
106
  console.log('Running second query to use cache...');
99
107
  const secondInputs = { messages: [...conversationHistory] };
100
108
  await run.processStream(secondInputs, config);
@@ -121,4 +129,4 @@ testPromptCaching().catch((err) => {
121
129
  console.log('Content parts:');
122
130
  console.dir(_contentParts, { depth: null });
123
131
  process.exit(1);
124
- });
132
+ });
@@ -0,0 +1,241 @@
1
+ // src/scripts/code_exec_multi_session.ts
2
+ /**
3
+ * Tests multi-session file tracking for code execution.
4
+ * Verifies that:
5
+ * 1. Files from multiple executions are accumulated
6
+ * 2. Each file tracks its source session_id
7
+ * 3. Edited/recreated files replace older versions (latest preferred)
8
+ *
9
+ * Run with: npm run code_exec_multi_session
10
+ */
11
+ import { config } from 'dotenv';
12
+ config();
13
+ import { HumanMessage, BaseMessage } from '@langchain/core/messages';
14
+ import type { RunnableConfig } from '@langchain/core/runnables';
15
+ import type * as t from '@/types';
16
+ import { ChatModelStreamHandler } from '@/stream';
17
+ import { ToolEndHandler, ModelEndHandler } from '@/events';
18
+ import { getLLMConfig } from '@/utils/llmConfig';
19
+ import { getArgs } from '@/scripts/args';
20
+ import { Constants, GraphEvents } from '@/common';
21
+ import { Run } from '@/run';
22
+ import { createCodeExecutionTool } from '@/tools/CodeExecutor';
23
+
24
+ const conversationHistory: BaseMessage[] = [];
25
+
26
+ /**
27
+ * Prints session context from the graph
28
+ */
29
+ function printSessionContext(run: Run<t.IState>, label: string): void {
30
+ const graph = run.Graph;
31
+ if (!graph) {
32
+ console.log(`\n[${label}] No graph available`);
33
+ return;
34
+ }
35
+
36
+ const session = graph.sessions.get(Constants.EXECUTE_CODE) as
37
+ | t.CodeSessionContext
38
+ | undefined;
39
+
40
+ console.log(`\n========== ${label} ==========`);
41
+ if (!session) {
42
+ console.log(' No session context stored yet');
43
+ return;
44
+ }
45
+
46
+ console.log(` Latest session_id: ${session.session_id}`);
47
+ console.log(` Files tracked: ${session.files.length}`);
48
+ for (const file of session.files) {
49
+ console.log(` - ${file.name} (session: ${file.session_id})`);
50
+ }
51
+ }
52
+
53
+ async function testMultiSessionFiles(): Promise<void> {
54
+ const { provider } = await getArgs();
55
+
56
+ const customHandlers = {
57
+ [GraphEvents.TOOL_END]: new ToolEndHandler(),
58
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
59
+ [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
60
+ };
61
+
62
+ const llmConfig = getLLMConfig(provider);
63
+
64
+ const run = await Run.create<t.IState>({
65
+ runId: 'multi-session-test',
66
+ graphConfig: {
67
+ type: 'standard',
68
+ llmConfig,
69
+ tools: [createCodeExecutionTool()],
70
+ instructions: `You are a coding assistant. Execute code exactly as requested.
71
+ When asked to create files, use Python and save to /mnt/data/.
72
+ When reading files, print their contents.
73
+ Be concise in responses.`,
74
+ },
75
+ returnContent: true,
76
+ customHandlers,
77
+ });
78
+
79
+ const streamConfig: Partial<RunnableConfig> & {
80
+ version: 'v1' | 'v2';
81
+ streamMode: string;
82
+ } = {
83
+ configurable: {
84
+ provider,
85
+ thread_id: 'multi-session-test',
86
+ },
87
+ streamMode: 'values',
88
+ version: 'v2' as const,
89
+ };
90
+
91
+ // ========== TEST 1: Create first file ==========
92
+ console.log('\n\n' + '='.repeat(60));
93
+ console.log('TEST 1: Create first file (file_a.txt)');
94
+ console.log('='.repeat(60));
95
+
96
+ conversationHistory.push(
97
+ new HumanMessage(`
98
+ Create a file called "file_a.txt" with the content:
99
+ "This is file A, version 1"
100
+ Print confirmation when done.
101
+ `)
102
+ );
103
+
104
+ await run.processStream({ messages: conversationHistory }, streamConfig);
105
+ const messages1 = run.getRunMessages();
106
+ if (messages1) conversationHistory.push(...messages1);
107
+
108
+ printSessionContext(run, 'After Test 1');
109
+
110
+ // ========== TEST 2: Create second file (different session) ==========
111
+ console.log('\n\n' + '='.repeat(60));
112
+ console.log('TEST 2: Create second file (file_b.txt)');
113
+ console.log('Expecting: Both file_a.txt and file_b.txt tracked');
114
+ console.log('='.repeat(60));
115
+
116
+ conversationHistory.push(
117
+ new HumanMessage(`
118
+ Create a NEW file called "file_b.txt" with the content:
119
+ "This is file B"
120
+ Print confirmation when done.
121
+ `)
122
+ );
123
+
124
+ await run.processStream({ messages: conversationHistory }, streamConfig);
125
+ const messages2 = run.getRunMessages();
126
+ if (messages2) conversationHistory.push(...messages2);
127
+
128
+ printSessionContext(run, 'After Test 2');
129
+
130
+ // ========== TEST 3: Read BOTH files (verifies accumulation) ==========
131
+ console.log('\n\n' + '='.repeat(60));
132
+ console.log('TEST 3: Read BOTH files from previous executions');
133
+ console.log('This verifies multi-session file accumulation works');
134
+ console.log('='.repeat(60));
135
+
136
+ conversationHistory.push(
137
+ new HumanMessage(`
138
+ Read and print the contents of BOTH files:
139
+ 1. file_a.txt
140
+ 2. file_b.txt
141
+
142
+ Show me what's in each file.
143
+ `)
144
+ );
145
+
146
+ await run.processStream({ messages: conversationHistory }, streamConfig);
147
+ const messages3 = run.getRunMessages();
148
+ if (messages3) conversationHistory.push(...messages3);
149
+
150
+ printSessionContext(run, 'After Test 3');
151
+
152
+ // ========== TEST 4: Edit file_a.txt (verifies latest-wins) ==========
153
+ console.log('\n\n' + '='.repeat(60));
154
+ console.log('TEST 4: Edit file_a.txt (create new version)');
155
+ console.log('Expecting: Old file_a.txt replaced with new version');
156
+ console.log('='.repeat(60));
157
+
158
+ conversationHistory.push(
159
+ new HumanMessage(`
160
+ Create an UPDATED version of "file_a.txt" with the content:
161
+ "This is file A, version 2 - UPDATED"
162
+ Print confirmation when done.
163
+ `)
164
+ );
165
+
166
+ await run.processStream({ messages: conversationHistory }, streamConfig);
167
+ const messages4 = run.getRunMessages();
168
+ if (messages4) conversationHistory.push(...messages4);
169
+
170
+ printSessionContext(run, 'After Test 4');
171
+
172
+ // ========== TEST 5: Read file_a.txt (verifies latest version) ==========
173
+ console.log('\n\n' + '='.repeat(60));
174
+ console.log('TEST 5: Read file_a.txt to verify it has the UPDATED content');
175
+ console.log('Expected: "version 2 - UPDATED" NOT "version 1"');
176
+ console.log('='.repeat(60));
177
+
178
+ conversationHistory.push(
179
+ new HumanMessage(`
180
+ Read and print the contents of file_a.txt.
181
+ Tell me what version it shows.
182
+ `)
183
+ );
184
+
185
+ await run.processStream({ messages: conversationHistory }, streamConfig);
186
+ const messages5 = run.getRunMessages();
187
+ if (messages5) conversationHistory.push(...messages5);
188
+
189
+ printSessionContext(run, 'Final Session State');
190
+
191
+ // ========== SUMMARY ==========
192
+ console.log('\n\n' + '='.repeat(60));
193
+ console.log('TEST SUMMARY');
194
+ console.log('='.repeat(60));
195
+
196
+ const finalSession = run.Graph?.sessions.get(Constants.EXECUTE_CODE) as
197
+ | t.CodeSessionContext
198
+ | undefined;
199
+
200
+ if (finalSession) {
201
+ const uniqueSessionIds = new Set(
202
+ finalSession.files.map((f) => f.session_id)
203
+ );
204
+ console.log(`\nTotal files tracked: ${finalSession.files.length}`);
205
+ console.log(`Unique session_ids: ${uniqueSessionIds.size}`);
206
+ console.log('\nFiles:');
207
+ for (const file of finalSession.files) {
208
+ console.log(
209
+ ` - ${file.name} (session: ${file.session_id?.slice(0, 20)}...)`
210
+ );
211
+ }
212
+
213
+ // Verify expectations
214
+ const fileACount = finalSession.files.filter(
215
+ (f) => f.name === 'file_a.txt'
216
+ ).length;
217
+ const fileBCount = finalSession.files.filter(
218
+ (f) => f.name === 'file_b.txt'
219
+ ).length;
220
+
221
+ console.log('\n✓ Checks:');
222
+ console.log(` file_a.txt count: ${fileACount} (expected: 1, latest wins)`);
223
+ console.log(` file_b.txt count: ${fileBCount} (expected: 1)`);
224
+
225
+ if (fileACount === 1 && fileBCount === 1) {
226
+ console.log('\n✅ All tests passed! Multi-session tracking works.');
227
+ } else {
228
+ console.log('\n❌ Test failed - unexpected file counts');
229
+ }
230
+ }
231
+ }
232
+
233
+ process.on('unhandledRejection', (reason, promise) => {
234
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
235
+ process.exit(1);
236
+ });
237
+
238
+ testMultiSessionFiles().catch((err) => {
239
+ console.error('Test failed:', err);
240
+ process.exit(1);
241
+ });
@@ -145,9 +145,9 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
145
145
 
146
146
  /**
147
147
  * Inject session context for code execution tools when available.
148
+ * Each file uses its own session_id (supporting multi-session file tracking).
148
149
  * Both session_id and _injected_files are injected directly to invokeParams
149
150
  * (not inside args) so they bypass Zod schema validation and reach config.toolCall.
150
- * This avoids /files endpoint race conditions.
151
151
  */
152
152
  if (
153
153
  call.name === Constants.EXECUTE_CODE ||
@@ -156,14 +156,18 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
156
156
  const codeSession = this.sessions?.get(Constants.EXECUTE_CODE) as
157
157
  | t.CodeSessionContext
158
158
  | undefined;
159
- if (codeSession?.session_id != null && codeSession.files.length > 0) {
160
- /** Convert tracked files to CodeEnvFile format for the API */
159
+ if (codeSession?.files != null && codeSession.files.length > 0) {
160
+ /**
161
+ * Convert tracked files to CodeEnvFile format for the API.
162
+ * Each file uses its own session_id (set when file was created).
163
+ * This supports files from multiple parallel/sequential executions.
164
+ */
161
165
  const fileRefs: t.CodeEnvFile[] = codeSession.files.map((file) => ({
162
- session_id: codeSession.session_id,
166
+ session_id: file.session_id ?? codeSession.session_id,
163
167
  id: file.id,
164
168
  name: file.name,
165
169
  }));
166
- /** Inject session_id and files directly - bypasses Zod, reaches config.toolCall */
170
+ /** Inject latest session_id and files - bypasses Zod, reaches config.toolCall */
167
171
  invokeParams = {
168
172
  ...invokeParams,
169
173
  session_id: codeSession.session_id,
package/src/types/llm.ts CHANGED
@@ -55,7 +55,9 @@ export type AnthropicReasoning = {
55
55
  thinkingBudget?: number;
56
56
  };
57
57
  export type OpenAIClientOptions = ChatOpenAIFields;
58
- export type AnthropicClientOptions = AnthropicInput;
58
+ export type AnthropicClientOptions = AnthropicInput & {
59
+ promptCache?: boolean;
60
+ };
59
61
  export type MistralAIClientOptions = ChatMistralAIInput;
60
62
  export type VertexAIClientOptions = ChatVertexAIInput & {
61
63
  includeThoughts?: boolean;
@@ -74,6 +74,8 @@ export type FileRef = {
74
74
  id: string;
75
75
  name: string;
76
76
  path?: string;
77
+ /** Session ID this file belongs to (for multi-session file tracking) */
78
+ session_id?: string;
77
79
  };
78
80
 
79
81
  export type FileRefs = FileRef[];