Expand description
§llmleaf-client
Official async Rust SDK for the llmleaf LLM
proxy. It speaks llmleaf’s OpenAI/OpenRouter-shaped JSON over HTTP — the wire is JSON,
never protobuf-binary — and covers every endpoint in clients/SPEC.md:
- chat completions, non-streaming (
Client::chat) and streaming (Client::chat_stream, animpl StreamofChatCompletionChunks that stops on the[DONE]sentinel); - the OpenAI Responses dialect, non-streaming (
Client::responses) and streaming (Client::responses_stream, animpl StreamofResponsesStreamEvents that ends on the terminalresponse.completed/incomplete/failedevent — there is no[DONE]sentinel); - embeddings (
Client::embeddings, with base64 → float decoding); - rerank (
Client::rerank, scoring documents against a query); - model catalog (
Client::list_models); - text-to-speech (
Client::speech→(bytes, content_type)) and the voice catalog (Client::voices); - speech-to-text (
Client::transcribe, multipart with thefilepart); - batches (
Client::create_batch,Client::get_batch,Client::cancel_batch,Client::batch_results→ an NDJSON stream ofBatchResultLines).
§Codegen
build.rs compiles proto/llmleaf/v1/llmleaf.proto with prost-build (real codegen,
run every build); the generated messages are exposed under pb. The public types
(re-exported at the crate root, e.g. ChatRequest) are hand-written serde structs
that produce the exact OpenAI JSON wire — prost compiles the proto while serde drives
the wire.
§Quickstart
use llmleaf_client::{Client, ChatRequest, ChatMessage};
let client = Client::new("https://gateway.example.com", "sk-...")?;
let resp = client
.chat(ChatRequest::new(
"gpt-4o-mini",
vec![ChatMessage::user("hi")],
))
.await?;
println!("{}", resp.first_text().unwrap_or_default());Modules§
- pb
- Prost-generated typed model, compiled from
proto/llmleaf/v1/llmleaf.protobybuild.rs. This is the “real codegen” proof: the proto genuinely compiles into the crate and the generated messages are available here as a typed mirror.
Structs§
- Architecture
- Model architecture metadata.
- Batch
Counts - Aggregate counts on a batch handle.
- Batch
Create Request POST /v1/batchesrequest body.- Batch
Error - A failed per-item batch response.
- Batch
Handle - A batch handle returned by create / retrieve / cancel.
- Batch
Request Item - One item in a batch create request: a
custom_idplus aChatRequestbody. - Batch
Response - A successful per-item batch response.
- Batch
Result Line - One line of the JSONL results stream.
- Chat
Completion Chunk - A streaming SSE frame (
object:"chat.completion.chunk"). - Chat
Message - A chat message (request or response).
- Chat
Request POST /v1/chat/completionsrequest body.- Chat
Response POST /v1/chat/completionsnon-streaming response (object:"chat.completion").- Choice
- One completion choice.
- Chunk
Choice - One streaming choice.
- Client
- Async client for the llmleaf gateway.
- Client
Builder - Builder for
Client. Obtain viaClient::builder. - Delta
- Incremental delta on a streaming choice.
- Embedding
- A single embedding vector. The transport always presents
embeddingas floats, even when the wire carried base64. - Embedding
Request POST /v1/embeddingsrequest body.- Embedding
Response POST /v1/embeddingsresponse (object:"list").- Function
Call - A function the model called.
argumentsis a JSON-encoded string (OpenAI shape). - Function
Call Delta - Incremental tool-call fragment on a streaming delta.
- Function
Def - A function the model MAY call.
parametersis a raw JSON Schema value. - Function
Name - Pin a specific function:
{"name":"..."}. - Image
Url {"url":"...","detail":"auto"}.- List
Models Response GET /v1/modelsresponse.- Model
Endpoint - Admin-only fallback-chain entry (present only with a valid
x-admin-token). - Model
Entry - One model in the catalog.
- Named
Tool Choice - Named tool choice:
{"type":"function","function":{"name":"..."}}. - Pricing
- Per-token pricing (decimal strings, USD).
- Prompt
Tokens Details - Breakdown of
Usage::prompt_tokens. Today only the cache-read (hit) share is surfaced — the count of prompt tokens served from the provider’s cache rather than processed fresh. - Reasoning
Detail - One structured reasoning (“thinking”) block (OpenRouter
reasoning_details[]). It expresses both open reasoning — visible text, optionally signed — and hidden reasoning — an encrypted/redacted blob the provider returns in place of the text.kind(wiretype) is the discriminator: - Rerank
Request POST /v1/rerankrequest body.- Rerank
Response POST /v1/rerankresponse (object:"list").- Rerank
Result - A single reranked document: its position in the request
documentsand its score. - Response
Format response_format:{"type":"text"|"json_object"|"json_schema","json_schema":{...}}.- Response
Function Call Item - A function call the model made (
{"type":"function_call","call_id","name","arguments"}).call_idpairs it with itsResponseFunctionCallOutputItem;argumentsis the raw JSON string exactly as emitted. - Response
Function Call Output Item - The caller’s answer to a function call, replayed on the next turn
(
{"type":"function_call_output","call_id":"...","output":"..."}). - Response
Message Item - A conversation message item. On the wire it is a role-keyed object with NO
"type"field:{"role":"user","content":"..."}.id/statusare output-only. - Response
Reasoning Item - A reasoning (“thinking”) item.
encrypted_contentis opaque and MUST be echoed back verbatim in the next request’s input to continue an encrypted reasoning turn (SPEC.md). - Response
Reasoning Text - One reasoning text entry. Its wire
"type"token is decided by the list it sits in on aResponseReasoningItem:summary[]→"summary_text",content[]→"reasoning_text". - Responses
Error - The inline error body carried on a failed
ResponsesResponse(status:"failed"); the proto’sErrorBody. Distinct from an HTTP error envelope (which surfaces ascrate::Error::Api) and from the streaming"error"event. - Responses
Incomplete Details status:"incomplete"refinement:"max_output_tokens" | "content_filter".- Responses
Input Tokens Details - Prompt-cache hit accounting inside
ResponsesUsage. - Responses
Named Tool Choice - The FLAT named tool choice:
{"type":"function","name":"..."}(no nestedfunction). - Responses
Output Tokens Details - Reasoning-token accounting inside
ResponsesUsage. - Responses
Reasoning reasoning:{"effort":"minimal"|"low"|"medium"|"high"|..., "summary":...}.- Responses
Request POST /v1/responsesrequest body.- Responses
Response - The response object (
object:"response"), also the snapshot carried by theresponse.created/response.in_progress/ terminal stream events. Wire fields this SDK does not model (tools, truncation, parallel_tool_calls, …) are ignored on decode. - Responses
Stream Event - One streaming SSE event. Unlike chat streaming there is NO
data: [DONE]sentinel: the stream ends after the terminalresponse.completed/response.incomplete/response.failedevent. This is a flat superset of every event’s fields —kindsays which are meaningful; see the accessor helpers. - Responses
Tool Def - A tool the model MAY call — FLAT in this dialect (
type/name/parametersat the top level, no nestedfunctionobject).parametersis a raw JSON Schema value. - Responses
Usage - Token accounting in the Responses dialect’s own names (
input_tokens/output_tokens, not the chat dialect’sprompt_tokens/completion_tokens). - Speech
Request POST /v1/audio/speechrequest body.- Tool
Call - A tool call emitted by the model.
- Tool
Call Delta - Streaming tool-call delta; fields arrive piecemeal.
- ToolDef
- A tool definition (
{"type":"function","function":{...}}). - TopProvider
- Top-provider capabilities for a model.
- Transcription
Request - The accompanying form fields for
POST /v1/audio/transcriptions. The audio bytes are the multipartfilepart and are passed separately to the SDK call. - Transcription
Response - Structured transcription result (for
response_formatjson / verbose_json). - Usage
- Token accounting echoed on every response.
cost_usdis an llmleaf addition and is absent when the model has no known price. - Voice
- A TTS voice.
- Voices
Response GET /v1/audio/voicesresponse.
Enums§
- Batch
Status - Batch lifecycle status.
- Content
- Message
content: a plain string when there is only text, else an array of parts. Untagged so it serialises as a bare string or a bare array, matching the wire. - Content
Part - A single content part of a multimodal message.
- Embedding
Input input: the wire accepts a bare string or an array of strings. Untagged.- Error
- Errors returned by the SDK.
- Finish
Reason - Why the model stopped generating.
- Model
Type typequery filter forGET /v1/models.- Rerank
Document - A rerank document. Usually a plain string; the wire also accepts a structured
multimodal object (
{ text?, image? }), captured here as raw JSON. Untagged, so it round-trips either shape (mirrors howEmbeddingInputstays JSON-flexible). - Response
Content - A Responses message
content: a bare string, or an array of parts. Untagged. - Response
Content Part - A single content part of a Responses message. The wire
"type"token matches the set variant; noteinput_image.image_urlis a plain string (not the chat dialect’s{url}object) andoutput_textalways carries anannotationsarray. - Response
Item - One item of the request
inputarray or the responseoutputarray. The wire discriminator is"type"; a message is the role-keyed object emitted with no"type"(and decoded from an absent or"message"type).ResponseItem::Otherpreserves any item type this SDK version does not model, verbatim. - Responses
Input input: a bare string (one user message) or an array of items. Untagged so it serialises as a bare string or a bare array, matching the wire.- Responses
Tool Choice tool_choice: a bare mode string ("auto"/"none"/"required") or the flat named object. Untagged so it serialises as a bare string or the object, matching the wire.- Role
- Message author role.
- Stop
stop: a bare string for one element, else an array (the wire accepts either; we emit a string for a single element and an array otherwise). Untagged.- Tool
Choice tool_choice: a bare mode string ("auto"/"none"/"required") or a named object. Untagged so it serialises as a bare string or the object, matching the wire.- Transcription
- Result of a transcription: a structured object (json/verbose_json) or a plain-text body (text/srt/vtt) — SPEC.md returns text directly for the latter.
Type Aliases§
- Result
- A convenience result alias.