Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : src/lib/cost/ai/provider.ts9 * Module : lib10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-09-0812 * Last Modified : 2026-09-0813 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Abstraction du modèle de vision (§181) + fournisseur Claude Sonnet 5 (§94,44 * 134-136, 180-182). Sortie structurée via un outil imposé par `tool_choice`45 * (schéma JSON complet ; `strict` optionnel — voir note dans analyze), streaming46 * + `finalMessage()`, prompt système versionné et mis en cache,47 * validation/réparation maison + 1 relance.48 * Aucune chaîne de pensée n'est conservée.49 */50import Anthropic from "@anthropic-ai/sdk";51import fs from "fs";52import path from "path";53import { buildModelSchema, MAX_MISSING_SECTIONS, missingTopLevelSections, PROMPT_VERSION, schemaForApi, validateAndRepair, type ModelOutput, type ValidationIssue } from "./schema";54import type { ImageMediaType } from "./images";5556export const DEFAULT_MODEL = "claude-sonnet-5";57export const TOOL_NAME = "submit_property_analysis";58/** Tarif Sonnet 5 (USD / M jetons) — pour l'estimation de coût API (admin). */59export const PRICING_USD = { input: 2.0, output: 10.0, cacheRead: 0.2, cacheWrite: 2.5 };6061export interface AnalyzeImage { id: string; mediaType: ImageMediaType; data: Buffer; roomHint: string; position: number }62export interface AnalyzeInput {63 listingContext: string; // texte déterministe : champs structurés + description + MAMH64 images: AnalyzeImage[];65 assemblyCodes: string[];66 assemblyCatalogueText: string; // codes + libellés + unités67}68export interface AnalyzeUsage { inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; estimatedCostUsd: number; latencyMs: number; attempts: number }69export interface AnalyzeResult { output: ModelOutput; usage: AnalyzeUsage; model: string; promptVersion: string; issues: ValidationIssue[] }7071export interface PropertyVisionModel {72 readonly model: string;73 analyze(input: AnalyzeInput): Promise<AnalyzeResult>;74}7576let promptCache: string | null = null;77export function loadSystemPrompt(): string {78 if (promptCache) return promptCache;79 const p = path.join(process.cwd(), "prompts", `property-cost-analysis-${PROMPT_VERSION}.md`);80 promptCache = fs.readFileSync(p, "utf8");81 return promptCache;82}8384export function estimateCostUsd(u: { input: number; output: number; cacheRead: number; cacheWrite: number }): number {85 return (u.input * PRICING_USD.input + u.output * PRICING_USD.output + u.cacheRead * PRICING_USD.cacheRead + u.cacheWrite * PRICING_USD.cacheWrite) / 1_000_000;86}8788export class ClaudeSonnet5Provider implements PropertyVisionModel {89 readonly model: string;90 private client: Anthropic;91 constructor(model = process.env.PROPERTY_ANALYSIS_MODEL ?? DEFAULT_MODEL, client?: Anthropic) {92 this.model = model;93 this.client = client ?? new Anthropic();94 }9596 async analyze(input: AnalyzeInput): Promise<AnalyzeResult> {97 const schema = buildModelSchema(input.assemblyCodes);98 const system: Anthropic.TextBlockParam[] = [99 { type: "text", text: loadSystemPrompt(), cache_control: { type: "ephemeral" } },100 { type: "text", text: `## Assembly catalogue (only these codes are valid)\n${input.assemblyCatalogueText}`, cache_control: { type: "ephemeral" } },101 ];102 const manifest = input.images.map((i) => `${i.id}: position ${i.position}, room_hint=${i.roomHint}`).join("\n");103 const content: Anthropic.ContentBlockParam[] = [];104 for (const img of input.images) {105 content.push({ type: "text", text: `[${img.id}]` });106 content.push({ type: "image", source: { type: "base64", media_type: img.mediaType, data: img.data.toString("base64") } });107 }108 content.push({ type: "text", text: `## Image manifest\n${manifest}\n\n## Listing context\n${input.listingContext}\n\nExtract the building profile now by calling the ${TOOL_NAME} tool. Fill every field; use null when not supported by evidence.` });109 // Mode strict de l'API : limité à 16 paramètres nullables/union — notre schéma en compte ~150 (chaque110 // inférence est nullable par conception, §94). On force donc l'outil (tool_choice) sans `strict`, et la111 // conformité est garantie par le validateur/réparateur local + une relance. STRICT=1 réactive le mode strict.112 const strict = process.env.PROPERTY_ANALYSIS_STRICT === "1";113 const tools: Anthropic.Tool[] = [{ name: TOOL_NAME, description: "Structured technical profile of the building for the cost engine (no monetary values). Every field is required; use null when evidence is missing.", ...(strict ? { strict: true } : {}), input_schema: schemaForApi(schema) as Anthropic.Tool.InputSchema }];114 const messages: Anthropic.MessageParam[] = [{ role: "user", content }];115116 const t0 = Date.now();117 let inTok = 0, outTok = 0, cacheRead = 0, cacheWrite = 0;118 let attempts = 0;119 let lastIssues: ValidationIssue[] = [];120 let output: ModelOutput | null = null;121 // tool_choice : `auto` au 1er essai — un outil FORCÉ (`type:"tool"`) sans réflexion fait parfois122 // répondre Sonnet 5 par un placeholder ({"property_analysis":{"placeholder":true}}, 44 jetons) sur ce123 // schéma de ~150 champs (constaté 2026-09-08 sur une annonce Facebook Marketplace ; la même requête en124 // `auto` produit 21 Ko d'analyse). `any` en relance : le modèle doit appeler un outil, avec le retour d'erreur.125 const MAX_ATTEMPTS = 3;126 while (attempts < MAX_ATTEMPTS && !output) {127 attempts++;128 const stream = this.client.messages.stream({129 model: this.model, max_tokens: 24000, system, messages, tools, tool_choice: attempts === 1 ? { type: "auto" } : { type: "any" }, thinking: { type: "disabled" },130 });131 const msg = await stream.finalMessage();132 inTok += msg.usage.input_tokens; outTok += msg.usage.output_tokens;133 cacheRead += msg.usage.cache_read_input_tokens ?? 0; cacheWrite += msg.usage.cache_creation_input_tokens ?? 0;134 if (msg.stop_reason === "refusal") throw new Error("Le modèle a refusé l'analyse (stop_reason=refusal).");135 const tu = msg.content.find((b): b is Anthropic.ToolUseBlock => b.type === "tool_use" && b.name === TOOL_NAME);136 if (!tu) {137 lastIssues = [{ path: "$", message: `aucun appel d'outil (stop_reason=${msg.stop_reason})`, repaired: false }];138 } else {139 const { value, issues } = validateAndRepair(tu.input, schema);140 const hard = issues.filter((i) => !i.repaired);141 const missing = missingTopLevelSections(issues);142 lastIssues = missing.length > MAX_MISSING_SECTIONS143 ? [{ path: "$", message: `sortie vide ou placeholder — ${missing.length} sections absentes (${missing.slice(0, 6).join(", ")}…)`, repaired: false }, ...issues]144 : issues;145 if (!hard.length && missing.length <= MAX_MISSING_SECTIONS) { output = value as ModelOutput; break; }146 }147 if (attempts >= MAX_ATTEMPTS) break;148 // relance avec les erreurs de validation (la sortie fautive reste dans l'historique du tour)149 messages.push({ role: "assistant", content: msg.content.map((b) => (b.type === "tool_use" ? { type: "tool_use" as const, id: b.id, name: b.name, input: b.input } : b.type === "text" ? { type: "text" as const, text: b.text } : { type: "text" as const, text: "" })).filter((b) => b.type !== "text" || b.text) });150 const toolId = msg.content.find((b): b is Anthropic.ToolUseBlock => b.type === "tool_use")?.id;151 const feedback = `Schema validation failed:\n${lastIssues.slice(0, 40).map((i) => `${i.path}: ${i.message}`).join("\n")}\nThis was not an analysis. Look at every photo and the listing context, then call ${TOOL_NAME} again with the COMPLETE input: all top-level sections (property, geometry, construction, exterior, interior, kitchens, bathrooms, mechanical, electrical, plumbing, basement, garage, exterior_improvements, quality, condition, estimated_effective_age, renovations, estimated_quantities, assemblies, uncertainties, privacy) filled, null only where evidence is missing. Never return a placeholder.`;152 messages.push({ role: "user", content: toolId ? [{ type: "tool_result", tool_use_id: toolId, is_error: true, content: feedback }] : feedback });153 }154 if (!output) throw new Error(`Sortie du modèle invalide après ${attempts} tentative(s) : ${lastIssues.slice(0, 5).map((i) => `${i.path} ${i.message}`).join(" ; ")}`);155 return {156 output, model: this.model, promptVersion: PROMPT_VERSION, issues: lastIssues,157 usage: { inputTokens: inTok, outputTokens: outTok, cacheReadTokens: cacheRead, cacheWriteTokens: cacheWrite, estimatedCostUsd: estimateCostUsd({ input: inTok, output: outTok, cacheRead, cacheWrite }), latencyMs: Date.now() - t0, attempts },158 };159 }160}161