import Anthropic from "@anthropic-ai/sdk";
import { createHuggingFaceClient, DEFAULT_HF_MODEL } from "./llm-hf";
import { getLlmConfig, type LlmConfig } from "./llm-context";
// ---------------------------------------------------------------------------
// Per-request LLM provider selection.
//
// The app speaks the Anthropic Messages schema everywhere; the actual backend
// is chosen per request so each visitor can run the AI features on their own
// (free) Hugging Face token instead of a single shared key.
//
// Priority for resolving the provider:
// 1. an HF token passed for this request (x-hf-token header → LlmConfig)
// 2. env HF_TOKEN / HF_API_KEY (a Space-wide shared fallback)
// 3. Anthropic (ANTHROPIC_API_KEY / ANTHROPIC_BASE_URL)
//
// The request context (runWithLlmConfig / getLlmConfig) lives in llm-context.ts
// so route tests that mock this module keep working. withApiError sets the
// context, and the singleton `claude` export — used unchanged at ~21 call
// sites — transparently picks up the active request's credentials.
// ---------------------------------------------------------------------------
export type { LlmConfig } from "./llm-context";
export { runWithLlmConfig, getLlmConfig, llmConfigFromHeaders } from "./llm-context";
export type ResolvedProvider =
| { provider: "hf"; apiKey: string; model: string; baseUrl?: string }
| { provider: "anthropic" }
| { provider: "none" };
const globalForClaude = globalThis as unknown as {
claude?: Anthropic;
__defaultClaude?: Anthropic;
};
function clean(v: string | null | undefined): string | undefined {
const t = v?.trim();
return t ? t : undefined;
}
/**
* Pure provider resolver. Reads the given config (defaulting to the active
* request context) plus environment, and reports which backend to use.
*/
export function resolveLlmProvider(
config: LlmConfig = getLlmConfig() ?? {},
): ResolvedProvider {
const hfToken =
clean(config.hfToken) ?? clean(process.env.HF_TOKEN) ?? clean(process.env.HF_API_KEY);
if (hfToken) {
return {
provider: "hf",
apiKey: hfToken,
model: clean(config.hfModel) ?? clean(process.env.HF_MODEL) ?? DEFAULT_HF_MODEL,
baseUrl: clean(process.env.HF_BASE_URL),
};
}
if (clean(process.env.ANTHROPIC_API_KEY)) return { provider: "anthropic" };
return { provider: "none" };
}
/** Whether any LLM backend is reachable for the given/active config. */
export function isLlmAvailable(config?: LlmConfig): boolean {
return resolveLlmProvider(config).provider !== "none";
}
/**
* Resolve an LLM client for the given (or active request) config. The HF
* adapter implements only the surface the app uses (messages.create →
* content[0].text), so it is cast to the Anthropic type to keep call sites
* unchanged. The env-only Anthropic client is memoized as a singleton.
*/
export function getClaude(config: LlmConfig = getLlmConfig() ?? {}): Anthropic {
const resolved = resolveLlmProvider(config);
if (resolved.provider === "hf") {
return createHuggingFaceClient({
apiKey: resolved.apiKey,
baseUrl: resolved.baseUrl,
model: resolved.model,
}) as unknown as Anthropic;
}
// anthropic / none → real Anthropic SDK (no key → it throws on first call).
if (!globalForClaude.__defaultClaude) {
globalForClaude.__defaultClaude = new Anthropic();
}
return globalForClaude.__defaultClaude;
}
/**
* Back-compat singleton used unchanged at ~21 call sites. A proxy that
* resolves the right client per access, honoring the active request's
* credentials (set by withApiError) and falling back to the env default.
*/
export const claude: Anthropic = new Proxy({} as Anthropic, {
get(_t, prop, receiver) {
const client = getClaude();
const value = Reflect.get(client as object, prop, receiver);
return typeof value === "function" ? value.bind(client) : value;
},
});
/**
* Remove … / … blocks. Reasoning models
* (e.g. DeepSeek) and some HF models emit these inline before the answer.
*/
function stripThinkingTokens(text: string): string {
return text
.replace(/[\s\S]*?<\/thinking>/gi, "")
.replace(/[\s\S]*?<\/think>/gi, "")
.trim();
}
/**
* Walk `text` from the first `{` or `[` and return the first balanced JSON
* object/array span, respecting string literals and escapes. Returns null if
* no balanced span exists.
*/
function extractFirstJsonSpan(text: string): string | null {
const firstBrace = text.indexOf("{");
const firstBracket = text.indexOf("[");
if (firstBrace === -1 && firstBracket === -1) return null;
let start: number;
if (firstBrace === -1) start = firstBracket;
else if (firstBracket === -1) start = firstBrace;
else start = Math.min(firstBrace, firstBracket);
const open = text[start] as "{" | "[";
const close = open === "{" ? "}" : "]";
let depth = 0;
let inString = false;
let escape = false;
for (let i = start; i < text.length; i++) {
const ch = text[i];
if (escape) { escape = false; continue; }
if (ch === "\\" && inString) { escape = 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(start, i + 1);
}
}
return null;
}
/**
* Strip thinking tokens and markdown code fences, then JSON.parse. Used in
* 15+ AI routes — correctness here impacts every AI-backed feature.
*
* Primary: strip thinking tokens → strip fences → JSON.parse.
* Last-resort: when the primary parse fails (e.g. a reasoning model wraps the
* JSON in prose), extract the first balanced {…}/[…] span and parse that.
* Still throws SyntaxError when no valid JSON can be found.
*/
export function parseClaudeJson(text: string): T {
const stripped = stripThinkingTokens(text)
.replace(/^```(?:json)?\s*/i, "")
.replace(/\s*```\s*$/, "")
.trim();
try {
return JSON.parse(stripped) as T;
} catch {
const span = extractFirstJsonSpan(stripped);
if (span !== null) {
return JSON.parse(span) as T; // propagates SyntaxError if the span is malformed
}
throw new SyntaxError(
`No JSON object or array found in response: ${text.slice(0, 120)}`,
);
}
}
/**
* Two-phase LLM formatting pass: takes raw freeform text and a schema
* description, returns structured JSON. Uses Haiku for cost efficiency
* since this is a pure formatting task.
*/
export async function formatToJson(rawText: string, schema: string): Promise {
const message = await claude.messages.create({
model: "claude-haiku-4-5-20251001",
max_tokens: 2048,
messages: [
{
role: "user",
content: `Transform the following content into the exact JSON structure below. Output ONLY the raw JSON — no markdown, no code fences, no explanation.
REQUIRED JSON SCHEMA:
${schema}
CONTENT TO TRANSFORM:
${rawText}`,
},
],
});
const raw = message.content[0].type === "text" ? message.content[0].text : "";
return parseClaudeJson(raw);
}