@amitdeshmukh/ax-crew 3.11.1 → 4.0.1
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/CHANGELOG.md +24 -0
- package/README.md +31 -62
- package/dist/agents/agentConfig.d.ts +6 -6
- package/dist/agents/agentConfig.js +43 -36
- package/dist/agents/index.d.ts +14 -11
- package/dist/agents/index.js +154 -40
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/metrics/index.d.ts +2 -0
- package/dist/metrics/index.js +2 -0
- package/dist/metrics/registry.d.ts +9 -0
- package/dist/metrics/registry.js +138 -0
- package/dist/metrics/types.d.ts +40 -0
- package/dist/metrics/types.js +1 -0
- package/dist/types.d.ts +7 -7
- package/examples/basic-researcher-writer.ts +18 -13
- package/examples/mcp-agent.ts +12 -8
- package/examples/perplexityDeepSearch.ts +89 -0
- package/examples/search-tweets.ts +74 -0
- package/examples/solve-math-problem.ts +7 -5
- package/examples/streaming.ts +7 -6
- package/package.json +7 -2
- package/src/agents/agentConfig.ts +47 -41
- package/src/agents/index.ts +169 -60
- package/src/index.ts +2 -0
- package/src/metrics/index.ts +4 -0
- package/src/metrics/registry.ts +167 -0
- package/src/metrics/types.ts +48 -0
- package/src/types.ts +25 -8
- package/tests/AxCrew.test.ts +22 -18
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
|
-
// Import
|
|
3
|
-
import {
|
|
4
|
-
// Import Ax types
|
|
2
|
+
// Import Ax factory and MCP transports (as exported by current package)
|
|
3
|
+
import { ai, AxMCPClient, AxMCPHTTPSSETransport, AxMCPStreambleHTTPTransport, AxDefaultCostTracker } from '@ax-llm/ax'
|
|
5
4
|
import type { AxFunction } from '@ax-llm/ax';
|
|
6
|
-
//
|
|
7
|
-
import {
|
|
5
|
+
// STDIO transport from tools package
|
|
6
|
+
import { AxMCPStdioTransport } from '@ax-llm/ax-tools'
|
|
8
7
|
import { PROVIDER_API_KEYS } from '../config/index.js';
|
|
9
8
|
import type {
|
|
10
9
|
AgentConfig,
|
|
@@ -13,28 +12,29 @@ import type {
|
|
|
13
12
|
MCPTransportConfig,
|
|
14
13
|
MCPStdioTransportConfig,
|
|
15
14
|
MCPHTTPSSETransportConfig,
|
|
16
|
-
|
|
15
|
+
MCPStreamableHTTPTransportConfig
|
|
17
16
|
} from '../types.js';
|
|
17
|
+
import type { Provider } from '../types.js';
|
|
18
18
|
|
|
19
|
-
//
|
|
20
|
-
const
|
|
21
|
-
'
|
|
22
|
-
'
|
|
23
|
-
'
|
|
24
|
-
'
|
|
25
|
-
'
|
|
26
|
-
'
|
|
27
|
-
'
|
|
28
|
-
'
|
|
29
|
-
'ollama'
|
|
30
|
-
'
|
|
31
|
-
'
|
|
32
|
-
'
|
|
33
|
-
'
|
|
34
|
-
|
|
19
|
+
// Canonical provider slugs supported by ai() factory
|
|
20
|
+
const PROVIDER_CANONICAL = new Set([
|
|
21
|
+
'openai',
|
|
22
|
+
'anthropic',
|
|
23
|
+
'google-gemini',
|
|
24
|
+
'mistral',
|
|
25
|
+
'groq',
|
|
26
|
+
'cohere',
|
|
27
|
+
'together',
|
|
28
|
+
'deepseek',
|
|
29
|
+
'ollama',
|
|
30
|
+
'huggingface',
|
|
31
|
+
'openrouter',
|
|
32
|
+
'azure-openai',
|
|
33
|
+
'reka',
|
|
34
|
+
'x-grok'
|
|
35
|
+
]);
|
|
35
36
|
|
|
36
|
-
// Provider type
|
|
37
|
-
export type Provider = keyof typeof AIConstructors;
|
|
37
|
+
// Provider type lives in src/types.ts
|
|
38
38
|
|
|
39
39
|
// Type guard to check if config is stdio transport
|
|
40
40
|
export function isStdioTransport(config: MCPTransportConfig): config is MCPStdioTransportConfig {
|
|
@@ -47,7 +47,7 @@ export function isHTTPSSETransport(config: MCPTransportConfig): config is MCPHTT
|
|
|
47
47
|
}
|
|
48
48
|
|
|
49
49
|
// Type guard to check if config is streamable HTTP transport
|
|
50
|
-
export function isStreambleHTTPTransport(config: MCPTransportConfig): config is
|
|
50
|
+
export function isStreambleHTTPTransport(config: MCPTransportConfig): config is MCPStreamableHTTPTransportConfig {
|
|
51
51
|
return 'mcpEndpoint' in config;
|
|
52
52
|
}
|
|
53
53
|
|
|
@@ -128,11 +128,10 @@ const initializeMCPServers = async (agentConfigData: AgentConfig): Promise<AxFun
|
|
|
128
128
|
args: mcpServerConfig.args,
|
|
129
129
|
env: mcpServerConfig.env
|
|
130
130
|
});
|
|
131
|
-
} else if (isStreambleHTTPTransport(mcpServerConfig)) {
|
|
132
|
-
transport = new AxMCPStreambleHTTPTransport(mcpServerConfig.mcpEndpoint, mcpServerConfig.options);
|
|
133
131
|
} else if (isHTTPSSETransport(mcpServerConfig)) {
|
|
134
|
-
// This handles both new SSE transport and legacy HTTP transport (both use sseUrl)
|
|
135
132
|
transport = new AxMCPHTTPSSETransport(mcpServerConfig.sseUrl);
|
|
133
|
+
} else if (isStreambleHTTPTransport(mcpServerConfig)) {
|
|
134
|
+
transport = new AxMCPStreambleHTTPTransport(mcpServerConfig.mcpEndpoint, mcpServerConfig.options);
|
|
136
135
|
} else {
|
|
137
136
|
throw new Error(`Unsupported transport type: ${JSON.stringify(mcpServerConfig)}`);
|
|
138
137
|
}
|
|
@@ -205,11 +204,12 @@ const parseAgentConfig = async (
|
|
|
205
204
|
throw new Error(`AI agent with name ${agentName} is not configured`);
|
|
206
205
|
}
|
|
207
206
|
|
|
208
|
-
//
|
|
209
|
-
const
|
|
210
|
-
if (!
|
|
211
|
-
throw new Error(`AI provider ${agentConfigData.provider} is not supported.
|
|
207
|
+
// Enforce canonical provider slug
|
|
208
|
+
const lower = agentConfigData.provider.toLowerCase();
|
|
209
|
+
if (!PROVIDER_CANONICAL.has(lower)) {
|
|
210
|
+
throw new Error(`AI provider ${agentConfigData.provider} is not supported. Use one of: ${Array.from(PROVIDER_CANONICAL).join(', ')}`);
|
|
212
211
|
}
|
|
212
|
+
const provider = lower as Provider;
|
|
213
213
|
|
|
214
214
|
// If an API Key property is present, get the API key for the AI agent from the environment variables
|
|
215
215
|
let apiKey = '';
|
|
@@ -223,25 +223,30 @@ const parseAgentConfig = async (
|
|
|
223
223
|
throw new Error(`Provider key name is missing in the agent configuration`);
|
|
224
224
|
}
|
|
225
225
|
|
|
226
|
-
// Create
|
|
227
|
-
const
|
|
226
|
+
// Create a cost tracker instance and pass to ai()
|
|
227
|
+
const costTracker = new AxDefaultCostTracker();
|
|
228
|
+
|
|
229
|
+
// Create an instance of the AI agent via factory
|
|
230
|
+
const aiArgs: any = {
|
|
231
|
+
name: provider,
|
|
228
232
|
apiKey,
|
|
229
233
|
config: agentConfigData.ai,
|
|
230
234
|
options: {
|
|
231
235
|
debug: agentConfigData.debug || false,
|
|
232
|
-
...agentConfigData.options
|
|
236
|
+
...agentConfigData.options,
|
|
237
|
+
// Attach default cost tracker so usage/costs are recorded by provider layer
|
|
238
|
+
trackers: [costTracker]
|
|
233
239
|
}
|
|
234
|
-
}
|
|
235
|
-
// If an apiURL is provided in the agent config, set it in the AI agent
|
|
240
|
+
};
|
|
236
241
|
if (agentConfigData.apiURL) {
|
|
237
242
|
try {
|
|
238
|
-
// Validate apiURL format
|
|
239
243
|
new URL(agentConfigData.apiURL);
|
|
240
|
-
|
|
244
|
+
aiArgs.apiURL = agentConfigData.apiURL;
|
|
241
245
|
} catch (error) {
|
|
242
246
|
throw new Error(`Invalid apiURL provided: ${agentConfigData.apiURL}`);
|
|
243
|
-
}
|
|
247
|
+
}
|
|
244
248
|
}
|
|
249
|
+
const aiInstance = ai(aiArgs);
|
|
245
250
|
|
|
246
251
|
// If an mcpServers config is provided in the agent config, convert to functions
|
|
247
252
|
const mcpFunctions = await initializeMCPServers(agentConfigData);
|
|
@@ -265,13 +270,14 @@ const parseAgentConfig = async (
|
|
|
265
270
|
|
|
266
271
|
// Return AI instance and Agent parameters
|
|
267
272
|
return {
|
|
268
|
-
ai,
|
|
273
|
+
ai: aiInstance,
|
|
269
274
|
name: agentName,
|
|
270
275
|
description: agentConfigData.description,
|
|
271
276
|
signature: agentConfigData.signature,
|
|
272
277
|
functions: agentFunctions,
|
|
273
278
|
subAgentNames: agentConfigData.agents || [],
|
|
274
279
|
examples: agentConfigData.examples || [],
|
|
280
|
+
tracker: costTracker,
|
|
275
281
|
};
|
|
276
282
|
} catch (error) {
|
|
277
283
|
if (error instanceof Error) {
|
package/src/agents/index.ts
CHANGED
|
@@ -20,7 +20,7 @@ import type {
|
|
|
20
20
|
|
|
21
21
|
import { createState } from "../state/index.js";
|
|
22
22
|
import { parseCrewConfig, parseAgentConfig } from "./agentConfig.js";
|
|
23
|
-
import {
|
|
23
|
+
import { MetricsRegistry } from "../metrics/index.js";
|
|
24
24
|
|
|
25
25
|
// Define the interface for the agent configuration
|
|
26
26
|
interface ParsedAgentConfig {
|
|
@@ -36,6 +36,7 @@ interface ParsedAgentConfig {
|
|
|
36
36
|
mcpServers?: Record<string, MCPTransportConfig>;
|
|
37
37
|
subAgentNames: string[];
|
|
38
38
|
examples?: Array<Record<string, any>>;
|
|
39
|
+
tracker?: any;
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
// Extend the AxAgent class from ax-llm
|
|
@@ -43,6 +44,14 @@ class StatefulAxAgent extends AxAgent<any, any> {
|
|
|
43
44
|
state: StateInstance;
|
|
44
45
|
axai: any;
|
|
45
46
|
private agentName: string;
|
|
47
|
+
private costTracker?: any;
|
|
48
|
+
private lastRecordedCostUSD: number = 0;
|
|
49
|
+
private isAxAIService(obj: any): obj is AxAI {
|
|
50
|
+
return !!obj && typeof obj.getName === 'function' && typeof obj.chat === 'function';
|
|
51
|
+
}
|
|
52
|
+
private isAxAIInstance(obj: any): obj is AxAI {
|
|
53
|
+
return !!obj && typeof obj === 'object' && ('defaults' in obj || 'modelInfo' in obj);
|
|
54
|
+
}
|
|
46
55
|
|
|
47
56
|
constructor(
|
|
48
57
|
ai: AxAI,
|
|
@@ -50,7 +59,7 @@ class StatefulAxAgent extends AxAgent<any, any> {
|
|
|
50
59
|
name: string;
|
|
51
60
|
description: string;
|
|
52
61
|
signature: string | AxSignature;
|
|
53
|
-
agents?: AxAgentic[] | undefined;
|
|
62
|
+
agents?: AxAgentic<any, any>[] | undefined;
|
|
54
63
|
functions?: (AxFunction | (() => AxFunction))[] | undefined;
|
|
55
64
|
examples?: Array<Record<string, any>> | undefined;
|
|
56
65
|
mcpServers?: Record<string, MCPTransportConfig> | undefined;
|
|
@@ -76,52 +85,92 @@ class StatefulAxAgent extends AxAgent<any, any> {
|
|
|
76
85
|
}
|
|
77
86
|
|
|
78
87
|
// Function overloads for forward method
|
|
79
|
-
async forward(values: Record<string, any>, options?: Readonly<AxProgramForwardOptions
|
|
80
|
-
async forward(ai: AxAI, values: Record<string, any>, options?: Readonly<AxProgramForwardOptions
|
|
88
|
+
async forward(values: Record<string, any>, options?: Readonly<AxProgramForwardOptions<any>>): Promise<Record<string, any>>;
|
|
89
|
+
async forward(ai: AxAI, values: Record<string, any>, options?: Readonly<AxProgramForwardOptions<any>>): Promise<Record<string, any>>;
|
|
81
90
|
|
|
82
91
|
// Implementation
|
|
83
92
|
async forward(
|
|
84
93
|
first: Record<string, any> | AxAI,
|
|
85
|
-
second?: Record<string, any> | Readonly<AxProgramForwardOptions
|
|
86
|
-
third?: Readonly<AxProgramForwardOptions
|
|
94
|
+
second?: Record<string, any> | Readonly<AxProgramForwardOptions<any>>,
|
|
95
|
+
third?: Readonly<AxProgramForwardOptions<any>>
|
|
87
96
|
): Promise<Record<string, any>> {
|
|
88
97
|
let result;
|
|
89
98
|
|
|
99
|
+
const start = performance.now();
|
|
100
|
+
const crewId = (this.state as any)?.crewId || (this.state.get?.('crewId')) || 'default';
|
|
101
|
+
const labels = { crewId, agent: this.agentName } as any;
|
|
102
|
+
|
|
90
103
|
// Track costs regardless of whether it's a direct or sub-agent call
|
|
91
104
|
// This ensures we capture multiple legitimate calls to the same agent
|
|
92
|
-
if (
|
|
105
|
+
if (this.isAxAIService(first)) {
|
|
93
106
|
// Sub-agent case (called with AI service)
|
|
94
107
|
result = await super.forward(this.axai, second as Record<string, any>, third);
|
|
95
108
|
} else {
|
|
96
109
|
// Direct call case
|
|
97
|
-
result = await super.forward(this.axai, first, second as Readonly<AxProgramForwardOptions
|
|
110
|
+
result = await super.forward(this.axai, first, second as Readonly<AxProgramForwardOptions<any>>);
|
|
98
111
|
}
|
|
99
112
|
|
|
100
|
-
// Track costs after the call
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
113
|
+
// Track metrics and costs after the call using built-in usage
|
|
114
|
+
const durationMs = performance.now() - start;
|
|
115
|
+
MetricsRegistry.recordRequest(labels, false, durationMs);
|
|
116
|
+
// Always record tokens from built-in usage array if present
|
|
117
|
+
const builtIn = (this as any).getUsage?.();
|
|
118
|
+
if (Array.isArray(builtIn)) {
|
|
119
|
+
const totals = builtIn.reduce(
|
|
120
|
+
(acc: any, u: any) => {
|
|
121
|
+
const pt = u.tokens?.promptTokens ?? u.promptTokens ?? 0;
|
|
122
|
+
const ct = u.tokens?.completionTokens ?? u.completionTokens ?? 0;
|
|
123
|
+
acc.promptTokens += typeof pt === 'number' ? pt : 0;
|
|
124
|
+
acc.completionTokens += typeof ct === 'number' ? ct : 0;
|
|
125
|
+
// also aggregate per-model to feed Ax tracker
|
|
126
|
+
const model = u.model || (this.axai as any)?.getLastUsedChatModel?.() || (this.axai as any)?.defaults?.model;
|
|
127
|
+
if (model) {
|
|
128
|
+
acc.byModel[model] = (acc.byModel[model] || 0) + (pt + ct);
|
|
129
|
+
}
|
|
130
|
+
return acc;
|
|
131
|
+
},
|
|
132
|
+
{ promptTokens: 0, completionTokens: 0, byModel: {} as Record<string, number> }
|
|
133
|
+
);
|
|
134
|
+
MetricsRegistry.recordTokens(labels, {
|
|
135
|
+
promptTokens: totals.promptTokens,
|
|
136
|
+
completionTokens: totals.completionTokens,
|
|
137
|
+
totalTokens: totals.promptTokens + totals.completionTokens,
|
|
138
|
+
});
|
|
139
|
+
// Feed Ax's cost tracker with token totals per model; Ax owns pricing
|
|
140
|
+
const costTracker = (this as any).costTracker;
|
|
141
|
+
try {
|
|
142
|
+
for (const [m, count] of Object.entries(totals.byModel)) {
|
|
143
|
+
costTracker?.trackTokens?.(count, m);
|
|
144
|
+
}
|
|
145
|
+
const totalUSD = Number(costTracker?.getCurrentCost?.() ?? 0);
|
|
146
|
+
if (!Number.isNaN(totalUSD) && totalUSD > 0) {
|
|
147
|
+
MetricsRegistry.recordEstimatedCost(labels, totalUSD);
|
|
148
|
+
}
|
|
149
|
+
} catch {}
|
|
104
150
|
}
|
|
105
151
|
|
|
106
152
|
return result;
|
|
107
153
|
}
|
|
108
154
|
|
|
109
155
|
// Add streaming forward method overloads
|
|
110
|
-
streamingForward(values: Record<string, any>, options?: Readonly<AxProgramStreamingForwardOptions
|
|
111
|
-
streamingForward(ai: AxAI, values: Record<string, any>, options?: Readonly<AxProgramStreamingForwardOptions
|
|
156
|
+
streamingForward(values: Record<string, any>, options?: Readonly<AxProgramStreamingForwardOptions<any>>): AxGenStreamingOut<any>;
|
|
157
|
+
streamingForward(ai: AxAI, values: Record<string, any>, options?: Readonly<AxProgramStreamingForwardOptions<any>>): AxGenStreamingOut<any>;
|
|
112
158
|
|
|
113
159
|
// Implementation
|
|
114
160
|
streamingForward(
|
|
115
161
|
first: Record<string, any> | AxAI,
|
|
116
|
-
second?: Record<string, any> | Readonly<AxProgramStreamingForwardOptions
|
|
117
|
-
third?: Readonly<AxProgramStreamingForwardOptions
|
|
162
|
+
second?: Record<string, any> | Readonly<AxProgramStreamingForwardOptions<any>>,
|
|
163
|
+
third?: Readonly<AxProgramStreamingForwardOptions<any>>
|
|
118
164
|
): AxGenStreamingOut<any> {
|
|
165
|
+
const start = performance.now();
|
|
166
|
+
const crewId = (this.state as any)?.crewId || (this.state.get?.('crewId')) || 'default';
|
|
167
|
+
const labels = { crewId, agent: this.agentName } as any;
|
|
119
168
|
let streamingResult: AxGenStreamingOut<any>;
|
|
120
169
|
|
|
121
|
-
if (
|
|
170
|
+
if (this.isAxAIService(first)) {
|
|
122
171
|
streamingResult = super.streamingForward(this.axai, second as Record<string, any>, third);
|
|
123
172
|
} else {
|
|
124
|
-
streamingResult = super.streamingForward(this.axai, first, second as Readonly<AxProgramStreamingForwardOptions
|
|
173
|
+
streamingResult = super.streamingForward(this.axai, first, second as Readonly<AxProgramStreamingForwardOptions<any>>);
|
|
125
174
|
}
|
|
126
175
|
|
|
127
176
|
// Create a new async generator that tracks costs after completion
|
|
@@ -131,43 +180,71 @@ class StatefulAxAgent extends AxAgent<any, any> {
|
|
|
131
180
|
yield chunk;
|
|
132
181
|
}
|
|
133
182
|
} finally {
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
183
|
+
const durationMs = performance.now() - start;
|
|
184
|
+
MetricsRegistry.recordRequest(labels, true, durationMs);
|
|
185
|
+
// Record tokens from built-in usage array if present
|
|
186
|
+
const builtIn = (this as any).getUsage?.();
|
|
187
|
+
if (Array.isArray(builtIn)) {
|
|
188
|
+
const totals = builtIn.reduce(
|
|
189
|
+
(acc: any, u: any) => {
|
|
190
|
+
const pt = u.tokens?.promptTokens ?? u.promptTokens ?? 0;
|
|
191
|
+
const ct = u.tokens?.completionTokens ?? u.completionTokens ?? 0;
|
|
192
|
+
acc.promptTokens += typeof pt === 'number' ? pt : 0;
|
|
193
|
+
acc.completionTokens += typeof ct === 'number' ? ct : 0;
|
|
194
|
+
const model = u.model || (this.axai as any)?.getLastUsedChatModel?.() || (this.axai as any)?.defaults?.model;
|
|
195
|
+
if (model) {
|
|
196
|
+
acc.byModel[model] = (acc.byModel[model] || 0) + (pt + ct);
|
|
197
|
+
}
|
|
198
|
+
return acc;
|
|
199
|
+
},
|
|
200
|
+
{ promptTokens: 0, completionTokens: 0, byModel: {} as Record<string, number> }
|
|
201
|
+
);
|
|
202
|
+
MetricsRegistry.recordTokens(labels, {
|
|
203
|
+
promptTokens: totals.promptTokens,
|
|
204
|
+
completionTokens: totals.completionTokens,
|
|
205
|
+
totalTokens: totals.promptTokens + totals.completionTokens,
|
|
206
|
+
});
|
|
207
|
+
const costTracker = (this as any).costTracker;
|
|
208
|
+
try {
|
|
209
|
+
for (const [m, count] of Object.entries(totals.byModel)) {
|
|
210
|
+
costTracker?.trackTokens?.(count, m);
|
|
211
|
+
}
|
|
212
|
+
const totalUSD = Number(costTracker?.getCurrentCost?.() ?? 0);
|
|
213
|
+
if (!Number.isNaN(totalUSD) && totalUSD > 0) {
|
|
214
|
+
MetricsRegistry.recordEstimatedCost(labels, totalUSD);
|
|
215
|
+
}
|
|
216
|
+
} catch {}
|
|
137
217
|
}
|
|
218
|
+
// Record estimated cost (USD) via attached tracker if available
|
|
219
|
+
const costTracker = (this as any).costTracker;
|
|
220
|
+
try {
|
|
221
|
+
const totalUSD = Number(costTracker?.getCurrentCost?.() ?? 0);
|
|
222
|
+
if (!Number.isNaN(totalUSD) && totalUSD > 0) {
|
|
223
|
+
MetricsRegistry.recordEstimatedCost(labels, totalUSD);
|
|
224
|
+
}
|
|
225
|
+
} catch {}
|
|
138
226
|
}
|
|
139
227
|
}).bind(this)();
|
|
140
228
|
|
|
141
229
|
return wrappedGenerator as AxGenStreamingOut<any>;
|
|
142
230
|
}
|
|
143
231
|
|
|
144
|
-
//
|
|
145
|
-
getLastUsageCost(): UsageCost | null {
|
|
146
|
-
const { modelUsage, modelInfo, defaults } = this.axai;
|
|
147
|
-
|
|
148
|
-
// Check if all required properties exist
|
|
149
|
-
if (!modelUsage?.promptTokens || !modelUsage?.completionTokens) {
|
|
150
|
-
return null;
|
|
151
|
-
}
|
|
232
|
+
// Legacy cost API removed: rely on Ax trackers for cost reporting
|
|
233
|
+
getLastUsageCost(): UsageCost | null { return null; }
|
|
152
234
|
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const currentModelInfo = modelInfo.find((m: { name: string }) => m.name === defaults.model);
|
|
158
|
-
|
|
159
|
-
if (!currentModelInfo?.promptTokenCostPer1M || !currentModelInfo?.completionTokenCostPer1M) {
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
235
|
+
// Get the accumulated costs for all runs of this agent
|
|
236
|
+
getAccumulatedCosts(): UsageCost | null { return null; }
|
|
162
237
|
|
|
163
|
-
|
|
238
|
+
// Metrics API for this agent
|
|
239
|
+
getMetrics() {
|
|
240
|
+
const crewId = (this.state as any)?.crewId || (this.state.get?.('crewId')) || 'default';
|
|
241
|
+
return MetricsRegistry.snapshot({ crewId, agent: this.agentName } as any);
|
|
164
242
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
const stateKey = `${StateFulAxAgentUsage.STATE_KEY_PREFIX}${this.agentName}`;
|
|
169
|
-
return this.state.get(stateKey) as UsageCost | null;
|
|
243
|
+
resetMetrics(): void {
|
|
244
|
+
const crewId = (this.state as any)?.crewId || (this.state.get?.('crewId')) || 'default';
|
|
245
|
+
MetricsRegistry.reset({ crewId, agent: this.agentName } as any);
|
|
170
246
|
}
|
|
247
|
+
|
|
171
248
|
}
|
|
172
249
|
|
|
173
250
|
/**
|
|
@@ -208,6 +285,8 @@ class AxCrew {
|
|
|
208
285
|
this.crewId = crewId;
|
|
209
286
|
this.agents = new Map<string, StatefulAxAgent>();
|
|
210
287
|
this.state = createState(crewId);
|
|
288
|
+
// Make crewId discoverable to metrics
|
|
289
|
+
this.state.set('crewId', crewId);
|
|
211
290
|
}
|
|
212
291
|
|
|
213
292
|
/**
|
|
@@ -226,7 +305,7 @@ class AxCrew {
|
|
|
226
305
|
);
|
|
227
306
|
|
|
228
307
|
// Destructure with type assertion
|
|
229
|
-
const { ai, name, description, signature, functions, subAgentNames, examples } = agentConfig;
|
|
308
|
+
const { ai, name, description, signature, functions, subAgentNames, examples, tracker } = agentConfig;
|
|
230
309
|
|
|
231
310
|
// Get subagents for the AI agent
|
|
232
311
|
const subAgents = subAgentNames.map((subAgentName: string) => {
|
|
@@ -238,6 +317,30 @@ class AxCrew {
|
|
|
238
317
|
return this.agents?.get(subAgentName);
|
|
239
318
|
});
|
|
240
319
|
|
|
320
|
+
// Dedupe sub-agents by name (defensive)
|
|
321
|
+
const subAgentSet = new Map<string, StatefulAxAgent>();
|
|
322
|
+
for (const sa of subAgents.filter((agent): agent is StatefulAxAgent => agent !== undefined)) {
|
|
323
|
+
const n = (sa as any)?.agentName ?? (sa as any)?.name ?? '';
|
|
324
|
+
if (!subAgentSet.has(n)) subAgentSet.set(n, sa);
|
|
325
|
+
}
|
|
326
|
+
const uniqueSubAgents = Array.from(subAgentSet.values());
|
|
327
|
+
|
|
328
|
+
// Dedupe functions by name and avoid collision with sub-agent names
|
|
329
|
+
const subAgentNameSet = new Set(uniqueSubAgents.map((sa: any) => sa?.agentName ?? sa?.name).filter(Boolean));
|
|
330
|
+
const uniqueFunctions: AxFunction[] = [];
|
|
331
|
+
const seenFn = new Set<string>();
|
|
332
|
+
for (const fn of functions.filter((fn): fn is AxFunction => fn !== undefined)) {
|
|
333
|
+
const fnName = fn.name;
|
|
334
|
+
if (subAgentNameSet.has(fnName)) {
|
|
335
|
+
// Skip function that collides with a sub-agent name
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
if (!seenFn.has(fnName)) {
|
|
339
|
+
seenFn.add(fnName);
|
|
340
|
+
uniqueFunctions.push(fn);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
241
344
|
// Create an instance of StatefulAxAgent
|
|
242
345
|
const agent = new StatefulAxAgent(
|
|
243
346
|
ai,
|
|
@@ -245,16 +348,13 @@ class AxCrew {
|
|
|
245
348
|
name,
|
|
246
349
|
description,
|
|
247
350
|
signature,
|
|
248
|
-
functions:
|
|
249
|
-
|
|
250
|
-
),
|
|
251
|
-
agents: subAgents.filter(
|
|
252
|
-
(agent): agent is StatefulAxAgent => agent !== undefined
|
|
253
|
-
),
|
|
351
|
+
functions: uniqueFunctions,
|
|
352
|
+
agents: uniqueSubAgents,
|
|
254
353
|
examples,
|
|
255
354
|
},
|
|
256
355
|
this.state
|
|
257
356
|
);
|
|
357
|
+
(agent as any).costTracker = tracker;
|
|
258
358
|
|
|
259
359
|
return agent;
|
|
260
360
|
} catch (error) {
|
|
@@ -394,20 +494,29 @@ class AxCrew {
|
|
|
394
494
|
this.state.reset();
|
|
395
495
|
}
|
|
396
496
|
|
|
397
|
-
/**
|
|
398
|
-
* Gets aggregated costs for all agents in the crew
|
|
399
|
-
* @returns Aggregated cost information for all agents
|
|
400
|
-
*/
|
|
401
|
-
getAggregatedCosts(): ReturnType<typeof StateFulAxAgentUsage.getAggregatedCosts> {
|
|
402
|
-
return StateFulAxAgentUsage.getAggregatedCosts(this.state);
|
|
403
|
-
}
|
|
404
497
|
|
|
405
498
|
/**
|
|
406
499
|
* Resets all cost tracking for the crew
|
|
407
500
|
*/
|
|
408
501
|
resetCosts(): void {
|
|
409
|
-
|
|
502
|
+
// Reset AxAgent built-in usage and our metrics registry
|
|
503
|
+
if (this.agents) {
|
|
504
|
+
for (const [, agent] of this.agents) {
|
|
505
|
+
try { (agent as any).resetUsage?.(); } catch {}
|
|
506
|
+
try { (agent as any).resetMetrics?.(); } catch {}
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
MetricsRegistry.reset({ crewId: this.crewId });
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// Metrics API
|
|
513
|
+
getCrewMetrics() {
|
|
514
|
+
return MetricsRegistry.snapshotCrew(this.crewId);
|
|
515
|
+
}
|
|
516
|
+
resetCrewMetrics(): void {
|
|
517
|
+
MetricsRegistry.reset({ crewId: this.crewId });
|
|
410
518
|
}
|
|
411
519
|
}
|
|
412
520
|
|
|
413
|
-
export { AxCrew };
|
|
521
|
+
export { AxCrew };
|
|
522
|
+
export type { StatefulAxAgent };
|
package/src/index.ts
CHANGED