File size: 4,685 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
// ---------------------------------------------------------------------------
// 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,
          },
        };
      },
    },
  };
}