@librechat/agents 3.0.42 → 3.0.43
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/agents/AgentContext.cjs +134 -70
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +1 -1
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +7 -13
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +5 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/tools.cjs +85 -0
- package/dist/cjs/messages/tools.cjs.map +1 -0
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +55 -32
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +30 -13
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +134 -70
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -1
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +8 -14
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/tools.mjs +82 -0
- package/dist/esm/messages/tools.mjs.map +1 -0
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +54 -33
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +30 -13
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +37 -17
- package/dist/types/common/enum.d.ts +1 -1
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/tools.d.ts +17 -0
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +15 -23
- package/dist/types/tools/ToolNode.d.ts +9 -7
- package/dist/types/types/tools.d.ts +5 -5
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +157 -85
- package/src/agents/__tests__/AgentContext.test.ts +805 -0
- package/src/common/enum.ts +1 -1
- package/src/graphs/Graph.ts +9 -21
- package/src/messages/__tests__/tools.test.ts +473 -0
- package/src/messages/index.ts +1 -0
- package/src/messages/tools.ts +99 -0
- package/src/scripts/code_exec_ptc.ts +78 -21
- package/src/scripts/programmatic_exec.ts +3 -3
- package/src/scripts/programmatic_exec_agent.ts +4 -4
- package/src/tools/ProgrammaticToolCalling.ts +71 -39
- package/src/tools/ToolNode.ts +33 -14
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.ts +9 -9
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +180 -5
- package/src/types/tools.ts +3 -5
|
@@ -7,16 +7,6 @@ var _enum = require('../common/enum.cjs');
|
|
|
7
7
|
|
|
8
8
|
/* eslint-disable no-console */
|
|
9
9
|
// src/agents/AgentContext.ts
|
|
10
|
-
/**
|
|
11
|
-
* Checks if a tool allows the specified caller type.
|
|
12
|
-
* Default is 'direct' only if allowed_callers is not specified.
|
|
13
|
-
*/
|
|
14
|
-
function toolAllowsCaller(toolDef, caller) {
|
|
15
|
-
if (!toolDef)
|
|
16
|
-
return false;
|
|
17
|
-
const allowedCallers = toolDef.allowed_callers ?? ['direct'];
|
|
18
|
-
return allowedCallers.includes(caller);
|
|
19
|
-
}
|
|
20
10
|
/**
|
|
21
11
|
* Encapsulates agent-specific state that can vary between agents in a multi-agent system
|
|
22
12
|
*/
|
|
@@ -44,12 +34,16 @@ class AgentContext {
|
|
|
44
34
|
useLegacyContent,
|
|
45
35
|
});
|
|
46
36
|
if (tokenCounter) {
|
|
37
|
+
// Initialize system runnable BEFORE async tool token calculation
|
|
38
|
+
// This ensures system message tokens are in instructionTokens before
|
|
39
|
+
// updateTokenMapWithInstructions is called
|
|
40
|
+
agentContext.initializeSystemRunnable();
|
|
47
41
|
const tokenMap = indexTokenCountMap || {};
|
|
48
42
|
agentContext.indexTokenCountMap = tokenMap;
|
|
49
43
|
agentContext.tokenCalculationPromise = agentContext
|
|
50
44
|
.calculateInstructionTokens(tokenCounter)
|
|
51
45
|
.then(() => {
|
|
52
|
-
// Update token map with instruction tokens
|
|
46
|
+
// Update token map with instruction tokens (includes system + tool tokens)
|
|
53
47
|
agentContext.updateTokenMapWithInstructions(tokenMap);
|
|
54
48
|
})
|
|
55
49
|
.catch((err) => {
|
|
@@ -108,8 +102,12 @@ class AgentContext {
|
|
|
108
102
|
currentTokenType = _enum.ContentTypes.TEXT;
|
|
109
103
|
/** Whether tools should end the workflow */
|
|
110
104
|
toolEnd = false;
|
|
111
|
-
/**
|
|
112
|
-
|
|
105
|
+
/** Cached system runnable (created lazily) */
|
|
106
|
+
cachedSystemRunnable;
|
|
107
|
+
/** Whether system runnable needs rebuild (set when discovered tools change) */
|
|
108
|
+
systemRunnableStale = true;
|
|
109
|
+
/** Cached system message token count (separate from tool tokens) */
|
|
110
|
+
systemMessageTokens = 0;
|
|
113
111
|
/** Promise for token calculation initialization */
|
|
114
112
|
tokenCalculationPromise;
|
|
115
113
|
/** Format content blocks as strings (for legacy compatibility) */
|
|
@@ -136,24 +134,112 @@ class AgentContext {
|
|
|
136
134
|
this.instructionTokens = instructionTokens;
|
|
137
135
|
}
|
|
138
136
|
this.useLegacyContent = useLegacyContent ?? false;
|
|
139
|
-
this.systemRunnable = this.createSystemRunnable();
|
|
140
137
|
}
|
|
141
138
|
/**
|
|
142
|
-
*
|
|
139
|
+
* Builds instructions text for tools that are ONLY callable via programmatic code execution.
|
|
140
|
+
* These tools cannot be called directly by the LLM but are available through the
|
|
141
|
+
* run_tools_with_code tool.
|
|
142
|
+
*
|
|
143
|
+
* Includes:
|
|
144
|
+
* - Code_execution-only tools that are NOT deferred
|
|
145
|
+
* - Code_execution-only tools that ARE deferred but have been discovered via tool search
|
|
146
|
+
*/
|
|
147
|
+
buildProgrammaticOnlyToolsInstructions() {
|
|
148
|
+
if (!this.toolRegistry)
|
|
149
|
+
return '';
|
|
150
|
+
const programmaticOnlyTools = [];
|
|
151
|
+
for (const [name, toolDef] of this.toolRegistry) {
|
|
152
|
+
const allowedCallers = toolDef.allowed_callers ?? ['direct'];
|
|
153
|
+
const isCodeExecutionOnly = allowedCallers.includes('code_execution') &&
|
|
154
|
+
!allowedCallers.includes('direct');
|
|
155
|
+
if (!isCodeExecutionOnly)
|
|
156
|
+
continue;
|
|
157
|
+
// Include if: not deferred OR deferred but discovered
|
|
158
|
+
const isDeferred = toolDef.defer_loading === true;
|
|
159
|
+
const isDiscovered = this.discoveredToolNames.has(name);
|
|
160
|
+
if (!isDeferred || isDiscovered) {
|
|
161
|
+
programmaticOnlyTools.push(toolDef);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (programmaticOnlyTools.length === 0)
|
|
165
|
+
return '';
|
|
166
|
+
const toolDescriptions = programmaticOnlyTools
|
|
167
|
+
.map((tool) => {
|
|
168
|
+
let desc = `- **${tool.name}**`;
|
|
169
|
+
if (tool.description != null && tool.description !== '') {
|
|
170
|
+
desc += `: ${tool.description}`;
|
|
171
|
+
}
|
|
172
|
+
if (tool.parameters) {
|
|
173
|
+
desc += `\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\n/g, '\n ')}`;
|
|
174
|
+
}
|
|
175
|
+
return desc;
|
|
176
|
+
})
|
|
177
|
+
.join('\n\n');
|
|
178
|
+
return ('\n\n## Programmatic-Only Tools\n\n' +
|
|
179
|
+
'The following tools are available exclusively through the `run_tools_with_code` tool. ' +
|
|
180
|
+
'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\n\n' +
|
|
181
|
+
toolDescriptions);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Gets the system runnable, creating it lazily if needed.
|
|
185
|
+
* Includes instructions, additional instructions, and programmatic-only tools documentation.
|
|
186
|
+
* Only rebuilds when marked stale (via markToolsAsDiscovered).
|
|
187
|
+
*/
|
|
188
|
+
get systemRunnable() {
|
|
189
|
+
// Return cached if not stale
|
|
190
|
+
if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {
|
|
191
|
+
return this.cachedSystemRunnable;
|
|
192
|
+
}
|
|
193
|
+
// Stale or first access - rebuild
|
|
194
|
+
const instructionsString = this.buildInstructionsString();
|
|
195
|
+
this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
|
|
196
|
+
this.systemRunnableStale = false;
|
|
197
|
+
return this.cachedSystemRunnable;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Explicitly initializes the system runnable.
|
|
201
|
+
* Call this before async token calculation to ensure system message tokens are counted first.
|
|
202
|
+
*/
|
|
203
|
+
initializeSystemRunnable() {
|
|
204
|
+
if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {
|
|
205
|
+
const instructionsString = this.buildInstructionsString();
|
|
206
|
+
this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
|
|
207
|
+
this.systemRunnableStale = false;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Builds the raw instructions string (without creating SystemMessage).
|
|
143
212
|
*/
|
|
144
|
-
|
|
145
|
-
let
|
|
213
|
+
buildInstructionsString() {
|
|
214
|
+
let result = this.instructions ?? '';
|
|
146
215
|
if (this.additionalInstructions != null &&
|
|
147
216
|
this.additionalInstructions !== '') {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
: this.additionalInstructions;
|
|
217
|
+
result = result
|
|
218
|
+
? `${result}\n\n${this.additionalInstructions}`
|
|
219
|
+
: this.additionalInstructions;
|
|
152
220
|
}
|
|
221
|
+
const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();
|
|
222
|
+
if (programmaticToolsDoc) {
|
|
223
|
+
result = result
|
|
224
|
+
? `${result}${programmaticToolsDoc}`
|
|
225
|
+
: programmaticToolsDoc;
|
|
226
|
+
}
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Build system runnable from pre-built instructions string.
|
|
231
|
+
* Only called when content has actually changed.
|
|
232
|
+
*/
|
|
233
|
+
buildSystemRunnable(instructionsString) {
|
|
234
|
+
if (!instructionsString) {
|
|
235
|
+
// Remove previous tokens if we had a system message before
|
|
236
|
+
this.instructionTokens -= this.systemMessageTokens;
|
|
237
|
+
this.systemMessageTokens = 0;
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
let finalInstructions = instructionsString;
|
|
153
241
|
// Handle Anthropic prompt caching
|
|
154
|
-
if (
|
|
155
|
-
finalInstructions !== '' &&
|
|
156
|
-
this.provider === _enum.Providers.ANTHROPIC) {
|
|
242
|
+
if (this.provider === _enum.Providers.ANTHROPIC) {
|
|
157
243
|
const anthropicOptions = this.clientOptions;
|
|
158
244
|
const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders;
|
|
159
245
|
const anthropicBeta = defaultHeaders?.['anthropic-beta'];
|
|
@@ -163,29 +249,32 @@ class AgentContext {
|
|
|
163
249
|
content: [
|
|
164
250
|
{
|
|
165
251
|
type: 'text',
|
|
166
|
-
text:
|
|
252
|
+
text: instructionsString,
|
|
167
253
|
cache_control: { type: 'ephemeral' },
|
|
168
254
|
},
|
|
169
255
|
],
|
|
170
256
|
};
|
|
171
257
|
}
|
|
172
258
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
return [systemMessage, ...messages];
|
|
180
|
-
}).withConfig({ runName: 'prompt' });
|
|
259
|
+
const systemMessage = new messages.SystemMessage(finalInstructions);
|
|
260
|
+
// Update token counts (subtract old, add new)
|
|
261
|
+
if (this.tokenCounter) {
|
|
262
|
+
this.instructionTokens -= this.systemMessageTokens;
|
|
263
|
+
this.systemMessageTokens = this.tokenCounter(systemMessage);
|
|
264
|
+
this.instructionTokens += this.systemMessageTokens;
|
|
181
265
|
}
|
|
182
|
-
return
|
|
266
|
+
return runnables.RunnableLambda.from((messages) => {
|
|
267
|
+
return [systemMessage, ...messages];
|
|
268
|
+
}).withConfig({ runName: 'prompt' });
|
|
183
269
|
}
|
|
184
270
|
/**
|
|
185
271
|
* Reset context for a new run
|
|
186
272
|
*/
|
|
187
273
|
reset() {
|
|
188
274
|
this.instructionTokens = 0;
|
|
275
|
+
this.systemMessageTokens = 0;
|
|
276
|
+
this.cachedSystemRunnable = undefined;
|
|
277
|
+
this.systemRunnableStale = true;
|
|
189
278
|
this.lastToken = undefined;
|
|
190
279
|
this.indexTokenCountMap = {};
|
|
191
280
|
this.currentUsage = undefined;
|
|
@@ -236,41 +325,6 @@ class AgentContext {
|
|
|
236
325
|
// Add tool tokens to existing instruction tokens (which may already include system message tokens)
|
|
237
326
|
this.instructionTokens += toolTokens;
|
|
238
327
|
}
|
|
239
|
-
/**
|
|
240
|
-
* Gets a map of tools that allow programmatic (code_execution) calling.
|
|
241
|
-
* Filters toolMap based on toolRegistry's allowed_callers settings.
|
|
242
|
-
* @returns ToolMap containing only tools that allow code_execution
|
|
243
|
-
*/
|
|
244
|
-
getProgrammaticToolMap() {
|
|
245
|
-
const programmaticMap = new Map();
|
|
246
|
-
if (!this.toolMap) {
|
|
247
|
-
return programmaticMap;
|
|
248
|
-
}
|
|
249
|
-
for (const [name, tool] of this.toolMap) {
|
|
250
|
-
const toolDef = this.toolRegistry?.get(name);
|
|
251
|
-
if (toolAllowsCaller(toolDef, 'code_execution')) {
|
|
252
|
-
programmaticMap.set(name, tool);
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
return programmaticMap;
|
|
256
|
-
}
|
|
257
|
-
/**
|
|
258
|
-
* Gets tool definitions for tools that allow programmatic calling.
|
|
259
|
-
* Used to send to the Code API for stub generation.
|
|
260
|
-
* @returns Array of LCTool definitions for programmatic tools
|
|
261
|
-
*/
|
|
262
|
-
getProgrammaticToolDefs() {
|
|
263
|
-
if (!this.toolRegistry) {
|
|
264
|
-
return [];
|
|
265
|
-
}
|
|
266
|
-
const defs = [];
|
|
267
|
-
for (const [_name, toolDef] of this.toolRegistry) {
|
|
268
|
-
if (toolAllowsCaller(toolDef, 'code_execution')) {
|
|
269
|
-
defs.push(toolDef);
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
return defs;
|
|
273
|
-
}
|
|
274
328
|
/**
|
|
275
329
|
* Gets the tool registry for deferred tools (for tool search).
|
|
276
330
|
* @param onlyDeferred If true, only returns tools with defer_loading=true
|
|
@@ -291,12 +345,22 @@ class AgentContext {
|
|
|
291
345
|
/**
|
|
292
346
|
* Marks tools as discovered via tool search.
|
|
293
347
|
* Discovered tools will be included in the next model binding.
|
|
348
|
+
* Only marks system runnable stale if NEW tools were actually added.
|
|
294
349
|
* @param toolNames - Array of discovered tool names
|
|
350
|
+
* @returns true if any new tools were discovered
|
|
295
351
|
*/
|
|
296
352
|
markToolsAsDiscovered(toolNames) {
|
|
353
|
+
let hasNewDiscoveries = false;
|
|
297
354
|
for (const name of toolNames) {
|
|
298
|
-
this.discoveredToolNames.
|
|
355
|
+
if (!this.discoveredToolNames.has(name)) {
|
|
356
|
+
this.discoveredToolNames.add(name);
|
|
357
|
+
hasNewDiscoveries = true;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (hasNewDiscoveries) {
|
|
361
|
+
this.systemRunnableStale = true;
|
|
299
362
|
}
|
|
363
|
+
return hasNewDiscoveries;
|
|
300
364
|
}
|
|
301
365
|
/**
|
|
302
366
|
* Gets tools that should be bound to the LLM.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentContext.cjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Checks if a tool allows the specified caller type.\n * Default is 'direct' only if allowed_callers is not specified.\n */\nfunction toolAllowsCaller(\n toolDef: t.LCTool | undefined,\n caller: t.AllowedCaller\n): boolean {\n if (!toolDef) return false;\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes(caller);\n}\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** System runnable for this agent */\n systemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n\n this.systemRunnable = this.createSystemRunnable();\n }\n\n /**\n * Create system runnable from instructions and calculate tokens if tokenCounter is available\n */\n private createSystemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n let finalInstructions: string | BaseMessageFields | undefined =\n this.instructions;\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n finalInstructions =\n finalInstructions != null && finalInstructions\n ? `${finalInstructions}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n // Handle Anthropic prompt caching\n if (\n finalInstructions != null &&\n finalInstructions !== '' &&\n this.provider === Providers.ANTHROPIC\n ) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: this.instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n if (finalInstructions != null && finalInstructions !== '') {\n const systemMessage = new SystemMessage(finalInstructions);\n\n if (this.tokenCounter) {\n this.instructionTokens += this.tokenCounter(systemMessage);\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n return undefined;\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets a map of tools that allow programmatic (code_execution) calling.\n * Filters toolMap based on toolRegistry's allowed_callers settings.\n * @returns ToolMap containing only tools that allow code_execution\n */\n getProgrammaticToolMap(): t.ToolMap {\n const programmaticMap: t.ToolMap = new Map();\n\n if (!this.toolMap) {\n return programmaticMap;\n }\n\n for (const [name, tool] of this.toolMap) {\n const toolDef = this.toolRegistry?.get(name);\n if (toolAllowsCaller(toolDef, 'code_execution')) {\n programmaticMap.set(name, tool);\n }\n }\n\n return programmaticMap;\n }\n\n /**\n * Gets tool definitions for tools that allow programmatic calling.\n * Used to send to the Code API for stub generation.\n * @returns Array of LCTool definitions for programmatic tools\n */\n getProgrammaticToolDefs(): t.LCTool[] {\n if (!this.toolRegistry) {\n return [];\n }\n\n const defs: t.LCTool[] = [];\n for (const [_name, toolDef] of this.toolRegistry) {\n if (toolAllowsCaller(toolDef, 'code_execution')) {\n defs.push(toolDef);\n }\n }\n\n return defs;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * @param toolNames - Array of discovered tool names\n */\n markToolsAsDiscovered(toolNames: string[]): void {\n for (const name of toolNames) {\n this.discoveredToolNames.add(name);\n }\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":["ContentTypes","Providers","SystemMessage","RunnableLambda","zodToJsonSchema"],"mappings":";;;;;;;AAAA;AACA;AAcA;;;AAGG;AACH,SAAS,gBAAgB,CACvB,OAA6B,EAC7B,MAAuB,EAAA;AAEvB,IAAA,IAAI,CAAC,OAAO;AAAE,QAAA,OAAO,KAAK;IAC1B,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,IAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,MAAM,CAAC;AACxC;AAEA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MAAM,EACJ,OAAO,EACP,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,GACjB,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,QAA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AAO,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;YACjD,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO,IAAI,CAAC;;;YAId,IAAI,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;;gBAE3C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,gBAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;;;YAI1C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,YAAA,QACE,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI;AAEvE,SAAC,CAAC;AAEF,QAAA,OAAO,cAAc;;AAExB;;;;"}
|
|
1
|
+
{"version":3,"file":"AgentContext.cjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nimport { SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { ContentTypes, Providers } from '@/common';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else if (indexTokenCountMap) {\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n\n constructor({\n agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n }: {\n agentId: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n }) {\n this.agentId = agentId;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n // Include if: not deferred OR deferred but discovered\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n */\n private buildInstructionsString(): string {\n let result = this.instructions ?? '';\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n result = result\n ? `${result}\\n\\n${this.additionalInstructions}`\n : this.additionalInstructions;\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n result = result\n ? `${result}${programmaticToolsDoc}`\n : programmaticToolsDoc;\n }\n\n return result;\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n const defaultHeaders = anthropicOptions?.clientOptions?.defaultHeaders as\n | Record<string, string>\n | undefined;\n const anthropicBeta = defaultHeaders?.['anthropic-beta'];\n if (\n typeof anthropicBeta === 'string' &&\n anthropicBeta.includes('prompt-caching')\n ) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n const systemMessage = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = {};\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n }\n\n /**\n * Update the token count map with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const schema = genericTool.schema as {\n describe: (desc: string) => unknown;\n };\n const describedSchema = schema.describe(\n (genericTool.description as string) || ''\n );\n const jsonSchema = zodToJsonSchema(\n describedSchema as Parameters<typeof zodToJsonSchema>[0],\n (genericTool.name as string) || ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n }\n }\n }\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * Includes:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (!this.tools || !this.toolRegistry) {\n return this.tools;\n }\n\n const toolsToInclude = this.tools.filter((tool) => {\n if (!('name' in tool)) {\n return true; // No name, include by default\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true; // Not in registry, include by default\n }\n\n // Check if discovered (overrides defer_loading)\n if (this.discoveredToolNames.has(tool.name)) {\n // Discovered tools must still have allowed_callers: ['direct']\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n // Not discovered: must be direct-callable AND not deferred\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n\n return toolsToInclude;\n }\n}\n"],"names":["ContentTypes","Providers","SystemMessage","RunnableLambda","zodToJsonSchema"],"mappings":";;;;;;;AAAA;AACA;AAcA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;AAE3C,QAAA,MAAM,EACJ,OAAO,EACP,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,GACjB,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,QAAQ;YACR,aAAa;YACb,gBAAgB;YAChB,YAAY;YACZ,KAAK;YACL,OAAO;YACP,YAAY;YACZ,YAAY;AACZ,YAAA,sBAAsB,EAAE,uBAAuB;YAC/C,YAAY;YACZ,OAAO;AACP,YAAA,iBAAiB,EAAE,CAAC;YACpB,YAAY;YACZ,gBAAgB;AACjB,SAAA,CAAC;QAEF,IAAI,YAAY,EAAE;;;;YAIhB,YAAY,CAAC,wBAAwB,EAAE;AAEvC,YAAA,MAAM,QAAQ,GAAG,kBAAkB,IAAI,EAAE;AACzC,YAAA,YAAY,CAAC,kBAAkB,GAAG,QAAQ;YAC1C,YAAY,CAAC,uBAAuB,GAAG;i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AAG,IAAI;;;QAG5B,IAAI,iBAAiB,EAAE;AACrB,YAAA,IAAI,CAAC,mBAAmB,GAAG,IAAI;;AAEjC,QAAA,OAAO,iBAAiB;;AAG1B;;;;;;AAMG;IACH,kBAAkB,GAAA;QAChB,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE;YACrC,OAAO,IAAI,CAAC,KAAK;;QAGnB,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAI;AAChD,YAAA,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,EAAE;gBACrB,OAAO,IAAI,CAAC;;AAGd,YAAA,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC;YACjD,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO,IAAI,CAAC;;;YAId,IAAI,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;;gBAE3C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,gBAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;;;YAI1C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,YAAA,QACE,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI;AAEvE,SAAC,CAAC;AAEF,QAAA,OAAO,cAAc;;AAExB;;;;"}
|
package/dist/cjs/common/enum.cjs
CHANGED
|
@@ -146,7 +146,7 @@ exports.Constants = void 0;
|
|
|
146
146
|
Constants["OFFICIAL_CODE_BASEURL"] = "https://api.librechat.ai/v1";
|
|
147
147
|
Constants["EXECUTE_CODE"] = "execute_code";
|
|
148
148
|
Constants["TOOL_SEARCH_REGEX"] = "tool_search_regex";
|
|
149
|
-
Constants["PROGRAMMATIC_TOOL_CALLING"] = "
|
|
149
|
+
Constants["PROGRAMMATIC_TOOL_CALLING"] = "run_tools_with_code";
|
|
150
150
|
Constants["WEB_SEARCH"] = "web_search";
|
|
151
151
|
Constants["CONTENT_AND_ARTIFACT"] = "content_and_artifact";
|
|
152
152
|
Constants["LC_TRANSFER_TO_"] = "lc_transfer_to_";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enum.cjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools=',\n AGENT = 'agent=',\n ROUTER = 'router',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n TOOL_SEARCH_REGEX = 'tool_search_regex',\n PROGRAMMATIC_TOOL_CALLING = '
|
|
1
|
+
{"version":3,"file":"enum.cjs","sources":["../../../src/common/enum.ts"],"sourcesContent":["/**\n * Enum representing the various event types emitted during the execution of runnables.\n * These events provide real-time information about the progress and state of different components.\n *\n * @enum {string}\n */\nexport enum GraphEvents {\n /* Custom Events */\n\n /** [Custom] Agent update event in multi-agent graph/workflow */\n ON_AGENT_UPDATE = 'on_agent_update',\n /** [Custom] Delta event for run steps (message creation and tool calls) */\n ON_RUN_STEP = 'on_run_step',\n /** [Custom] Delta event for run steps (tool calls) */\n ON_RUN_STEP_DELTA = 'on_run_step_delta',\n /** [Custom] Completed event for run steps (tool calls) */\n ON_RUN_STEP_COMPLETED = 'on_run_step_completed',\n /** [Custom] Delta events for messages */\n ON_MESSAGE_DELTA = 'on_message_delta',\n /** [Custom] Reasoning Delta events for messages */\n ON_REASONING_DELTA = 'on_reasoning_delta',\n\n /* Official Events */\n\n /** Custom event, emitted by system */\n ON_CUSTOM_EVENT = 'on_custom_event',\n /** Emitted when a chat model starts processing. */\n CHAT_MODEL_START = 'on_chat_model_start',\n\n /** Emitted when a chat model streams a chunk of its response. */\n CHAT_MODEL_STREAM = 'on_chat_model_stream',\n\n /** Emitted when a chat model completes its processing. */\n CHAT_MODEL_END = 'on_chat_model_end',\n\n /** Emitted when a language model starts processing. */\n LLM_START = 'on_llm_start',\n\n /** Emitted when a language model streams a chunk of its response. */\n LLM_STREAM = 'on_llm_stream',\n\n /** Emitted when a language model completes its processing. */\n LLM_END = 'on_llm_end',\n\n /** Emitted when a chain starts processing. */\n CHAIN_START = 'on_chain_start',\n\n /** Emitted when a chain streams a chunk of its output. */\n CHAIN_STREAM = 'on_chain_stream',\n\n /** Emitted when a chain completes its processing. */\n CHAIN_END = 'on_chain_end',\n\n /** Emitted when a tool starts its operation. */\n TOOL_START = 'on_tool_start',\n\n /** Emitted when a tool completes its operation. */\n TOOL_END = 'on_tool_end',\n\n /** Emitted when a retriever starts its operation. */\n RETRIEVER_START = 'on_retriever_start',\n\n /** Emitted when a retriever completes its operation. */\n RETRIEVER_END = 'on_retriever_end',\n\n /** Emitted when a prompt starts processing. */\n PROMPT_START = 'on_prompt_start',\n\n /** Emitted when a prompt completes its processing. */\n PROMPT_END = 'on_prompt_end',\n}\n\nexport enum Providers {\n OPENAI = 'openAI',\n VERTEXAI = 'vertexai',\n BEDROCK = 'bedrock',\n ANTHROPIC = 'anthropic',\n MISTRALAI = 'mistralai',\n MISTRAL = 'mistral',\n GOOGLE = 'google',\n AZURE = 'azureOpenAI',\n DEEPSEEK = 'deepseek',\n OPENROUTER = 'openrouter',\n XAI = 'xai',\n}\n\nexport enum GraphNodeKeys {\n TOOLS = 'tools=',\n AGENT = 'agent=',\n ROUTER = 'router',\n PRE_TOOLS = 'pre_tools',\n POST_TOOLS = 'post_tools',\n}\n\nexport enum GraphNodeActions {\n TOOL_NODE = 'tool_node',\n CALL_MODEL = 'call_model',\n ROUTE_MESSAGE = 'route_message',\n}\n\nexport enum CommonEvents {\n LANGGRAPH = 'LangGraph',\n}\n\nexport enum StepTypes {\n TOOL_CALLS = 'tool_calls',\n MESSAGE_CREATION = 'message_creation',\n}\n\nexport enum ContentTypes {\n TEXT = 'text',\n ERROR = 'error',\n THINK = 'think',\n TOOL_CALL = 'tool_call',\n IMAGE_URL = 'image_url',\n IMAGE_FILE = 'image_file',\n /** Anthropic */\n THINKING = 'thinking',\n /** Vertex AI / Google Common */\n REASONING = 'reasoning',\n /** Multi-Agent Switch */\n AGENT_UPDATE = 'agent_update',\n /** Bedrock */\n REASONING_CONTENT = 'reasoning_content',\n}\n\nexport enum ToolCallTypes {\n FUNCTION = 'function',\n RETRIEVAL = 'retrieval',\n FILE_SEARCH = 'file_search',\n CODE_INTERPRETER = 'code_interpreter',\n /* Agents Tool Call */\n TOOL_CALL = 'tool_call',\n}\n\nexport enum Callback {\n TOOL_ERROR = 'handleToolError',\n TOOL_START = 'handleToolStart',\n TOOL_END = 'handleToolEnd',\n CUSTOM_EVENT = 'handleCustomEvent',\n /*\n LLM_START = 'handleLLMStart',\n LLM_NEW_TOKEN = 'handleLLMNewToken',\n LLM_ERROR = 'handleLLMError',\n LLM_END = 'handleLLMEnd',\n CHAT_MODEL_START = 'handleChatModelStart',\n CHAIN_START = 'handleChainStart',\n CHAIN_ERROR = 'handleChainError',\n CHAIN_END = 'handleChainEnd',\n TEXT = 'handleText',\n AGENT_ACTION = 'handleAgentAction',\n AGENT_END = 'handleAgentEnd',\n RETRIEVER_START = 'handleRetrieverStart',\n RETRIEVER_END = 'handleRetrieverEnd',\n RETRIEVER_ERROR = 'handleRetrieverError',\n */\n}\n\nexport enum Constants {\n OFFICIAL_CODE_BASEURL = 'https://api.librechat.ai/v1',\n EXECUTE_CODE = 'execute_code',\n TOOL_SEARCH_REGEX = 'tool_search_regex',\n PROGRAMMATIC_TOOL_CALLING = 'run_tools_with_code',\n WEB_SEARCH = 'web_search',\n CONTENT_AND_ARTIFACT = 'content_and_artifact',\n LC_TRANSFER_TO_ = 'lc_transfer_to_',\n}\n\nexport enum TitleMethod {\n STRUCTURED = 'structured',\n FUNCTIONS = 'functions',\n COMPLETION = 'completion',\n}\n\nexport enum EnvVar {\n CODE_API_KEY = 'LIBRECHAT_CODE_API_KEY',\n CODE_BASEURL = 'LIBRECHAT_CODE_BASEURL',\n}\n"],"names":["GraphEvents","Providers","GraphNodeKeys","GraphNodeActions","CommonEvents","StepTypes","ContentTypes","ToolCallTypes","Callback","Constants","TitleMethod","EnvVar"],"mappings":";;AAAA;;;;;AAKG;AACSA;AAAZ,CAAA,UAAY,WAAW,EAAA;;;AAIrB,IAAA,WAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;;AAEnC,IAAA,WAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;;AAE3B,IAAA,WAAA,CAAA,mBAAA,CAAA,GAAA,mBAAuC;;AAEvC,IAAA,WAAA,CAAA,uBAAA,CAAA,GAAA,uBAA+C;;AAE/C,IAAA,WAAA,CAAA,kBAAA,CAAA,GAAA,kBAAqC;;AAErC,IAAA,WAAA,CAAA,oBAAA,CAAA,GAAA,oBAAyC;;;AAKzC,IAAA,WAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;;AAEnC,IAAA,WAAA,CAAA,kBAAA,CAAA,GAAA,qBAAwC;;AAGxC,IAAA,WAAA,CAAA,mBAAA,CAAA,GAAA,sBAA0C;;AAG1C,IAAA,WAAA,CAAA,gBAAA,CAAA,GAAA,mBAAoC;;AAGpC,IAAA,WAAA,CAAA,WAAA,CAAA,GAAA,cAA0B;;AAG1B,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,eAA4B;;AAG5B,IAAA,WAAA,CAAA,SAAA,CAAA,GAAA,YAAsB;;AAGtB,IAAA,WAAA,CAAA,aAAA,CAAA,GAAA,gBAA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AAyB;AACzB,IAAA,SAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,SAAA,CAAA,iBAAA,CAAA,GAAA,iBAAmC;AACrC,CAAC,EARWA,iBAAS,KAATA,iBAAS,GAQpB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,WAAW,EAAA;AACrB,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AACzB,IAAA,WAAA,CAAA,WAAA,CAAA,GAAA,WAAuB;AACvB,IAAA,WAAA,CAAA,YAAA,CAAA,GAAA,YAAyB;AAC3B,CAAC,EAJWA,mBAAW,KAAXA,mBAAW,GAItB,EAAA,CAAA,CAAA;AAEWC;AAAZ,CAAA,UAAY,MAAM,EAAA;AAChB,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,wBAAuC;AACvC,IAAA,MAAA,CAAA,cAAA,CAAA,GAAA,wBAAuC;AACzC,CAAC,EAHWA,cAAM,KAANA,cAAM,GAGjB,EAAA,CAAA,CAAA;;"}
|
|
@@ -12,6 +12,7 @@ var prune = require('../messages/prune.cjs');
|
|
|
12
12
|
var format = require('../messages/format.cjs');
|
|
13
13
|
var cache = require('../messages/cache.cjs');
|
|
14
14
|
var content = require('../messages/content.cjs');
|
|
15
|
+
var tools = require('../messages/tools.cjs');
|
|
15
16
|
var graph = require('../utils/graph.cjs');
|
|
16
17
|
var llm = require('../utils/llm.cjs');
|
|
17
18
|
var run = require('../utils/run.cjs');
|
|
@@ -271,8 +272,6 @@ class StandardGraph extends Graph {
|
|
|
271
272
|
toolCallStepIds: this.toolCallStepIds,
|
|
272
273
|
errorHandler: (data, metadata) => StandardGraph.handleToolCallErrorStatic(this, data, metadata),
|
|
273
274
|
toolRegistry: agentContext?.toolRegistry,
|
|
274
|
-
programmaticToolMap: agentContext?.getProgrammaticToolMap(),
|
|
275
|
-
programmaticToolDefs: agentContext?.getProgrammaticToolDefs(),
|
|
276
275
|
});
|
|
277
276
|
}
|
|
278
277
|
initializeModel({ provider, tools, clientOptions, }) {
|
|
@@ -381,6 +380,12 @@ class StandardGraph extends Graph {
|
|
|
381
380
|
if (!config) {
|
|
382
381
|
throw new Error('No config provided');
|
|
383
382
|
}
|
|
383
|
+
const { messages: messages$1 } = state;
|
|
384
|
+
// Extract tool discoveries from current turn only (similar to formatArtifactPayload pattern)
|
|
385
|
+
const discoveredNames = tools.extractToolDiscoveries(messages$1);
|
|
386
|
+
if (discoveredNames.length > 0) {
|
|
387
|
+
agentContext.markToolsAsDiscovered(discoveredNames);
|
|
388
|
+
}
|
|
384
389
|
const toolsForBinding = agentContext.getToolsForBinding();
|
|
385
390
|
let model = this.overrideModel ??
|
|
386
391
|
this.initializeModel({
|
|
@@ -398,7 +403,6 @@ class StandardGraph extends Graph {
|
|
|
398
403
|
config.signal = this.signal;
|
|
399
404
|
}
|
|
400
405
|
this.config = config;
|
|
401
|
-
const { messages: messages$1 } = state;
|
|
402
406
|
let messagesToUse = messages$1;
|
|
403
407
|
if (!agentContext.pruneMessages &&
|
|
404
408
|
agentContext.tokenCounter &&
|
|
@@ -448,16 +452,6 @@ class StandardGraph extends Graph {
|
|
|
448
452
|
finalMessages[finalMessages.length - 2].content = '';
|
|
449
453
|
}
|
|
450
454
|
const isLatestToolMessage = lastMessageY instanceof messages.ToolMessage;
|
|
451
|
-
if (isLatestToolMessage &&
|
|
452
|
-
lastMessageY.name === _enum.Constants.TOOL_SEARCH_REGEX &&
|
|
453
|
-
typeof lastMessageY.artifact === 'object' &&
|
|
454
|
-
lastMessageY.artifact != null) {
|
|
455
|
-
const artifact = lastMessageY.artifact;
|
|
456
|
-
if (artifact.tool_references && artifact.tool_references.length > 0) {
|
|
457
|
-
const discoveredNames = artifact.tool_references.map((ref) => ref.tool_name);
|
|
458
|
-
agentContext.markToolsAsDiscovered(discoveredNames);
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
455
|
if (isLatestToolMessage &&
|
|
462
456
|
agentContext.provider === _enum.Providers.ANTHROPIC) {
|
|
463
457
|
core.formatAnthropicArtifactContent(finalMessages);
|