File size: 7,168 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
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 <thinking>…</thinking> / <think>…</think> blocks. Reasoning models
 * (e.g. DeepSeek) and some HF models emit these inline before the answer.
 */
function stripThinkingTokens(text: string): string {
  return text
    .replace(/<thinking>[\s\S]*?<\/thinking>/gi, "")
    .replace(/<think>[\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<T>(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<T>(rawText: string, schema: string): Promise<T> {
  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<T>(raw);
}