papertrail/lib/claude.ts
caelum0x bd38aba7a0 fix: Trial Matcher fits serverless limit — Haiku eligibility + tighter output
After fixing the CT.gov search, the trial matcher actually ran its per-trial eligibility
fan-out and hit a 504 at the 60s Vercel limit (5 parallel Sonnet calls + profile extraction).
Eligibility is a fast per-criterion classification, so:
- callClaudeForJson gains an optional per-call model override (default unchanged); the
  accuracy-critical verify path is untouched.
- Per-trial eligibility now runs on Haiku (claude-haiku-4-5-20251001, override via
  TRIAL_MATCHER_MODEL) and assesses the leading 10 criteria/type at a 2560-token budget.

Full example run dropped from 56s to 34.5s (profile 9.9s) with 4 real matches, degraded=null
— comfortable margin under the 60s limit.
2026-07-12 00:36:04 +03:00

149 lines
4.9 KiB
TypeScript

import Anthropic from "@anthropic-ai/sdk";
let client: Anthropic | undefined;
export function getClaude(): Anthropic {
if (!client) {
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
throw new Error("ANTHROPIC_API_KEY is not set");
}
client = new Anthropic({ apiKey });
}
return client;
}
export const CLAUDE_MODEL = process.env.ANTHROPIC_MODEL || "claude-sonnet-4-6";
/**
* Calls Claude with a prompt that must return a single JSON object, and
* validates it against the provided Zod schema. Throws if the model doesn't
* produce valid JSON or the JSON doesn't match the schema - callers decide
* how to handle that (usually: surface a "couldn't verify" state, never
* silently fabricate a result).
*/
// Extract the first balanced JSON value (object or array) from a text that may contain
// surrounding prose — a common LLM behavior where the model explains before/after the JSON.
// Tracks string state + escapes so braces inside strings don't throw off the depth count.
function extractFirstJson(text: string): string | null {
const startIdx = (() => {
const obj = text.indexOf("{");
const arr = text.indexOf("[");
if (obj === -1) return arr;
if (arr === -1) return obj;
return Math.min(obj, arr);
})();
if (startIdx === -1) return null;
const open = text[startIdx];
const close = open === "{" ? "}" : "]";
let depth = 0;
let inString = false;
let escaped = false;
for (let i = startIdx; i < text.length; i++) {
const ch = text[i];
if (escaped) {
escaped = false;
continue;
}
if (ch === "\\") {
escaped = true;
continue;
}
if (ch === '"') {
inString = !inString;
continue;
}
if (inString) continue;
if (ch === open) depth++;
else if (ch === close) {
depth--;
if (depth === 0) return text.slice(startIdx, i + 1);
}
}
return null;
}
// Parse a model text block into JSON, tolerating code fences and surrounding prose.
function parseJsonLoose(text: string): unknown | undefined {
const cleaned = text
.trim()
.replace(/^```json\s*/i, "")
.replace(/^```\s*/i, "")
.replace(/```\s*$/i, "");
try {
return JSON.parse(cleaned);
} catch {
const extracted = extractFirstJson(cleaned);
if (extracted !== null) {
try {
return JSON.parse(extracted);
} catch {
return undefined;
}
}
return undefined;
}
}
export async function callClaudeForJson<T>(params: {
system: string;
user: string;
schema: { parse: (v: unknown) => T };
maxTokens?: number;
// Optional per-call model override. Defaults to CLAUDE_MODEL. Lets latency-sensitive,
// high-fan-out steps (e.g. per-trial eligibility) opt into a faster model without
// changing the global default used by the accuracy-critical verification path.
model?: string;
}): Promise<T> {
const anthropic = getClaude();
const model = params.model ?? CLAUDE_MODEL;
const call = async (system: string, user: string): Promise<unknown | undefined> => {
// Retry transient Anthropic errors (429 rate_limit, 529 overloaded, 503) with exponential
// backoff so a rate-limit blip degrades latency, not correctness. Non-transient errors and
// the final attempt propagate. Deterministic backoff (no jitter) keeps behavior reproducible.
let delayMs = 1000;
const maxRetries = 5;
for (let attempt = 0; ; attempt++) {
try {
const response = await anthropic.messages.create({
model,
max_tokens: params.maxTokens ?? 1024,
system,
messages: [{ role: "user", content: user }],
});
const textBlock = response.content.find((b) => b.type === "text");
if (!textBlock || textBlock.type !== "text") {
throw new Error("Claude response contained no text block");
}
return parseJsonLoose(textBlock.text);
} catch (err: unknown) {
const status = (err as { status?: number })?.status;
const transient = status === 429 || status === 529 || status === 503;
if (!transient || attempt >= maxRetries) throw err;
await new Promise((resolve) => setTimeout(resolve, delayMs));
delayMs *= 2;
}
}
};
// First attempt with the caller's prompt (prose-tolerant parse).
let parsedJson = await call(params.system, params.user);
// One stricter retry when the model editorialized instead of emitting a JSON value.
if (parsedJson === undefined) {
const strictSystem =
params.system +
"\n\nCRITICAL: Respond with ONLY a single JSON value — no explanation, no reasoning, " +
"no prose before or after it. The first character of your reply must be { or [.";
parsedJson = await call(strictSystem, params.user);
}
if (parsedJson === undefined) {
throw new Error("Claude did not return valid JSON after a retry.");
}
return params.schema.parse(parsedJson);
}