RotNot / src /lib /llm-hf.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
4.69 kB
// ---------------------------------------------------------------------------
// Hugging Face inference adapter.
//
// Lets the app run on a Hugging Face API token instead of an Anthropic key, so
// anyone can supply their own (free) HF token and use the AI features. The app
// keeps speaking the Anthropic Messages schema everywhere (claude.messages
// .create(...) → message.content[0].text); this adapter translates those calls
// to Hugging Face's OpenAI-compatible router (https://router.huggingface.co/v1)
// and translates the response back into the Anthropic shape.
//
// The Anthropic `model` id passed by call sites is ignored — the served model
// is chosen by HF_MODEL (an open instruct model). Everything is injectable
// (fetch) so it is unit-tested without network access.
// ---------------------------------------------------------------------------
export interface LlmContentBlock {
type: string;
text?: string;
}
export interface LlmMessage {
role: "user" | "assistant";
content: string | LlmContentBlock[];
}
export interface LlmCreateParams {
model: string;
max_tokens: number;
system?: string;
temperature?: number;
messages: LlmMessage[];
}
export interface LlmCreateResult {
content: Array<{ type: "text"; text: string }>;
stop_reason: string | null;
usage?: { input_tokens: number; output_tokens: number };
}
/** The minimal client surface the app uses (a subset of the Anthropic SDK). */
export interface LlmClient {
messages: { create(params: LlmCreateParams): Promise<LlmCreateResult> };
}
export interface HfClientOptions {
apiKey: string;
/** Defaults to the HF router. */
baseUrl?: string;
/** Open instruct model served by HF (e.g. meta-llama/Llama-3.1-8B-Instruct). */
model?: string;
/** Injectable fetch for testing. */
fetchImpl?: typeof fetch;
}
export const DEFAULT_HF_BASE_URL = "https://router.huggingface.co/v1";
// Reasoning model that returns clean JSON on "output only JSON" prompts; the
// `:fastest` suffix lets the HF router pick the fastest serving provider.
// Overridable per request (x-hf-model) or via the HF_MODEL env var.
export const DEFAULT_HF_MODEL = "deepseek-ai/DeepSeek-V4-Flash:fastest";
interface OpenAiMessage {
role: "system" | "user" | "assistant";
content: string;
}
function flattenContent(content: string | LlmContentBlock[]): string {
if (typeof content === "string") return content;
return content
.map((b) => (typeof b.text === "string" ? b.text : ""))
.join("");
}
/** Convert Anthropic-style params (system + messages) to OpenAI chat messages. */
export function toOpenAiMessages(params: LlmCreateParams): OpenAiMessage[] {
const out: OpenAiMessage[] = [];
if (params.system && params.system.trim().length > 0) {
out.push({ role: "system", content: params.system });
}
for (const m of params.messages) {
out.push({ role: m.role, content: flattenContent(m.content) });
}
return out;
}
export function createHuggingFaceClient(opts: HfClientOptions): LlmClient {
const baseUrl = (opts.baseUrl ?? DEFAULT_HF_BASE_URL).replace(/\/+$/, "");
const model = opts.model ?? DEFAULT_HF_MODEL;
const doFetch = opts.fetchImpl ?? fetch;
return {
messages: {
async create(params: LlmCreateParams): Promise<LlmCreateResult> {
const res = await doFetch(`${baseUrl}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${opts.apiKey}`,
},
body: JSON.stringify({
model,
messages: toOpenAiMessages(params),
max_tokens: params.max_tokens,
...(params.temperature != null ? { temperature: params.temperature } : {}),
}),
});
if (!res.ok) {
let detail = "";
try {
detail = await res.text();
} catch {
/* ignore */
}
throw new Error(
`Hugging Face inference error ${res.status}: ${detail.slice(0, 500)}`,
);
}
const data = (await res.json()) as {
choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;
usage?: { prompt_tokens?: number; completion_tokens?: number };
};
const text = data.choices?.[0]?.message?.content ?? "";
return {
content: [{ type: "text", text: String(text) }],
stop_reason: data.choices?.[0]?.finish_reason ?? null,
usage: {
input_tokens: data.usage?.prompt_tokens ?? 0,
output_tokens: data.usage?.completion_tokens ?? 0,
},
};
},
},
};
}