Added tps + duration to AI history
All checks were successful
Publish Library / Build NPM Project (push) Successful in 52s
Publish Library / Tag Version (push) Successful in 11s

This commit is contained in:
2026-08-04 09:26:57 -04:00
parent d53b1c6328
commit 62fbe73b22
4 changed files with 69 additions and 92 deletions

View File

@@ -47,6 +47,10 @@ export type LLMMessage = {
error?: undefined | string;
/** Timestamp */
timestamp?: number;
/** Response duration in ms */
duration?: number;
/** Tokens per second */
tps?: number;
}
export type LLMRequest = {
@@ -118,12 +122,6 @@ class LLM {
this.memoryManager = new MemoryManager(this);
}
/**
* Wrap agents as tools. Nested delegation is opt-in only (empty by default, like
* tools/skills/mcp) and an agent can never call itself even if explicitly whitelisted.
* Delegate results are queued in `pending` and spliced into history by `ask()` after
* the provider's own end-of-turn history sync has already run.
*/
private setupAgent(agents: Agent[] = [], allAgents: Agent[], pending: Map<string, any>, aborts: (() => void)[], depth = 0): AiTool[] {
return agents.map(a => {
const toolName = `${a.delegate ? '' : 'sub'}agent_${snakeCase(a.name)}`;
@@ -143,6 +141,7 @@ class LLM {
.map(name => allAgents.find(x => x.name === name))
.filter((x): x is Agent => !!x && x.name !== a.name);
const start = Date.now();
const request = this.ask(`${args.instructions}${args.context ? `\n\n<context>${args.context}</context>` : ''}`, {
system: `You are a specialized subagent. ${a.delegate ? 'Your output streams directly to the user for the remainder of this turn.' : 'You are wrapped in a tool call that will be analysis by an LLM'}
As a subagent, focus on executing your task completely using available tools and returning only the final result - no commentary, questions, or dialogue.
@@ -160,9 +159,14 @@ ${a.system}`,
} as any);
aborts.push(request.abort);
const resp = await request;
const duration = Date.now() - start;
const assistantTurns = subHistory.filter((h: any) => h.role === 'assistant' && h.duration);
const genTime = assistantTurns.reduce((s, h: any) => s + h.duration, 0);
const genTokens = assistantTurns.reduce((s, h: any) => s + (h.tps || 0) * (h.duration / 1000), 0);
const tps = genTime > 0 ? genTokens / (genTime / 1000) : 0;
if(a.delegate) {
pending.set(<string>id, {resp, subHistory});
pending.set(<string>id, {resp, subHistory, duration, tps});
return '';
}
return resp;
@@ -229,6 +233,20 @@ ${a.system}`,
}
}
private wrapToolTiming(tools: AiTool[], timings: Map<string, {duration: number, tps: number}>): AiTool[] {
return tools.map(t => ({
...t,
fn: async (args: any, stream: any, ai: any, id?: string) => {
const start = Date.now();
const result = await t.fn(args, stream, ai, id);
const duration = Date.now() - start;
const tps = duration > 0 ? this.estimateTokens(result) / (duration / 1000) : 0;
if(id) timings.set(id, {duration, tps});
return result;
}
}));
}
ask(message: string, options: LLMRequest = {}): AbortablePromise<string> {
options = <any>{
system: '',
@@ -314,19 +332,29 @@ Also relevant but not preloaded (use \`memory_recall\`): ${listed.map(r => r.nam
if(aborted) throw Object.assign(new Error('Aborted'), {name: 'AbortError'});
// Time each tool call's real execution so its history entry gets its own duration/tps
const toolTimings = new Map<string, {duration: number, tps: number}>();
tools = this.wrapToolTiming(tools, toolTimings);
prompts.unshift(options.system || this.ai.options.llm?.system || '');
request = this.models[m].ask(message, {...options, tools, system: prompts.filter(Boolean).join('\n\n')});
let resp = await request;
// Providers stamp duration/tps on assistant entries themselves (from real API usage).
// Overwrite tool entries with actual tool-execution timing instead of the LLM call timing.
for(const h of history) {
if(h.role === 'tool' && toolTimings.has(h.id)) Object.assign(h, toolTimings.get(h.id));
}
// Spice delegated agents response into history
let lastDelegateResp: string | null = null;
if(pendingDelegates.size) {
for(let i = 0; i < history.length; i++) {
const h: any = history[i];
if(h.role !== 'tool' || !pendingDelegates.has(h.id)) continue;
const {resp: delegateResp, subHistory} = pendingDelegates.get(h.id)!;
const {resp: delegateResp, subHistory, duration, tps} = pendingDelegates.get(h.id)!;
pendingDelegates.delete(h.id);
const insert: LLMMessage[] = [...subHistory.filter(sh => sh.role === 'tool'), {role: 'assistant', content: delegateResp, timestamp: Date.now()}];
const insert: LLMMessage[] = [...subHistory.filter(sh => sh.role === 'tool'), {role: 'assistant', content: delegateResp, timestamp: Date.now(), duration, tps}];
history.splice(i + 1, 0, ...insert);
lastDelegateResp = delegateResp;
i += insert.length;