BID · Console
Baseline · Intelligence · Decision
src/agents/intelligence/performance-metrics/llm.ts 9,253 bytes · typescript
/**
 * Performance Metrics — LLM + methodology-library tool-use loop.
 *
 * The agent walks its 7-step runbook with two methodology tools
 * available. For each requested metric the LLM is expected to:
 *   1. find_methodologies(type="metric_definition", domain, triggers)
 *   2. get_methodology(methodology_id) for any candidate
 *   3. apply the formula to the right cells from the analytical table
 *
 * Per-metric failure is expected and explicit (Std 12 — partial
 * results, with gaps surfaced). Self-contained per the codebase
 * convention.
 */

import Anthropic from '@anthropic-ai/sdk';
import type {
  Tool,
  ToolUseBlock,
  MessageParam,
  ContentBlock,
  TextBlock,
} from '@anthropic-ai/sdk/resources/messages.js';
import { z } from 'zod';

import { recordUsage } from '../../../observability/usage.js';
import { buildSystemPrompt } from './prompt.js';
import { METHODOLOGY_TOOLS, executeMethodologyTool } from '../../../intelligence/tools.js';
import {
  computedMetricSchema,
  methodologyGapSchema,
  type PerformanceMetricsInput,
  type PerformanceMetricsOutput,
} from './schema.js';
import type { JobRequest } from '../../../types.js';

const apiKey = process.env.ANTHROPIC_API_KEY;
const client = apiKey ? new Anthropic({ apiKey }) : null;

if (!client) {
  // eslint-disable-next-line no-console
  console.log(`[intelligence.performance-metrics] ANTHROPIC_API_KEY not set — agent will return a structured 'needs-api-key' failure.`);
}

const MODEL = 'claude-haiku-4-5';
const MAX_TOOL_ITERATIONS = 30;
const MAX_TOKENS_PER_TURN = 8000;

const ANTHROPIC_TOOLS: Tool[] = METHODOLOGY_TOOLS.map(t => ({
  name: t.name,
  description: t.description,
  input_schema: t.input_schema,
})) as Tool[];

export const MODEL_NAME = MODEL;
export const TOOL_COUNT = METHODOLOGY_TOOLS.length;
export const TOOL_NAMES: readonly string[] = METHODOLOGY_TOOLS.map(t => t.name);

export interface LlmFailure {
  readonly category: 'needs-api-key' | 'invalid-response' | 'sdk-error' | 'empty-response' | 'tool-loop-overrun';
  readonly reason: string;
  readonly hint?: string;
}
export type LlmResult<T> = { ok: true; value: T } | { ok: false; failure: LlmFailure };

export interface ToolCallTrace {
  readonly toolName: string;
  readonly input: Record<string, unknown>;
  readonly ok: boolean;
  readonly resultSummary: string;
  readonly errorMessage?: string;
  readonly at: string;
}

const responseSchema = z.object({
  metrics: z.array(computedMetricSchema),
  methodologyGaps: z.array(methodologyGapSchema).default([]),
  appliedMethodologies: z.array(z.string()).default([]),
  notes: z.array(z.string()).default([]),
});

function buildUserMessage(table: PerformanceMetricsInput, job: JobRequest): string {
  return [
    `## Performance Metrics — runbook execution`,
    ``,
    `## JobRequest`,
    `analysisId: ${job.analysisId}`,
    `question:   ${job.question}`,
    `targetMetrics (the metrics to compute):`,
    ...job.targetMetrics.map(m => `  - ${m.key}: ${m.definition}${m.unit ? ` (target unit ${m.unit})` : ''}`),
    ``,
    `## Analytical Table from Agent 1`,
    `entities: ${table.entities.join(', ')}`,
    `metrics:  ${table.metrics.join(', ')}`,
    `periods:  ${table.periods.join(', ')}`,
    `cells (${table.cells.length}):`,
    JSON.stringify(table.cells, null, 2),
    table.missingCells.length > 0
      ? `\nmissingCells (${table.missingCells.length}):\n${JSON.stringify(table.missingCells, null, 2)}`
      : '',
    ``,
    `## What to do`,
    `For every (entity × period) combination in the table, compute every requested target metric:`,
    `  - First call find_methodologies(type="metric_definition", domain matching the entity domain, triggers matching the metric key/definition).`,
    `  - If one or more candidates come back, call get_methodology(methodology_id) on the best match and apply its formula to the right cells.`,
    `  - If NO methodology applies AND the metric is a direct read of an existing table cell (e.g. the target_unit matches the cell unit and the metric key matches the cell metric), pass the cell value through with methodologyId=null and methodologyRationale explaining it.`,
    `  - If NO methodology applies AND the metric requires computation (ratio, derived value), add an entry to methodologyGaps and skip the metric for that (entity, period). Other metrics continue.`,
    ``,
    `## Output`,
    `Return ONLY a JSON object — no prose, no markdown fence — in this exact shape:`,
    `{`,
    `  "metrics": [`,
    `    {`,
    `      "metricKey":             string,`,
    `      "entity":                string,`,
    `      "period":                string,`,
    `      "value":                 number | null,`,
    `      "unit":                  string,`,
    `      "methodologyId":         string | null,    // library id, or null for identity pass-through`,
    `      "methodologyRationale":  string,            // why this methodology / why pass-through`,
    `      "inputLineage":          string[],          // sourceLineage from the cells used`,
    `      "confidence":            number,`,
    `      "flags":                 string[]`,
    `    }`,
    `  ],`,
    `  "methodologyGaps": [`,
    `    { "metricKey": string, "entity": string, "period": string, "reason": string }`,
    `  ],`,
    `  "appliedMethodologies": string[],   // unique methodology_id values applied`,
    `  "notes":                string[]`,
    `}`,
  ].filter(Boolean).join('\n');
}

function jsonResponseFromText(text: string): unknown {
  const cleaned = text.replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/i, '').trim();
  try { return JSON.parse(cleaned); } catch { /* fall through */ }
  const m = cleaned.match(/\{[\s\S]*\}/);
  if (!m) return null;
  try { return JSON.parse(m[0]); } catch { return null; }
}

function summarize(name: string, ok: boolean, result: unknown): string {
  if (!ok) return 'error';
  if (name === 'find_methodologies' && Array.isArray(result)) {
    return `${result.length} match(es): ${result.slice(0, 5).map((r: any) => r.methodology_id).join(', ')}`;
  }
  if (name === 'get_methodology' && result && typeof result === 'object') {
    const r = result as { methodology_id?: string; name?: string };
    return `${r.methodology_id ?? '?'} — ${r.name ?? ''}`;
  }
  return 'ok';
}

export interface ComputeResult {
  readonly metrics: PerformanceMetricsOutput;
  readonly toolCalls: readonly ToolCallTrace[];
}

export async function computeMetrics(
  table: PerformanceMetricsInput,
  job: JobRequest,
  onToolCall?: (t: ToolCallTrace) => void,
): Promise<LlmResult<ComputeResult>> {
  if (!client) {
    return {
      ok: false,
      failure: {
        category: 'needs-api-key',
        reason: 'Performance Metrics requires the LLM but ANTHROPIC_API_KEY is not configured.',
      },
    };
  }
  const system = buildSystemPrompt();
  const messages: MessageParam[] = [{ role: 'user', content: buildUserMessage(table, job) }];
  const toolCalls: ToolCallTrace[] = [];

  let finalText = '';
  for (let iter = 0; iter < MAX_TOOL_ITERATIONS; iter++) {
    let resp;
    try {
      resp = await client.messages.create({
        model: MODEL,
        max_tokens: MAX_TOKENS_PER_TURN,
        system,
        tools: ANTHROPIC_TOOLS,
        messages,
      });
    } catch (err) {
      return { ok: false, failure: { category: 'sdk-error', reason: err instanceof Error ? err.message : String(err) } };
    }
    recordUsage('intelligence.performance-metrics', MODEL, resp.usage.input_tokens, resp.usage.output_tokens);
    messages.push({ role: 'assistant', content: resp.content as ContentBlock[] });
    if (resp.stop_reason !== 'tool_use') {
      const textBlock = resp.content.find((b): b is TextBlock => b.type === 'text');
      finalText = textBlock ? textBlock.text : '';
      break;
    }
    const toolUses = resp.content.filter((b): b is ToolUseBlock => b.type === 'tool_use');
    const toolResults: { type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean }[] = [];
    for (const tu of toolUses) {
      const r = await executeMethodologyTool(tu.name, tu.input);
      const trace: ToolCallTrace = {
        toolName: tu.name,
        input: (tu.input ?? {}) as Record<string, unknown>,
        ok: r.ok,
        resultSummary: summarize(tu.name, r.ok, r.result),
        errorMessage: r.error?.message,
        at: new Date().toISOString(),
      };
      toolCalls.push(trace);
      onToolCall?.(trace);
      toolResults.push({
        type: 'tool_result',
        tool_use_id: tu.id,
        content: r.ok ? JSON.stringify(r.result) : JSON.stringify({ error: r.error }),
        is_error: !r.ok,
      });
    }
    messages.push({ role: 'user', content: toolResults });
  }
  if (!finalText) {
    return { ok: false, failure: { category: 'tool-loop-overrun', reason: `Tool-use loop exceeded ${MAX_TOOL_ITERATIONS} iterations.` } };
  }
  const parsed = responseSchema.safeParse(jsonResponseFromText(finalText));
  if (!parsed.success) {
    return { ok: false, failure: { category: 'invalid-response', reason: `final response did not match ComputedMetrics schema: ${parsed.error.message}` } };
  }
  return { ok: true, value: { metrics: parsed.data, toolCalls } };
}