@librechat/agents 2.1.2 → 2.1.3

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.
@@ -8,7 +8,7 @@ import { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';
8
8
  import { Runnable, RunnableConfig } from '@langchain/core/runnables';
9
9
  import { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';
10
10
  import { AIMessageChunk, ToolMessage, SystemMessage } from '@langchain/core/messages';
11
- import type { BaseMessage } from '@langchain/core/messages';
11
+ import type { BaseMessage, BaseMessageFields } from '@langchain/core/messages';
12
12
  import type * as t from '@/types';
13
13
  import { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback, ContentTypes } from '@/common';
14
14
  import { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';
@@ -127,11 +127,23 @@ export class StandardGraph extends Graph<
127
127
  this.reasoningKey = reasoningKey;
128
128
  }
129
129
 
130
- let finalInstructions = instructions ?? '';
130
+ let finalInstructions: string | BaseMessageFields = instructions ?? '';
131
131
  if (additional_instructions) {
132
132
  finalInstructions = finalInstructions ? `${finalInstructions}\n\n${additional_instructions}` : additional_instructions;
133
133
  }
134
134
 
135
+ if (finalInstructions && provider === Providers.ANTHROPIC && (clientOptions as t.AnthropicClientOptions)?.clientOptions?.defaultHeaders?.['anthropic-beta']?.includes('prompt-caching')) {
136
+ finalInstructions = {
137
+ content: [
138
+ {
139
+ type: "text",
140
+ text: instructions,
141
+ cache_control: { type: "ephemeral" },
142
+ },
143
+ ],
144
+ };
145
+ }
146
+
135
147
  if (finalInstructions) {
136
148
  this.systemMessage = new SystemMessage(finalInstructions);
137
149
  }
@@ -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
@@ -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 === 'string') {
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';
@@ -73,56 +74,80 @@ export function _makeMessageChunkFromAnthropicEvent(
73
74
  }),
74
75
  };
75
76
  } else if (
76
- data.type === 'content_block_start' &&
77
- data.content_block.type === 'tool_use'
77
+ data.type === "content_block_start" &&
78
+ ["tool_use", "document"].includes(data.content_block.type)
78
79
  ) {
79
- const toolCallContentBlock =
80
- data.content_block as Anthropic.Messages.ToolUseBlock;
80
+ const contentBlock = data.content_block;
81
+ let toolCallChunks: ToolCallChunk[];
82
+ if (contentBlock.type === "tool_use") {
83
+ toolCallChunks = [
84
+ {
85
+ id: contentBlock.id,
86
+ index: data.index,
87
+ name: contentBlock.name,
88
+ args: "",
89
+ },
90
+ ];
91
+ } else {
92
+ toolCallChunks = [];
93
+ }
81
94
  return {
82
95
  chunk: new AIMessageChunk({
83
96
  content: fields.coerceContentToString
84
- ? ''
97
+ ? ""
85
98
  : [
86
- {
87
- index: data.index,
88
- ...data.content_block,
89
- input: '',
90
- },
91
- ],
99
+ {
100
+ index: data.index,
101
+ ...data.content_block,
102
+ input: "",
103
+ },
104
+ ],
92
105
  additional_kwargs: {},
93
- tool_call_chunks: [
94
- {
95
- id: toolCallContentBlock.id,
96
- index: data.index,
97
- name: toolCallContentBlock.name,
98
- args: '',
99
- },
100
- ],
106
+ tool_call_chunks: toolCallChunks,
101
107
  }),
102
108
  };
103
109
  } else if (
104
- data.type === 'content_block_delta' &&
105
- data.delta.type === 'text_delta'
110
+ data.type === "content_block_delta" &&
111
+ [
112
+ "text_delta",
113
+ "citations_delta",
114
+ "thinking_delta",
115
+ "signature_delta",
116
+ ].includes(data.delta.type)
106
117
  ) {
107
- const content = data.delta.text;
108
- if (content !== undefined) {
118
+ if (fields.coerceContentToString && "text" in data.delta) {
109
119
  return {
110
120
  chunk: new AIMessageChunk({
111
- content: fields.coerceContentToString
112
- ? content
113
- : [
114
- {
115
- index: data.index,
116
- ...data.delta,
117
- },
118
- ],
119
- additional_kwargs: {},
121
+ content: data.delta.text,
122
+ }),
123
+ };
124
+ } else {
125
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
126
+ const contentBlock: Record<string, any> = data.delta;
127
+ if ("citation" in contentBlock) {
128
+ contentBlock.citations = [contentBlock.citation];
129
+ delete contentBlock.citation;
130
+ }
131
+ if (
132
+ contentBlock.type === "thinking_delta" ||
133
+ contentBlock.type === "signature_delta"
134
+ ) {
135
+ return {
136
+ chunk: new AIMessageChunk({
137
+ content: [{ index: data.index, ...contentBlock, type: "thinking" }],
138
+ }),
139
+ };
140
+ }
141
+
142
+ return {
143
+ chunk: new AIMessageChunk({
144
+ content: [{ index: data.index, ...contentBlock, type: "text" }],
120
145
  }),
121
146
  };
122
147
  }
123
148
  } else if (
124
- data.type === 'content_block_delta' &&
125
- data.delta.type === 'input_json_delta'
149
+ data.type === "content_block_delta" &&
150
+ data.delta.type === "input_json_delta"
126
151
  ) {
127
152
  return {
128
153
  chunk: new AIMessageChunk({
@@ -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
+ });
@@ -6,7 +6,7 @@ import { HumanMessage, BaseMessage } from '@langchain/core/messages';
6
6
  import { TavilySearchResults } from '@langchain/community/tools/tavily_search';
7
7
  import type * as t from '@/types';
8
8
  import { ChatModelStreamHandler, createContentAggregator } from '@/stream';
9
- import { ToolEndHandler } from '@/events';
9
+ import { ToolEndHandler, ModelEndHandler } from '@/events';
10
10
 
11
11
 
12
12
  import { getArgs } from '@/scripts/args';
@@ -20,7 +20,7 @@ async function testStandardStreaming(): Promise<void> {
20
20
  const { contentParts, aggregateContent } = createContentAggregator();
21
21
  const customHandlers = {
22
22
  [GraphEvents.TOOL_END]: new ToolEndHandler(),
23
- // [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
23
+ [GraphEvents.CHAT_MODEL_END]: new ModelEndHandler(),
24
24
  [GraphEvents.CHAT_MODEL_STREAM]: new ChatModelStreamHandler(),
25
25
  [GraphEvents.ON_RUN_STEP_COMPLETED]: {
26
26
  handle: (event: GraphEvents.ON_RUN_STEP_COMPLETED, data: t.StreamEventData): void => {
@@ -141,14 +141,19 @@ export class SplitStreamHandler {
141
141
  });
142
142
  }
143
143
  };
144
+ getDeltaContent(chunk: t.CustomChunk): string {
145
+ return chunk.choices?.[0]?.delta.content ?? '';
146
+ }
147
+ getReasoningDelta(chunk: t.CustomChunk): string {
148
+ return chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';
149
+ }
144
150
  handle(chunk?: t.CustomChunk): void {
145
151
  if (!chunk) {
146
152
  return;
147
153
  }
148
154
 
149
- const content = chunk.choices?.[0]?.delta.content ?? '';
150
- const reasoning_content = chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';
151
-
155
+ const content = this.getDeltaContent(chunk);
156
+ const reasoning_content = this.getReasoningDelta(chunk);
152
157
  if (!content.length && !reasoning_content.length) {
153
158
  return;
154
159
  }