Download src/lib/llm-context.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 2.06 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/llm-context.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/lib/llm-context.ts
-
curl -L -o llm-context.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/llm-context.ts
2.06 kB
| // --------------------------------------------------------------------------- | |
| // Per-request LLM credential context. | |
| // | |
| // Each visitor can run the app's AI features on their own (free) Hugging Face | |
| // token, supplied per request via the x-hf-token / x-hf-model headers. | |
| // withApiError() reads those headers and runs every route handler inside | |
| // runWithLlmConfig(), so the `claude` singleton (used unchanged at ~21 call | |
| // sites) transparently resolves the active request's credentials. | |
| // | |
| // This lives in its own module — separate from claude.ts — so that the many | |
| // route tests that `vi.mock("@/lib/claude")` keep working: withApiError pulls | |
| // the context primitives from here, not from the mocked claude module. | |
| // --------------------------------------------------------------------------- | |
| import { AsyncLocalStorage } from "node:async_hooks"; | |
| /** Per-request LLM credentials (typically derived from request headers). */ | |
| export interface LlmConfig { | |
| hfToken?: string; | |
| hfModel?: string; | |
| } | |
| const globalForLlm = globalThis as unknown as { | |
| __llmStore?: AsyncLocalStorage<LlmConfig>; | |
| }; | |
| // Singleton store so request context survives Next.js HMR module reloads. | |
| const llmStore: AsyncLocalStorage<LlmConfig> = | |
| globalForLlm.__llmStore ?? new AsyncLocalStorage<LlmConfig>(); | |
| globalForLlm.__llmStore = llmStore; | |
| /** Run `fn` with request-scoped LLM credentials visible to getClaude()/claude. */ | |
| export function runWithLlmConfig<T>(config: LlmConfig, fn: () => T): T { | |
| return llmStore.run(config, fn); | |
| } | |
| /** The active request's LLM config, or undefined outside a request. */ | |
| export function getLlmConfig(): LlmConfig | undefined { | |
| return llmStore.getStore(); | |
| } | |
| function clean(v: string | null | undefined): string | undefined { | |
| const t = v?.trim(); | |
| return t ? t : undefined; | |
| } | |
| /** Build an LlmConfig from request headers (x-hf-token / x-hf-model). */ | |
| export function llmConfigFromHeaders(headers: Headers): LlmConfig { | |
| return { | |
| hfToken: clean(headers.get("x-hf-token")), | |
| hfModel: clean(headers.get("x-hf-model")), | |
| }; | |
| } | |