Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/api/src/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,9 @@ export function openDb(path: string) {
if (!columns('appeals').some((c) => c.name === 'created_by')) sqlite.exec('ALTER TABLE appeals ADD COLUMN created_by TEXT');
if (!columns('appeals').some((c) => c.name === 'decided_by')) sqlite.exec('ALTER TABLE appeals ADD COLUMN decided_by TEXT');
if (!columns('reviews').some((c) => c.name === 'by_id')) sqlite.exec('ALTER TABLE reviews ADD COLUMN by_id TEXT');
if (!columns('evaluations').some((c) => c.name === 'diagnostics')) sqlite.exec('ALTER TABLE evaluations ADD COLUMN diagnostics TEXT');
// Historical jobs keep their original single-attempt budget; new jobs explicitly opt into retries.
if (!columns('jobs').some((c) => c.name === 'max_attempts')) sqlite.exec('ALTER TABLE jobs ADD COLUMN max_attempts INTEGER NOT NULL DEFAULT 1');
return drizzle(sqlite, { schema });
}

Expand Down
2 changes: 2 additions & 0 deletions apps/api/src/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export const evaluations = sqliteTable('evaluations', {
error: text('error'),
cacheContext: text('cache_context'),
decisionFacts: text('decision_facts', { mode: 'json' }),
diagnostics: text('diagnostics', { mode: 'json' }),
createdAt: text('created_at').notNull(),
});

Expand All @@ -66,6 +67,7 @@ export const jobs = sqliteTable('jobs', {
id: text('id').primaryKey(),
checklistVersionId: text('checklist_version_id').notNull(),
force: integer('force', { mode: 'boolean' }).notNull().default(false),
maxAttempts: integer('max_attempts').notNull().default(1),
conversationIds: text('conversation_ids', { mode: 'json' }).$type<string[]>().notNull(),
evaluationIds: text('evaluation_ids', { mode: 'json' }).$type<string[]>().notNull(),
status: text('status').notNull(),
Expand Down
16 changes: 15 additions & 1 deletion apps/api/src/routes/evaluations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ export function evaluationRoutes(app: FastifyInstance, db: Db, runner: JobRunner
if (denied(req, reply, 'evaluate')) return;
const body = StartEvaluationInputSchema.safeParse(req.body);
if (!body.success) return reply.code(400).send({ error: 'body must be { conversationIds: string[], checklistVersionId: string }' });
const actor = actorOf(req);
if (scopeOf(db, actor) !== null) {
const visible = new Set(listConversationViews(db, {}, actor).map(c => c.id));
if (body.data.conversationIds.some(id => !visible.has(id))) return reply.code(404).send({ error: 'conversations not found' });
}
try {
const job = runner.start(body.data);
logEvent(db, actorOf(req), { type: 'evaluation.started', summary: `Запущена оценка диалогов: ${body.data.conversationIds.length}`, data: { jobId: job.id, count: body.data.conversationIds.length, checklistVersionId: body.data.checklistVersionId, force: !!(body.data.force || body.data.fresh) } });
Expand All @@ -40,7 +45,16 @@ export function evaluationRoutes(app: FastifyInstance, db: Db, runner: JobRunner
}
});

app.get<{ Params: { id: string } }>('/api/jobs/:id', async (req, reply) => runner.getJob(req.params.id) ?? reply.code(404).send({ error: 'job not found' }));
app.get<{ Params: { id: string } }>('/api/jobs/:id', async (req, reply) => {
const ids = runner.conversationIds(req.params.id);
if (!ids) return reply.code(404).send({ error: 'job not found' });
const actor = actorOf(req);
if (scopeOf(db, actor) !== null) {
const visible = new Set(listConversationViews(db, {}, actor).map(c => c.id));
if (ids.some(id => !visible.has(id))) return reply.code(404).send({ error: 'job not found' });
}
return runner.getJob(req.params.id);
});

app.get<{ Params: { id: string } }>('/api/evaluations/:id', async (req, reply) => (evaluationVisible(db, req.params.id, actorOf(req)) && getEvaluation(db, req.params.id)) || reply.code(404).send({ error: 'evaluation not found' }));

Expand Down
16 changes: 9 additions & 7 deletions apps/api/src/services/evaluation/anthropic.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ProviderError, type LlmProvider, type ProviderRequest, type ProviderResponse } from './provider.js';
import { addUsage, emptyUsage, ProviderError, type LlmProvider, type ProviderRequest, type ProviderResponse } from './provider.js';

export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max'];
Expand Down Expand Up @@ -46,6 +46,7 @@ export class AnthropicProvider implements LlmProvider {
const retries = this.o.retries ?? 3;
const started = Date.now();
let lastStatus = 0;
const usage = emptyUsage();
// A reply without the tool call is also retried once: with `auto` the model may answer in prose.
let missingTool = 0;
for (let attempt = 0; attempt <= retries; attempt++) {
Expand All @@ -68,17 +69,18 @@ export class AnthropicProvider implements LlmProvider {
lastStatus = res.status;
if (res.ok) {
const body = (await res.json()) as Body;
if (body.stop_reason === 'refusal') throw new ProviderError(`model refused (${body.stop_details?.category ?? 'no category'})`);
if (body.stop_reason === 'max_tokens') throw new ProviderError('model output was cut off at max_tokens');
const u = body.usage;
addUsage(usage, u ? { inputTokens: u.input_tokens, outputTokens: u.output_tokens, cacheReadTokens: u.cache_read_input_tokens, cacheWriteTokens: u.cache_creation_input_tokens } : undefined);
if (body.stop_reason === 'refusal') throw new ProviderError(`model refused (${body.stop_details?.category ?? 'no category'})`, usage, false);
if (body.stop_reason === 'max_tokens') throw new ProviderError('model output was cut off at max_tokens', usage);
const tool = body.content?.find((c) => c.type === 'tool_use');
if (!tool) {
if (++missingTool > 1) throw new ProviderError('model returned no tool call');
if (++missingTool > 1) throw new ProviderError('model returned no tool call', usage);
continue;
}
const u = body.usage;
return {
output: tool.input,
usage: u ? { inputTokens: u.input_tokens, outputTokens: u.output_tokens, cacheReadTokens: u.cache_read_input_tokens, cacheWriteTokens: u.cache_creation_input_tokens } : undefined,
usage,
latencyMs: Date.now() - started,
};
}
Expand All @@ -88,6 +90,6 @@ export class AnthropicProvider implements LlmProvider {
lastStatus = 0; // network/timeout: retry; details dropped on purpose
}
}
throw new ProviderError(`provider request failed (status ${lastStatus || 'network error'})`);
throw new ProviderError(`provider request failed (status ${lastStatus || 'network error'})`, usage, lastStatus === 0 || lastStatus === 429 || lastStatus >= 500);
}
}
27 changes: 18 additions & 9 deletions apps/api/src/services/evaluation/evaluator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import { PROMPT_VERSION, systemPromptFor } from './prompts.js';
import { originalCriterion } from './rubric.js';
import { ORIGINAL_SEMANTIC_HELPERS, type DecisionFacts } from './semantic/index.js';
import { buildOutputSchema } from './output-schema.js';
import type { LlmProvider } from './provider.js';
import { addUsage, ProviderError, type LlmProvider } from './provider.js';

export class EvaluationFailure extends Error {}
export class EvaluationFailure extends Error {
constructor(message: string, public readonly provenance?: Provenance, public readonly decisionFacts?: DecisionFacts, public readonly diagnostics?: NonNullable<import('@cqa/contracts').Evaluation['diagnostics']>) { super(message); }
}

export { IDENTITY_VERIFIED_PATTERNS, deriveFacts as deriveContext } from './facts.js';

Expand Down Expand Up @@ -181,6 +183,7 @@ export type EvaluatorResult = {
total: number | null;
seriousViolation: boolean;
provenance: Provenance;
diagnostics: NonNullable<import('@cqa/contracts').Evaluation['diagnostics']>;
usage: { inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number };
latencyMs: number;
/** Criteria the model decided or helped decide in this run (empty when rules and reuse covered everything). */
Expand All @@ -195,6 +198,7 @@ export async function evaluateConversation(provider: LlmProvider | undefined, co
const { decided, assisted, undecided } = planCriteria(conversation, checklist, reuse);
const usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
let latencyMs = 0;
const calls: NonNullable<import('@cqa/contracts').Evaluation['diagnostics']>['calls'] = [];
const started = performance.now();
const modelResults = new Map<string, CriterionResult>();
const decisionFacts = new Map<string, DecisionFacts[string]>();
Expand All @@ -216,13 +220,18 @@ export async function evaluateConversation(provider: LlmProvider | undefined, co
let problems: string[] = [];
let ok = false;
for (let attempt = 1; attempt <= maxAttempts && !ok; attempt++) {
const res = await provider.complete({ system, user: buildUserPayload(conversation, subset, initialDecided, assisted, problems), outputSchema });
usage.inputTokens += res.usage?.inputTokens ?? 0;
usage.outputTokens += res.usage?.outputTokens ?? 0;
usage.cacheReadTokens += res.usage?.cacheReadTokens ?? 0;
usage.cacheWriteTokens += res.usage?.cacheWriteTokens ?? 0;
let res;
try {
res = await provider.complete({ system, user: buildUserPayload(conversation, subset, initialDecided, assisted, problems), outputSchema });
} catch (e) {
if (e instanceof ProviderError) addUsage(usage, e.usage);
calls.push({ criteria: [...criteria, ...assisted.map(a => a.criterion)].map(c => c.id), attempt, problems: [e instanceof Error ? e.message : 'provider failed'] });
throw e;
}
addUsage(usage, res.usage);
const v = validateModelOutput(res.output, conversation, { ...checklist, criteria });
const a = validateAssisted(res.output, conversation, assisted);
calls.push({ criteria: [...criteria, ...assisted.map(a => a.criterion)].map(c => c.id), attempt, problems: [...v.problems, ...a.problems] });
if (v.results && a.problems.length === 0) {
for (const r of v.results) {
const { reusedFrom: _drop, ...clean } = r;
Expand All @@ -240,12 +249,12 @@ export async function evaluateConversation(provider: LlmProvider | undefined, co
if (!ok) throw new EvaluationFailure(`model output failed validation: ${problems.slice(0, 5).join('; ')}`);
}));
const failed = completed.find((r): r is PromiseRejectedResult => r.status === 'rejected');
if (failed) throw failed.reason;
if (failed) throw new EvaluationFailure(failed.reason instanceof Error ? failed.reason.message : 'evaluation failed', { provider: provider.name, model: provider.model, promptVersion: PROMPT_VERSION, ...(provider.effort ? { effort: provider.effort } : {}), usage, latencyMs: Math.round(performance.now() - started) }, Object.fromEntries(decisionFacts), { calls, retryable: !(failed.reason instanceof ProviderError) || failed.reason.retryable });
latencyMs = Math.round(performance.now() - started);
provenance = { provider: provider.name, model: provider.model, promptVersion: PROMPT_VERSION, ...(provider.effort ? { effort: provider.effort } : {}), usage, latencyMs };
}

const results = checklist.criteria.map((c) => decided.get(c.id) ?? modelResults.get(c.id)!);
const { total, seriousViolation } = scoreEvaluation(checklist, results);
return { results, decisionFacts: Object.fromEntries(decisionFacts), total, seriousViolation, provenance, usage, latencyMs, modelCriteria: [...modelResults.keys(), ...assisted.map((x) => x.criterion.id)] };
return { results, decisionFacts: Object.fromEntries(decisionFacts), total, seriousViolation, provenance, diagnostics: { calls }, usage, latencyMs, modelCriteria: [...modelResults.keys(), ...assisted.map((x) => x.criterion.id)] };
}
Loading
Loading