@codefionn/llmleaf-client

中文文档
0.6.4发布于 2026/10/11MIT OR Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 5450

Official TypeScript/JavaScript client for the llmleaf LLM proxy.

原始使用文档
文档目录8 节
  1. Install
  2. Example
  3. Endpoints
  4. Decisions
  5. Errors
  6. Run the example
  7. Regenerate from the proto
  8. Notes

@codefionn/llmleaf-client

TypeScript / JavaScript client for the llmleaf LLM proxy.

Speaks llmleaf's OpenAI/OpenRouter-shaped JSON over HTTP (see ../SPEC.md). Zero runtime dependencies beyond the @bufbuild/protobuf runtime, and it runs anywhere a global fetch / ReadableStream / FormData exists — Node 20+, Deno, Bun, browsers.

Install

npm install @codefionn/llmleaf-client

Example

import { LlmleafClient, Role } from "@codefionn/llmleaf-client";

const client = new LlmleafClient({
  baseUrl: "https://gateway.example.com",
  apiKey: process.env.LLMLEAF_API_KEY!,
  timeoutMs: 30_000,   // optional; 0/omitted = no timeout. Also: adminToken, fetch
});

// Non-streaming chat
const res = await client.chat({
  model: "gpt-4o-mini",
  messages: [{ role: Role.USER, content: "Say hi." }],
});
console.log(res.choices[0]?.message.content);

// Streaming chat — async iterable of chunks, stops at `data: [DONE]`
for await (const chunk of client.chatStream({
  model: "gpt-4o-mini",
  messages: [{ role: Role.USER, content: "Count to 5." }],
})) {
  process.stdout.write(chunk.choices[0]?.delta.content ?? "");
}

// Responses dialect (POST /v1/responses) — `input` is a bare string or an item array
const resp = await client.responses({
  model: "gpt-4o-mini",
  input: [{ type: "message", role: "user", content: "Say hi." }],
});

// Streaming responses — typed events, NO `[DONE]`; stops on the terminal
// response.completed / .incomplete / .failed event; unknown event types are skipped
for await (const event of client.responsesStream({
  model: "gpt-4o-mini",
  input: "Count to 5.",
})) {
  if (event.type === "response.output_text.delta") process.stdout.write(event.delta ?? "");
}

Streaming tool calls are exposed as choice.delta.toolCalls. Group fragments by the choice index and each ToolCallDelta.index; retain id / type / function name whenever present, and append every function.arguments fragment in arrival order until finishReason === FinishReason.TOOL_CALLS.

Endpoints

await client.chat(req);              // POST /v1/chat/completions
client.chatStream(req);              // stream:true, async iterable of chunks
await client.responses(req);         // POST /v1/responses (OpenAI Responses dialect)
client.responsesStream(req);         // stream:true, async iterable of typed events (no [DONE])
await client.embeddings(req);        // base64 vectors decoded to floats
await client.rerank(req);            // POST /v1/rerank; results by relevance (plain JSON)
await client.decisions(req);          // POST /v1/decisions; structured decision answers
await client.listModels({ type: "llm" });
await client.speech(req);            // -> { bytes, contentType }
await client.voices("tts-1");
await client.transcribe(file, req);  // multipart; json/verbose_json -> object, text/srt/vtt -> tr.text
await client.createBatch(req);
await client.getBatch(id);
await client.cancelBatch(id);
client.batchResults(id);             // async iterable of result lines

Free-form fields (extra, responseFormat.jsonSchema, functionDef.parameters, …) are raw JSON strings — pass JSON.stringify(obj) and the transport splices the parsed value in; extra keys merge at the top level of the request.

Decisions

const decision = await client.decisions({
  model: "jev",
  state: { turn: 2 },
  questions: {
    route: { type: "choice", instructions: "Which route?", criteria: { left: null, right: null } },
  },
});
console.log(decision.answers.route);

state, questions, answers, and decisions metadata use native JSON values. extra is a structured object merged into the body; it cannot override model, state, or questions.

Errors

Any non-2xx response throws a typed ApiError:

import { ApiError } from "@codefionn/llmleaf-client";

try {
  await client.chat(req);
} catch (e) {
  if (e instanceof ApiError) console.error(e.status, e.message); // 403 "model not allowed"
}

Run the example

examples/basic.ts does chat, streaming, and a model list:

LLMLEAF_BASE_URL=https://gateway.example.com LLMLEAF_API_KEY=sk-… npx tsx examples/basic.ts

Regenerate from the proto

The generated file (src/gen/llmleaf/v1/llmleaf_pb.ts) is committed; regenerate it after the proto changes:

npm install      # fetch the @bufbuild/protoc-gen-es plugin
npm run gen      # runs scripts/gen.sh (needs protoc on PATH)

Notes

  • The wire mapping is hand-written (src/wire.ts) because protobuf-es's JSON codec emits camelCase + SCREAMING_CASE, which isn't the OpenAI wire (snake_case + lowercase tokens). The generated descriptors stay available under the gen export for reflection.
  • Decoders are lenient (extra/missing fields tolerated). No retries. chatStream / batchResults need a streaming-capable fetch. Realtime WebSocket is out of scope.

版本与发布记录

@codefionn/llmleaf-client 共发布 30 个版本,首次发布于 2026/06/22;过去 12 个月发布了 30 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.6.4latest2026/10/1129 天前
0.6.32026/10/1030 天前
0.6.22026/10/101 个月前
0.6.12026/10/101 个月前
0.6.02026/10/091 个月前
0.5.02026/10/021 个月前

关于 @codefionn/llmleaf-client 的常见问题

@codefionn/llmleaf-client 是什么?

Official TypeScript/JavaScript client for the llmleaf LLM proxy.

如何安装 @codefionn/llmleaf-client?

在项目目录运行 npm install @codefionn/llmleaf-client,或使用 pnpm add / yarn add / bun add。

@codefionn/llmleaf-client 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@codefionn/llmleaf-client 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@codefionn/llmleaf-client 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@codefionn/llmleaf-client 可以商用吗?

@codefionn/llmleaf-client 使用 MIT OR Apache-2.0 许可。可在 MIT、Apache-2.0 中任选其一遵守。选择 MIT 时,宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@codefionn/llmleaf-client 的下载量有多少?

根据 npm 官方下载统计,@codefionn/llmleaf-client 在 2026/10/10 – 2026/11/08 这 30 天内被下载 5,450 次,日均约 182 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@codefionn/llmleaf-client 还在维护吗?

最新版本 0.6.4 发布于 2026/10/11(29 天前);至今共发布 30 个版本,其中过去 12 个月发布了 30 个;首次发布于 2026/06/22。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。