@librechat/agents 1.7.7 → 1.7.9

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.
Files changed (48) hide show
  1. package/dist/cjs/graphs/Graph.cjs +7 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/llm/anthropic/llm.cjs +117 -0
  4. package/dist/cjs/llm/anthropic/llm.cjs.map +1 -0
  5. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +251 -0
  6. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -0
  7. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +135 -0
  8. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -0
  9. package/dist/cjs/llm/providers.cjs +3 -2
  10. package/dist/cjs/llm/providers.cjs.map +1 -1
  11. package/dist/cjs/llm/text.cjs +73 -0
  12. package/dist/cjs/llm/text.cjs.map +1 -0
  13. package/dist/cjs/run.cjs +2 -1
  14. package/dist/cjs/run.cjs.map +1 -1
  15. package/dist/esm/graphs/Graph.mjs +7 -1
  16. package/dist/esm/graphs/Graph.mjs.map +1 -1
  17. package/dist/esm/llm/anthropic/llm.mjs +115 -0
  18. package/dist/esm/llm/anthropic/llm.mjs.map +1 -0
  19. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +248 -0
  20. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -0
  21. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +133 -0
  22. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -0
  23. package/dist/esm/llm/providers.mjs +3 -2
  24. package/dist/esm/llm/providers.mjs.map +1 -1
  25. package/dist/esm/llm/text.mjs +71 -0
  26. package/dist/esm/llm/text.mjs.map +1 -0
  27. package/dist/esm/run.mjs +2 -1
  28. package/dist/esm/run.mjs.map +1 -1
  29. package/dist/types/graphs/Graph.d.ts +4 -1
  30. package/dist/types/llm/anthropic/llm.d.ts +13 -0
  31. package/dist/types/llm/anthropic/types.d.ts +20 -0
  32. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +14 -0
  33. package/dist/types/llm/anthropic/utils/message_outputs.d.ts +16 -0
  34. package/dist/types/llm/text.d.ts +21 -0
  35. package/dist/types/types/run.d.ts +1 -0
  36. package/package.json +4 -4
  37. package/src/graphs/Graph.ts +8 -0
  38. package/src/llm/anthropic/llm.ts +151 -0
  39. package/src/llm/anthropic/types.ts +32 -0
  40. package/src/llm/anthropic/utils/message_inputs.ts +279 -0
  41. package/src/llm/anthropic/utils/message_outputs.ts +217 -0
  42. package/src/llm/providers.ts +4 -2
  43. package/src/llm/text.ts +90 -0
  44. package/src/run.ts +2 -1
  45. package/src/scripts/abort.ts +4 -3
  46. package/src/scripts/code_exec.ts +1 -1
  47. package/src/scripts/code_exec_simple.ts +1 -1
  48. package/src/types/run.ts +1 -0
@@ -0,0 +1,71 @@
1
+ import { Readable } from 'stream';
2
+
3
+ /* eslint-disable no-console */
4
+ class TextStream extends Readable {
5
+ text;
6
+ currentIndex;
7
+ minChunkSize;
8
+ maxChunkSize;
9
+ delay;
10
+ constructor(text, options = {}) {
11
+ super(options);
12
+ this.text = text;
13
+ this.currentIndex = 0;
14
+ this.minChunkSize = options.minChunkSize ?? 2;
15
+ this.maxChunkSize = options.maxChunkSize ?? 4;
16
+ this.delay = options.delay ?? 20; // Time in milliseconds
17
+ }
18
+ _read() {
19
+ const { delay, minChunkSize, maxChunkSize } = this;
20
+ if (this.currentIndex < this.text.length) {
21
+ setTimeout(() => {
22
+ const remainingChars = this.text.length - this.currentIndex;
23
+ const chunkSize = Math.min(this.randomInt(minChunkSize, maxChunkSize + 1), remainingChars);
24
+ const chunk = this.text.slice(this.currentIndex, this.currentIndex + chunkSize);
25
+ this.push(chunk);
26
+ this.currentIndex += chunkSize;
27
+ }, delay);
28
+ }
29
+ else {
30
+ this.push(null); // signal end of data
31
+ }
32
+ }
33
+ randomInt(min, max) {
34
+ return Math.floor(Math.random() * (max - min)) + min;
35
+ }
36
+ async processTextStream(progressCallback) {
37
+ const streamPromise = new Promise((resolve, reject) => {
38
+ this.on('data', (chunk) => {
39
+ progressCallback(chunk.toString());
40
+ });
41
+ this.on('end', () => {
42
+ resolve();
43
+ });
44
+ this.on('error', (err) => {
45
+ reject(err);
46
+ });
47
+ });
48
+ try {
49
+ await streamPromise;
50
+ }
51
+ catch (err) {
52
+ console.error('[processTextStream] Error in text stream:', err);
53
+ // Handle the error appropriately, e.g., return an error message or throw an error
54
+ }
55
+ }
56
+ async *generateText(progressCallback) {
57
+ const { delay, minChunkSize, maxChunkSize } = this;
58
+ while (this.currentIndex < this.text.length) {
59
+ await new Promise(resolve => setTimeout(resolve, delay));
60
+ const remainingChars = this.text.length - this.currentIndex;
61
+ const chunkSize = Math.min(this.randomInt(minChunkSize, maxChunkSize + 1), remainingChars);
62
+ const chunk = this.text.slice(this.currentIndex, this.currentIndex + chunkSize);
63
+ progressCallback?.(chunk);
64
+ yield chunk;
65
+ this.currentIndex += chunkSize;
66
+ }
67
+ }
68
+ }
69
+
70
+ export { TextStream };
71
+ //# sourceMappingURL=text.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text.mjs","sources":["../../../src/llm/text.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { Readable } from 'stream';\nimport type { ReadableOptions } from 'stream';\nexport interface TextStreamOptions extends ReadableOptions {\n minChunkSize?: number;\n maxChunkSize?: number;\n delay?: number;\n}\n\nexport type ProgressCallback = (chunk: string) => void;\nexport type PostChunkCallback = (chunk: string) => void;\n\nexport class TextStream extends Readable {\n private text: string;\n private currentIndex: number;\n private minChunkSize: number;\n private maxChunkSize: number;\n private delay: number;\n\n constructor(text: string, options: TextStreamOptions = {}) {\n super(options);\n this.text = text;\n this.currentIndex = 0;\n this.minChunkSize = options.minChunkSize ?? 2;\n this.maxChunkSize = options.maxChunkSize ?? 4;\n this.delay = options.delay ?? 20; // Time in milliseconds\n }\n\n _read(): void {\n const { delay, minChunkSize, maxChunkSize } = this;\n\n if (this.currentIndex < this.text.length) {\n setTimeout(() => {\n const remainingChars = this.text.length - this.currentIndex;\n const chunkSize = Math.min(this.randomInt(minChunkSize, maxChunkSize + 1), remainingChars);\n\n const chunk = this.text.slice(this.currentIndex, this.currentIndex + chunkSize);\n this.push(chunk);\n this.currentIndex += chunkSize;\n }, delay);\n } else {\n this.push(null); // signal end of data\n }\n }\n\n private randomInt(min: number, max: number): number {\n return Math.floor(Math.random() * (max - min)) + min;\n }\n\n async processTextStream(progressCallback: ProgressCallback): Promise<void> {\n const streamPromise = new Promise<void>((resolve, reject) => {\n this.on('data', (chunk) => {\n progressCallback(chunk.toString());\n });\n\n this.on('end', () => {\n resolve();\n });\n\n this.on('error', (err) => {\n reject(err);\n });\n });\n\n try {\n await streamPromise;\n } catch (err) {\n console.error('[processTextStream] Error in text stream:', err);\n // Handle the error appropriately, e.g., return an error message or throw an error\n }\n }\n\n async *generateText(progressCallback?: ProgressCallback): AsyncGenerator<string, void, unknown> {\n const { delay, minChunkSize, maxChunkSize } = this;\n\n while (this.currentIndex < this.text.length) {\n await new Promise(resolve => setTimeout(resolve, delay));\n\n const remainingChars = this.text.length - this.currentIndex;\n const chunkSize = Math.min(this.randomInt(minChunkSize, maxChunkSize + 1), remainingChars);\n\n const chunk = this.text.slice(this.currentIndex, this.currentIndex + chunkSize);\n\n progressCallback?.(chunk);\n\n yield chunk;\n this.currentIndex += chunkSize;\n }\n }\n}"],"names":[],"mappings":";;AAAA;AAYM,MAAO,UAAW,SAAQ,QAAQ,CAAA;AAC9B,IAAA,IAAI,CAAS;AACb,IAAA,YAAY,CAAS;AACrB,IAAA,YAAY,CAAS;AACrB,IAAA,YAAY,CAAS;AACrB,IAAA,KAAK,CAAS;IAEtB,WAAY,CAAA,IAAY,EAAE,OAAA,GAA6B,EAAE,EAAA;QACvD,KAAK,CAAC,OAAO,CAAC,CAAC;AACf,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;A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,YAAY,GAAG,SAAS,CAAC,CAAC;AAEhF,YAAA,gBAAgB,GAAG,KAAK,CAAC,CAAC;AAE1B,YAAA,MAAM,KAAK,CAAC;AACZ,YAAA,IAAI,CAAC,YAAY,IAAI,SAAS,CAAC;SAChC;KACF;AACF;;;;"}
package/dist/esm/run.mjs CHANGED
@@ -41,12 +41,13 @@ class Run {
41
41
  this.returnContent = config.returnContent ?? false;
42
42
  }
43
43
  createStandardGraph(config) {
44
- const { llmConfig, instructions, additional_instructions, streamBuffer, toolEnd, tools = [] } = config;
44
+ const { llmConfig, instructions, additional_instructions, signal, streamBuffer, toolEnd, tools = [] } = config;
45
45
  const { provider, ...clientOptions } = llmConfig;
46
46
  const standardGraph = new StandardGraph({
47
47
  runId: this.id,
48
48
  tools,
49
49
  provider,
50
+ signal,
50
51
  instructions,
51
52
  clientOptions,
52
53
  additional_instructions,
@@ -1 +1 @@
1
- {"version":3,"file":"run.mjs","sources":["../../src/run.ts"],"sourcesContent":["// src/run.ts\nimport { PromptTemplate } from '@langchain/core/prompts';\n\nimport type { BaseMessage, MessageContentComplex } from '@langchain/core/messages';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { ClientCallbacks, SystemCallbacks } from '@/graphs/Graph';\nimport type * as t from '@/types';\nimport { GraphEvents, Providers, Callback } from '@/common';\nimport { manualToolStreamProviders } from '@/llm/providers';\nimport { createTitleRunnable } from '@/utils/title';\nimport { StandardGraph } from '@/graphs/Graph';\nimport { HandlerRegistry } from '@/events';\n\nexport class Run<T extends t.BaseGraphState> {\n graphRunnable?: t.CompiledWorkflow<T, Partial<T>, string>;\n // private collab!: CollabGraph;\n // private taskManager!: TaskManager;\n private handlerRegistry: HandlerRegistry;\n id: string;\n Graph: StandardGraph | undefined;\n provider: Providers | undefined;\n returnContent: boolean = false;\n\n private constructor(config: Partial<t.RunConfig>) {\n const runId = config.runId ?? '';\n if (!runId) {\n throw new Error('Run ID not provided');\n }\n\n this.id = runId;\n\n const handlerRegistry = new HandlerRegistry();\n\n if (config.customHandlers) {\n for (const [eventType, handler] of Object.entries(config.customHandlers)) {\n handlerRegistry.register(eventType, handler);\n }\n }\n\n this.handlerRegistry = handlerRegistry;\n\n if (!config.graphConfig) {\n throw new Error('Graph config not provided');\n }\n\n if (config.graphConfig.type === 'standard' || !config.graphConfig.type) {\n this.provider = config.graphConfig.llmConfig.provider;\n this.graphRunnable = this.createStandardGraph(config.graphConfig) as unknown as t.CompiledWorkflow<T, Partial<T>, string>;\n if (this.Graph) {\n this.Graph.handlerRegistry = handlerRegistry;\n }\n }\n\n this.returnContent = config.returnContent ?? false;\n }\n\n private createStandardGraph(config: t.StandardGraphConfig): t.CompiledWorkflow<t.IState, Partial<t.IState>, string> {\n const { llmConfig, instructions, additional_instructions, streamBuffer, toolEnd, tools = [] } = config;\n const { provider, ...clientOptions } = llmConfig;\n\n const standardGraph = new StandardGraph({\n runId: this.id,\n tools,\n provider,\n instructions,\n clientOptions,\n additional_instructions,\n streamBuffer,\n toolEnd,\n });\n this.Graph = standardGraph;\n return standardGraph.createWorkflow();\n }\n\n static async create<T extends t.BaseGraphState>(config: t.RunConfig): Promise<Run<T>> {\n return new Run<T>(config);\n }\n\n getRunMessages(): BaseMessage[] | undefined {\n if (!this.Graph) {\n throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n return this.Graph.getRunMessages();\n }\n\n async processStream(\n inputs: t.IState,\n config: Partial<RunnableConfig> & { version: 'v1' | 'v2'; run_id?: string },\n clientCallbacks?: ClientCallbacks,\n ): Promise<MessageContentComplex[] | undefined> {\n if (!this.graphRunnable) {\n throw new Error('Run not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n if (!this.Graph) {\n throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n\n this.Graph.resetValues();\n const provider = this.Graph.provider;\n const hasTools = this.Graph.tools ? this.Graph.tools.length > 0 : false;\n if (clientCallbacks) {\n /* TODO: conflicts with callback manager */\n const callbacks = config.callbacks as t.ProvidedCallbacks ?? [];\n config.callbacks = callbacks.concat(this.getCallbacks(clientCallbacks));\n }\n\n if (!this.id) {\n throw new Error('Run ID not provided');\n }\n\n config.run_id = this.id;\n config.configurable = Object.assign(config.configurable ?? {}, { run_id: this.id, provider: this.provider });\n\n const stream = this.graphRunnable.streamEvents(inputs, config);\n\n for await (const event of stream) {\n const { data, name, metadata, ...info } = event;\n\n let eventName: t.EventName = info.event;\n if (hasTools && manualToolStreamProviders.has(provider) && eventName === GraphEvents.CHAT_MODEL_STREAM) {\n /* Skipping CHAT_MODEL_STREAM event due to double-call edge case */\n continue;\n }\n\n if (eventName && eventName === GraphEvents.ON_CUSTOM_EVENT) {\n eventName = name;\n }\n\n // console.log(`Event: ${event.event} | Executing Event: ${eventName}`);\n\n const handler = this.handlerRegistry.getHandler(eventName);\n if (handler) {\n handler.handle(eventName, data, metadata, this.Graph);\n }\n }\n\n if (this.returnContent) {\n return this.Graph.getContentParts();\n }\n }\n\n private createSystemCallback<K extends keyof ClientCallbacks>(\n clientCallbacks: ClientCallbacks,\n key: K\n ): SystemCallbacks[K] {\n return ((...args: unknown[]) => {\n const clientCallback = clientCallbacks[key];\n if (clientCallback && this.Graph) {\n (clientCallback as (...args: unknown[]) => void)(this.Graph, ...args);\n }\n }) as SystemCallbacks[K];\n }\n\n getCallbacks(clientCallbacks: ClientCallbacks): SystemCallbacks {\n return {\n [Callback.TOOL_ERROR]: this.createSystemCallback(clientCallbacks, Callback.TOOL_ERROR),\n [Callback.TOOL_START]: this.createSystemCallback(clientCallbacks, Callback.TOOL_START),\n [Callback.TOOL_END]: this.createSystemCallback(clientCallbacks, Callback.TOOL_END),\n };\n }\n\n async generateTitle({\n inputText,\n contentParts,\n titlePrompt,\n clientOptions,\n chainOptions,\n skipLanguage,\n } : {\n inputText: string;\n contentParts: (t.MessageContentComplex | undefined)[];\n titlePrompt?: string;\n skipLanguage?: boolean;\n clientOptions?: t.ClientOptions;\n chainOptions?: Partial<RunnableConfig> | undefined;\n }): Promise<{ language: string; title: string }> {\n const convoTemplate = PromptTemplate.fromTemplate('User: {input}\\nAI: {output}');\n const response = contentParts.map((part) => {\n if (part?.type === 'text') return part.text;\n return '';\n }).join('\\n');\n const convo = (await convoTemplate.invoke({ input: inputText, output: response })).value;\n const model = this.Graph?.getNewModel({\n clientOptions,\n omitOriginalOptions: ['streaming'],\n });\n if (!model) {\n return { language: '', title: '' };\n }\n const chain = await createTitleRunnable(model, titlePrompt);\n return await chain.invoke({ convo, inputText, skipLanguage }, chainOptions) as { language: string; title: string };\n }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;MAaa,GAAG,CAAA;AACd,IAAA,aAAa,CAA6C;;;AAGlD,IAAA,eAAe,CAAkB;AACzC,IAAA,EAAE,CAAS;AACX,IAAA,KAAK,CAA4B;AACjC,IAAA,QAAQ,CAAwB;IAChC,aAAa,GAAY,KAAK,CAAC;AAE/B,IAAA,WAAA,CAAoB,MAA4B,EAAA;AAC9C,QAAA,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC;QACjC,IAAI,CAAC,KAAK,EAAE;AACV,YAAA,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;SACxC;AAED,QAAA,IAAI,CAAC,EAAE,GAAG,KAAK,CAAC;AAEhB,QAAA,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;AAE9C,QAAA,IAAI,MAAM,CAAC,cAAc,EAAE;AACzB,YAAA,KAAK,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE;AACxE,gBAAA,eAAe,CAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;aAC9C;SACF;AAED,QAAA,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;AAEvC,QAAA,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;AACvB,YAAA,MAAM,IAAI,KAAK,CAAC,2BAA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,YAAY,EAAE,EAAE,YAAY,CAAwC,CAAC;KACpH;AACF;;;;"}
1
+ {"version":3,"file":"run.mjs","sources":["../../src/run.ts"],"sourcesContent":["// src/run.ts\nimport { PromptTemplate } from '@langchain/core/prompts';\n\nimport type { BaseMessage, MessageContentComplex } from '@langchain/core/messages';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type { ClientCallbacks, SystemCallbacks } from '@/graphs/Graph';\nimport type * as t from '@/types';\nimport { GraphEvents, Providers, Callback } from '@/common';\nimport { manualToolStreamProviders } from '@/llm/providers';\nimport { createTitleRunnable } from '@/utils/title';\nimport { StandardGraph } from '@/graphs/Graph';\nimport { HandlerRegistry } from '@/events';\n\nexport class Run<T extends t.BaseGraphState> {\n graphRunnable?: t.CompiledWorkflow<T, Partial<T>, string>;\n // private collab!: CollabGraph;\n // private taskManager!: TaskManager;\n private handlerRegistry: HandlerRegistry;\n id: string;\n Graph: StandardGraph | undefined;\n provider: Providers | undefined;\n returnContent: boolean = false;\n\n private constructor(config: Partial<t.RunConfig>) {\n const runId = config.runId ?? '';\n if (!runId) {\n throw new Error('Run ID not provided');\n }\n\n this.id = runId;\n\n const handlerRegistry = new HandlerRegistry();\n\n if (config.customHandlers) {\n for (const [eventType, handler] of Object.entries(config.customHandlers)) {\n handlerRegistry.register(eventType, handler);\n }\n }\n\n this.handlerRegistry = handlerRegistry;\n\n if (!config.graphConfig) {\n throw new Error('Graph config not provided');\n }\n\n if (config.graphConfig.type === 'standard' || !config.graphConfig.type) {\n this.provider = config.graphConfig.llmConfig.provider;\n this.graphRunnable = this.createStandardGraph(config.graphConfig) as unknown as t.CompiledWorkflow<T, Partial<T>, string>;\n if (this.Graph) {\n this.Graph.handlerRegistry = handlerRegistry;\n }\n }\n\n this.returnContent = config.returnContent ?? false;\n }\n\n private createStandardGraph(config: t.StandardGraphConfig): t.CompiledWorkflow<t.IState, Partial<t.IState>, string> {\n const { llmConfig, instructions, additional_instructions, signal, streamBuffer, toolEnd, tools = [] } = config;\n const { provider, ...clientOptions } = llmConfig;\n\n const standardGraph = new StandardGraph({\n runId: this.id,\n tools,\n provider,\n signal,\n instructions,\n clientOptions,\n additional_instructions,\n streamBuffer,\n toolEnd,\n });\n this.Graph = standardGraph;\n return standardGraph.createWorkflow();\n }\n\n static async create<T extends t.BaseGraphState>(config: t.RunConfig): Promise<Run<T>> {\n return new Run<T>(config);\n }\n\n getRunMessages(): BaseMessage[] | undefined {\n if (!this.Graph) {\n throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n return this.Graph.getRunMessages();\n }\n\n async processStream(\n inputs: t.IState,\n config: Partial<RunnableConfig> & { version: 'v1' | 'v2'; run_id?: string },\n clientCallbacks?: ClientCallbacks,\n ): Promise<MessageContentComplex[] | undefined> {\n if (!this.graphRunnable) {\n throw new Error('Run not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n if (!this.Graph) {\n throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n\n this.Graph.resetValues();\n const provider = this.Graph.provider;\n const hasTools = this.Graph.tools ? this.Graph.tools.length > 0 : false;\n if (clientCallbacks) {\n /* TODO: conflicts with callback manager */\n const callbacks = config.callbacks as t.ProvidedCallbacks ?? [];\n config.callbacks = callbacks.concat(this.getCallbacks(clientCallbacks));\n }\n\n if (!this.id) {\n throw new Error('Run ID not provided');\n }\n\n config.run_id = this.id;\n config.configurable = Object.assign(config.configurable ?? {}, { run_id: this.id, provider: this.provider });\n\n const stream = this.graphRunnable.streamEvents(inputs, config);\n\n for await (const event of stream) {\n const { data, name, metadata, ...info } = event;\n\n let eventName: t.EventName = info.event;\n if (hasTools && manualToolStreamProviders.has(provider) && eventName === GraphEvents.CHAT_MODEL_STREAM) {\n /* Skipping CHAT_MODEL_STREAM event due to double-call edge case */\n continue;\n }\n\n if (eventName && eventName === GraphEvents.ON_CUSTOM_EVENT) {\n eventName = name;\n }\n\n // console.log(`Event: ${event.event} | Executing Event: ${eventName}`);\n\n const handler = this.handlerRegistry.getHandler(eventName);\n if (handler) {\n handler.handle(eventName, data, metadata, this.Graph);\n }\n }\n\n if (this.returnContent) {\n return this.Graph.getContentParts();\n }\n }\n\n private createSystemCallback<K extends keyof ClientCallbacks>(\n clientCallbacks: ClientCallbacks,\n key: K\n ): SystemCallbacks[K] {\n return ((...args: unknown[]) => {\n const clientCallback = clientCallbacks[key];\n if (clientCallback && this.Graph) {\n (clientCallback as (...args: unknown[]) => void)(this.Graph, ...args);\n }\n }) as SystemCallbacks[K];\n }\n\n getCallbacks(clientCallbacks: ClientCallbacks): SystemCallbacks {\n return {\n [Callback.TOOL_ERROR]: this.createSystemCallback(clientCallbacks, Callback.TOOL_ERROR),\n [Callback.TOOL_START]: this.createSystemCallback(clientCallbacks, Callback.TOOL_START),\n [Callback.TOOL_END]: this.createSystemCallback(clientCallbacks, Callback.TOOL_END),\n };\n }\n\n async generateTitle({\n inputText,\n contentParts,\n titlePrompt,\n clientOptions,\n chainOptions,\n skipLanguage,\n } : {\n inputText: string;\n contentParts: (t.MessageContentComplex | undefined)[];\n titlePrompt?: string;\n skipLanguage?: boolean;\n clientOptions?: t.ClientOptions;\n chainOptions?: Partial<RunnableConfig> | undefined;\n }): Promise<{ language: string; title: string }> {\n const convoTemplate = PromptTemplate.fromTemplate('User: {input}\\nAI: {output}');\n const response = contentParts.map((part) => {\n if (part?.type === 'text') return part.text;\n return '';\n }).join('\\n');\n const convo = (await convoTemplate.invoke({ input: inputText, output: response })).value;\n const model = this.Graph?.getNewModel({\n clientOptions,\n omitOriginalOptions: ['streaming'],\n });\n if (!model) {\n return { language: '', title: '' };\n }\n const chain = await createTitleRunnable(model, titlePrompt);\n return await chain.invoke({ convo, inputText, skipLanguage }, chainOptions) as { language: string; title: string };\n }\n}\n"],"names":[],"mappings":";;;;;;;AAAA;MAaa,GAAG,CAAA;AACd,IAAA,aAAa,CAA6C;;;AAGlD,IAAA,eAAe,CAAkB;AACzC,IAAA,EAAE,CAAS;AACX,IAAA,KAAK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M,QAAQ,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC,IAAI,KAAI;AACzC,YAAA,IAAI,IAAI,EAAE,IAAI,KAAK,MAAM;gBAAE,OAAO,IAAI,CAAC,IAAI,CAAC;AAC5C,YAAA,OAAO,EAAE,CAAC;AACZ,SAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACd,MAAM,KAAK,GAAG,CAAC,MAAM,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,EAAE,KAAK,CAAC;AACzF,QAAA,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,EAAE,WAAW,CAAC;YACpC,aAAa;YACb,mBAAmB,EAAE,CAAC,WAAW,CAAC;AACnC,SAAA,CAAC,CAAC;QACH,IAAI,CAAC,KAAK,EAAE;YACV,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;SACpC;QACD,MAAM,KAAK,GAAG,MAAM,mBAAmB,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;AAC5D,QAAA,OAAO,MAAM,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE,YAAY,CAAwC,CAAC;KACpH;AACF;;;;"}
@@ -45,6 +45,7 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
45
45
  toolCallStepIds: Map<string, string>;
46
46
  /** The amount of time that should pass before another consecutive API call */
47
47
  streamBuffer: number | undefined;
48
+ signal?: AbortSignal;
48
49
  }
49
50
  export declare class StandardGraph extends Graph<t.BaseGraphState, GraphNode> {
50
51
  private graphState;
@@ -61,8 +62,10 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, GraphNode> {
61
62
  startIndex: number;
62
63
  provider: Providers;
63
64
  toolEnd: boolean;
64
- constructor({ runId, tools, toolMap, provider, clientOptions, instructions, additional_instructions, streamBuffer, toolEnd, }: {
65
+ signal: AbortSignal | undefined;
66
+ constructor({ runId, tools, toolMap, provider, clientOptions, instructions, signal, additional_instructions, streamBuffer, toolEnd, }: {
65
67
  runId?: string;
68
+ signal?: AbortSignal;
66
69
  provider: Providers;
67
70
  tools?: t.GenericTool[];
68
71
  toolMap?: t.ToolMap;
@@ -0,0 +1,13 @@
1
+ import { ChatAnthropicMessages } from '@langchain/anthropic';
2
+ import { ChatGenerationChunk } from '@langchain/core/outputs';
3
+ import type { BaseMessage } from '@langchain/core/messages';
4
+ import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
5
+ import type { AnthropicInput } from '@langchain/anthropic';
6
+ export type CustomAnthropicInput = AnthropicInput & {
7
+ _lc_stream_delay?: number;
8
+ };
9
+ export declare class CustomAnthropic extends ChatAnthropicMessages {
10
+ _lc_stream_delay: number;
11
+ constructor(fields: CustomAnthropicInput);
12
+ _streamResponseChunks(messages: BaseMessage[], options: this['ParsedCallOptions'], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
13
+ }
@@ -0,0 +1,20 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ import type { Tool as AnthropicTool } from '@anthropic-ai/sdk/resources';
3
+ import { BindToolsInput } from '@langchain/core/language_models/chat_models';
4
+ export type AnthropicToolResponse = {
5
+ type: 'tool_use';
6
+ id: string;
7
+ name: string;
8
+ input: Record<string, any>;
9
+ };
10
+ export type AnthropicMessageParam = Anthropic.MessageParam;
11
+ export type AnthropicMessageResponse = Anthropic.ContentBlock | AnthropicToolResponse;
12
+ export type AnthropicMessageCreateParams = Anthropic.MessageCreateParamsNonStreaming;
13
+ export type AnthropicStreamingMessageCreateParams = Anthropic.MessageCreateParamsStreaming;
14
+ export type AnthropicMessageStreamEvent = Anthropic.MessageStreamEvent;
15
+ export type AnthropicRequestOptions = Anthropic.RequestOptions;
16
+ export type AnthropicToolChoice = {
17
+ type: 'tool';
18
+ name: string;
19
+ } | 'any' | 'auto' | 'none' | string;
20
+ export type ChatAnthropicToolType = AnthropicTool | BindToolsInput;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * This util file contains functions for converting LangChain messages to Anthropic messages.
3
+ */
4
+ import { BaseMessage } from '@langchain/core/messages';
5
+ import { ToolCall } from '@langchain/core/messages/tool';
6
+ import type { AnthropicMessageCreateParams, AnthropicToolResponse } from '@/llm/anthropic/types';
7
+ export declare function _convertLangChainToolCallToAnthropic(toolCall: ToolCall): AnthropicToolResponse;
8
+ /**
9
+ * Formats messages as a prompt for the model.
10
+ * Used in LangSmith, export is important here.
11
+ * @param messages The base messages to format as a prompt.
12
+ * @returns The formatted prompt.
13
+ */
14
+ export declare function _convertMessagesToAnthropicPayload(messages: BaseMessage[]): AnthropicMessageCreateParams;
@@ -0,0 +1,16 @@
1
+ /**
2
+ * This util file contains functions for converting Anthropic messages to LangChain messages.
3
+ */
4
+ import Anthropic from '@anthropic-ai/sdk';
5
+ import { AIMessageChunk } from '@langchain/core/messages';
6
+ import { ToolCall } from '@langchain/core/messages/tool';
7
+ import { ChatGeneration } from '@langchain/core/outputs';
8
+ import { AnthropicMessageResponse } from '../types.js';
9
+ export declare function extractToolCalls(content: Record<string, any>[]): ToolCall[];
10
+ export declare function _makeMessageChunkFromAnthropicEvent(data: Anthropic.Messages.RawMessageStreamEvent, fields: {
11
+ streamUsage: boolean;
12
+ coerceContentToString: boolean;
13
+ }): {
14
+ chunk: AIMessageChunk;
15
+ } | null;
16
+ export declare function anthropicResponseToChatMessages(messages: AnthropicMessageResponse[], additionalKwargs: Record<string, unknown>): ChatGeneration[];
@@ -0,0 +1,21 @@
1
+ import { Readable } from 'stream';
2
+ import type { ReadableOptions } from 'stream';
3
+ export interface TextStreamOptions extends ReadableOptions {
4
+ minChunkSize?: number;
5
+ maxChunkSize?: number;
6
+ delay?: number;
7
+ }
8
+ export type ProgressCallback = (chunk: string) => void;
9
+ export type PostChunkCallback = (chunk: string) => void;
10
+ export declare class TextStream extends Readable {
11
+ private text;
12
+ private currentIndex;
13
+ private minChunkSize;
14
+ private maxChunkSize;
15
+ private delay;
16
+ constructor(text: string, options?: TextStreamOptions);
17
+ _read(): void;
18
+ private randomInt;
19
+ processTextStream(progressCallback: ProgressCallback): Promise<void>;
20
+ generateText(progressCallback?: ProgressCallback): AsyncGenerator<string, void, unknown>;
21
+ }
@@ -17,6 +17,7 @@ export type StandardGraphConfig = {
17
17
  toolMap?: t.ToolMap;
18
18
  additional_instructions?: string;
19
19
  streamBuffer?: number;
20
+ signal?: AbortSignal;
20
21
  clientOptions?: Record<string, unknown>;
21
22
  toolEnd?: boolean;
22
23
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "1.7.7",
3
+ "version": "1.7.9",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -43,11 +43,11 @@
43
43
  "content": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/content.ts --provider 'anthropic' --name 'Jo' --location 'New York, NY'",
44
44
  "stream": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/stream.ts --provider 'anthropic' --name 'Jo' --location 'New York, NY'",
45
45
  "code_exec": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
46
- "code_exec_simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_simple.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
47
- "simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
46
+ "code_exec_simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_simple.ts --provider 'anthropic' --name 'Jo' --location 'New York, NY'",
47
+ "simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider 'anthropic' --name 'Jo' --location 'New York, NY'",
48
48
  "memory": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/memory.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
49
49
  "tool-test": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/tools.ts --provider 'anthropic' --name 'Jo' --location 'New York, NY'",
50
- "abort": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/abort.ts --provider 'anthropic' --name 'Jo' --location 'New York, NY'",
50
+ "abort": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/abort.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
51
51
  "start:cli2": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/cli2.ts --provider 'anthropic' --name 'Jo' --location 'New York, NY'",
52
52
  "script2": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/proto/example_test.ts",
53
53
  "script3": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/proto/example_test_anthropic.ts",
@@ -62,6 +62,7 @@ export abstract class Graph<
62
62
  toolCallStepIds: Map<string, string> = new Map();
63
63
  /** The amount of time that should pass before another consecutive API call */
64
64
  streamBuffer: number | undefined;
65
+ signal?: AbortSignal;
65
66
  }
66
67
 
67
68
  export class StandardGraph extends Graph<
@@ -82,6 +83,7 @@ export class StandardGraph extends Graph<
82
83
  startIndex: number = 0;
83
84
  provider: Providers;
84
85
  toolEnd: boolean;
86
+ signal: AbortSignal | undefined;
85
87
 
86
88
  constructor({
87
89
  runId,
@@ -90,11 +92,13 @@ export class StandardGraph extends Graph<
90
92
  provider,
91
93
  clientOptions,
92
94
  instructions,
95
+ signal,
93
96
  additional_instructions = '',
94
97
  streamBuffer,
95
98
  toolEnd = false,
96
99
  } : {
97
100
  runId?: string;
101
+ signal?: AbortSignal;
98
102
  provider: Providers;
99
103
  tools?: t.GenericTool[];
100
104
  toolMap?: t.ToolMap;
@@ -109,6 +113,7 @@ export class StandardGraph extends Graph<
109
113
  this.tools = tools;
110
114
  this.toolMap = toolMap;
111
115
  this.provider = provider;
116
+ this.signal = signal;
112
117
  this.clientOptions = clientOptions;
113
118
  this.streamBuffer = streamBuffer;
114
119
  this.graphState = this.createGraphState();
@@ -277,6 +282,9 @@ export class StandardGraph extends Graph<
277
282
  if (!config || !provider) {
278
283
  throw new Error(`No ${config ? 'provider' : 'config'} provided`);
279
284
  }
285
+ if (!config.signal) {
286
+ config.signal = this.signal;
287
+ }
280
288
  this.config = config;
281
289
  const { messages } = state;
282
290
 
@@ -0,0 +1,151 @@
1
+ import { AIMessageChunk } from '@langchain/core/messages';
2
+ import { ChatAnthropicMessages } from '@langchain/anthropic';
3
+ import { ChatGenerationChunk } from '@langchain/core/outputs';
4
+ import type { BaseMessage, MessageContentComplex } from '@langchain/core/messages';
5
+ import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
6
+ import type { AnthropicInput } from '@langchain/anthropic';
7
+ import type { AnthropicMessageCreateParams } from '@/llm/anthropic/types';
8
+ import { _makeMessageChunkFromAnthropicEvent } from './utils/message_outputs';
9
+ import { _convertMessagesToAnthropicPayload } from './utils/message_inputs';
10
+ import { TextStream } from '@/llm/text';
11
+
12
+ function _toolsInParams(params: AnthropicMessageCreateParams): boolean {
13
+ return !!(params.tools && params.tools.length > 0);
14
+ }
15
+
16
+ function extractToken(chunk: AIMessageChunk): [string, 'string' | 'input' | 'content'] | [undefined] {
17
+ if (typeof chunk.content === 'string') {
18
+ return [chunk.content, 'string'];
19
+ } else if (
20
+ Array.isArray(chunk.content) &&
21
+ chunk.content.length >= 1 &&
22
+ 'input' in chunk.content[0]
23
+ ) {
24
+ return typeof chunk.content[0].input === 'string'
25
+ ? [chunk.content[0].input, 'input']
26
+ : [JSON.stringify(chunk.content[0].input), 'input'];
27
+ } else if (
28
+ Array.isArray(chunk.content) &&
29
+ chunk.content.length >= 1 &&
30
+ 'text' in chunk.content[0]
31
+ ) {
32
+ return [chunk.content[0].text, 'content'];
33
+ }
34
+ return [undefined];
35
+ }
36
+
37
+ function cloneChunk(text: string, tokenType: string, chunk: AIMessageChunk): AIMessageChunk {
38
+ if (tokenType === 'string') {
39
+ return new AIMessageChunk(Object.assign({}, chunk, { content: text }));
40
+ } else if (tokenType === 'input') {
41
+ return chunk;
42
+ }
43
+ const content = chunk.content[0] as MessageContentComplex;
44
+ if (tokenType === 'content' && content.type === 'text') {
45
+ return new AIMessageChunk(Object.assign({}, chunk, { content: [Object.assign({}, content, { text })] }));
46
+ } else if (tokenType === 'content' && content.type === 'text_delta') {
47
+ return new AIMessageChunk(Object.assign({}, chunk, { content: [Object.assign({}, content, { text })] }));
48
+ }
49
+
50
+ return chunk;
51
+ }
52
+
53
+ export type CustomAnthropicInput = AnthropicInput & { _lc_stream_delay?: number };
54
+
55
+ export class CustomAnthropic extends ChatAnthropicMessages {
56
+ _lc_stream_delay: number;
57
+ constructor(fields: CustomAnthropicInput) {
58
+ super(fields);
59
+ this._lc_stream_delay = fields._lc_stream_delay ?? 25;
60
+ }
61
+
62
+ async *_streamResponseChunks(
63
+ messages: BaseMessage[],
64
+ options: this['ParsedCallOptions'],
65
+ runManager?: CallbackManagerForLLMRun
66
+ ): AsyncGenerator<ChatGenerationChunk> {
67
+ const params = this.invocationParams(options);
68
+ const formattedMessages = _convertMessagesToAnthropicPayload(messages);
69
+ const coerceContentToString = !_toolsInParams({
70
+ ...params,
71
+ ...formattedMessages,
72
+ stream: false,
73
+ });
74
+
75
+ const stream = await this.createStreamWithRetry(
76
+ {
77
+ ...params,
78
+ ...formattedMessages,
79
+ stream: true,
80
+ },
81
+ {
82
+ headers: options.headers,
83
+ }
84
+ );
85
+
86
+ for await (const data of stream) {
87
+ if (options.signal?.aborted) {
88
+ stream.controller.abort();
89
+ throw new Error('AbortError: User aborted the request.');
90
+ }
91
+ const shouldStreamUsage = this.streamUsage ?? options.streamUsage;
92
+ const result = _makeMessageChunkFromAnthropicEvent(data, {
93
+ streamUsage: shouldStreamUsage,
94
+ coerceContentToString,
95
+ });
96
+ if (!result) continue;
97
+
98
+ const { chunk } = result;
99
+
100
+ // Extract the text content token for text field and runManager.
101
+ const [token = '', tokenType] = extractToken(chunk);
102
+ const createGenerationChunk = (text: string, incomingChunk: AIMessageChunk): ChatGenerationChunk => {
103
+ return new ChatGenerationChunk({
104
+ message: new AIMessageChunk({
105
+ // Just yield chunk as it is and tool_use will be concat by BaseChatModel._generateUncached().
106
+ content: incomingChunk.content,
107
+ additional_kwargs: incomingChunk.additional_kwargs,
108
+ tool_call_chunks: incomingChunk.tool_call_chunks,
109
+ usage_metadata: shouldStreamUsage ? incomingChunk.usage_metadata : undefined,
110
+ response_metadata: incomingChunk.response_metadata,
111
+ id: incomingChunk.id,
112
+ }),
113
+ text,
114
+ });
115
+ };
116
+
117
+ if (!tokenType || tokenType === 'input') {
118
+ const generationChunk = createGenerationChunk(token, chunk);
119
+ yield generationChunk;
120
+ await runManager?.handleLLMNewToken(
121
+ token,
122
+ undefined,
123
+ undefined,
124
+ undefined,
125
+ undefined,
126
+ { chunk: generationChunk }
127
+ );
128
+ continue;
129
+ }
130
+
131
+ const textStream = new TextStream(token, {
132
+ delay: this._lc_stream_delay,
133
+ });
134
+ for await (const currentToken of textStream.generateText()) {
135
+ const newChunk = cloneChunk(currentToken, tokenType, chunk);
136
+ const generationChunk = createGenerationChunk(currentToken, newChunk);
137
+ yield generationChunk;
138
+
139
+ await runManager?.handleLLMNewToken(
140
+ token,
141
+ undefined,
142
+ undefined,
143
+ undefined,
144
+ undefined,
145
+ { chunk: generationChunk }
146
+ );
147
+ }
148
+ }
149
+ }
150
+
151
+ }
@@ -0,0 +1,32 @@
1
+ // eslint-disable-next-line import/no-named-as-default
2
+ import Anthropic from '@anthropic-ai/sdk';
3
+ import type { Tool as AnthropicTool } from '@anthropic-ai/sdk/resources';
4
+ import { BindToolsInput } from '@langchain/core/language_models/chat_models';
5
+
6
+ export type AnthropicToolResponse = {
7
+ type: 'tool_use';
8
+ id: string;
9
+ name: string;
10
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
11
+ input: Record<string, any>;
12
+ };
13
+ export type AnthropicMessageParam = Anthropic.MessageParam;
14
+ export type AnthropicMessageResponse =
15
+ | Anthropic.ContentBlock
16
+ | AnthropicToolResponse;
17
+ export type AnthropicMessageCreateParams =
18
+ Anthropic.MessageCreateParamsNonStreaming;
19
+ export type AnthropicStreamingMessageCreateParams =
20
+ Anthropic.MessageCreateParamsStreaming;
21
+ export type AnthropicMessageStreamEvent = Anthropic.MessageStreamEvent;
22
+ export type AnthropicRequestOptions = Anthropic.RequestOptions;
23
+ export type AnthropicToolChoice =
24
+ | {
25
+ type: 'tool';
26
+ name: string;
27
+ }
28
+ | 'any'
29
+ | 'auto'
30
+ | 'none'
31
+ | string;
32
+ export type ChatAnthropicToolType = AnthropicTool | BindToolsInput;