LLM API
The llm plugin gives one call shape for large language models: Anthropic Claude, OpenAI, Google Gemini, xAI Grok,
Mistral, Moonshot Kimi, DeepSeek, OpenRouter, Azure OpenAI, Amazon Bedrock and OpenAI-compatible servers you host yourself (Ollama,
vLLM, llama.cpp, LM Studio). Your code asks for a
profile or a route by name. The site's configuration decides which provider, model and key are behind that name. Several
profiles can be active at once, and a route tries its profiles in order: when one fails (rate limit, outage, missing key), the
next one answers. No library is needed: requests go out over curl. Nothing runs until a site configures a profile.
Calls
$r = llm()->chat('Summarise in one line: ' . $text); // the default route
if ($r->ok) {
echo _prepare_html($r->text);
}
$r = llm('summaries')->chat([
['role' => 'system', 'content' => 'You write short summaries.'],
['role' => 'user', 'content' => $text],
], ['max_tokens' => 300]);
$title = llm('titles')->complete('A title for: ' . $text); // the text, '' on failure
llm() is _class('llm') (yf_llm). llm('name') returns a copy bound to the profile or
route name; ['profile' => 'name'] in the options does the same for one call. Messages are a string (one user
message) or a list of role (system, user, assistant) and content (text).
| Option | Meaning |
|---|---|
profile | Profile or route name for this call. |
feature | Your name for the part of the site that calls (logs, usage and budgets group by it); default: the route name. |
model | Another model of the same provider for this call. |
system | System instructions (joined with any system messages). |
max_tokens | Longest answer in tokens. The site may cap it. |
json | true: ask for one JSON object; an array: a JSON schema the answer must follow (structured output where the
provider has it). Read it with $r->json(). |
effort | Reasoning effort (low, medium, high...) on the models that take it. |
temperature, top_p, stop | Sampling and stop sequences. Claude's current API takes no sampling settings: they are
dropped and noted in $r->warnings. |
extra | More request fields, sent as they are (provider-specific). |
stream | A function that gets each piece of the answer as it arrives (see Streaming). |
The answer
chat() always returns a yf_llm_response, a failed call too. Check ok first.
| Field | Meaning |
|---|---|
ok, text | Whether the provider answered, and the answer text. |
finish_reason | stop, length (cut at max_tokens), tool_calls, content_filter,
refusal, pause, error. |
usage | Tokens: input (all prompt tokens), cached (read from the prompt cache), cache_write,
output, reasoning. |
cost | USD from the site's price table; null when the model has no price there. |
latency_ms, attempts | Time of the whole call and HTTP attempts of the profile that answered. |
profile, provider, model, id | Who answered. |
fallbacks | The profiles that failed before, with their errors. |
error, error_type | Why it failed: auth, permission, billing, not_found, bad_request,
rate_limit, overloaded, server, network, config, budget (a spending limit of the site), disabled. Errors never hold the API key. |
tool_calls | id, name, arguments of the tools the model asked for (tool definitions come in a later phase). |
raw | The decoded provider answer, for anything the fields above do not carry. |
A request is retried on the same profile after a rate limit (429), an overload or server error (5xx) or no answer, with a growing
random wait or the provider's retry-after. When the provider asks to wait longer than the site allows, the call moves to the
next profile of the route instead. A bad request is not retried and does not move on: the next provider would refuse it too.
Streaming
$r = llm()->chat($messages, ['stream' => function (string $text) {
echo _prepare_html($text); // a piece of the answer, as soon as it arrives
flush();
}]);
// $r is the whole answer, as without stream: text, usage, cost, finish_reason, error...
Every driver streams: the Anthropic Messages API and Chat Completions through server-sent events, Bedrock through its event stream.
The returned response is the same as without stream, with the token usage of the final event, so the request log, the
costs and the budgets count a streamed call like any other. A failed profile falls over to the next one of the route only while nothing
has been streamed yet; once text went out, the error is returned and what was sent stays sent. A site driver without streaming answers
whole: the function gets the full text once.
Streaming to the browser
The answer can be shown in the browser as it is written, over plain server-sent events (an EventSource). Your page's
own POST handler prepares the call and gets a one-time ticket for it; the browser opens the stream with that ticket. The stream takes
no prompt from the browser: the ticket holds the whole call.
// in the module's POST handler (an ajax POST with the session CSRF token)
$t = llm('chat')->stream_ticket($messages, ['feature' => 'chatbox', 'max_tokens' => 800]);
// $t = ['ok' => true, 'ticket' => '...', 'url' => './?object=llm_stream&t=...', 'expires' => ...] or ['ok' => false, 'error' => ..., 'text' => ...]
return json_encode(['url' => $t['ok'] ? $t['url'] : null]);
var es = new EventSource(url), out = document.getElementById("answer");
es.addEventListener("delta", function (e) { out.textContent += JSON.parse(e.data).t; });
es.addEventListener("done", function (e) { es.close(); /* JSON: ok, profile, model, finish_reason, usage, cost, latency_ms */ });
es.addEventListener("error", function (e) { es.close(); /* e.data, when set: error_type, error */ });
es.addEventListener("busy", function () { es.close(); /* too many open streams: try again later */ });
- A ticket works once, for
STREAM_TICKET_TTLseconds (30), for the admin or user and the session that asked for it.stream_ticket()checks the session CSRF token itself (POST field orX-CSRF-Tokenheader). - Tickets and the counts of open streams are kept in Redis / Valkey (the connection settings of
redis()); without itstream_ticket()answers'error' => 'redis': answer whole instead. - The endpoint is
?object=llm_streamon the admin side and on the site side. UsetextContent(neverinnerHTML) for the pieces: they are model output. - Each open stream holds one PHP worker until the answer ends; the site caps them per admin, per user and per server.
Using answers safely
- An answer is text from outside: escape it like user input (
_prepare_html()), and never run it as code, SQL or a template. - Text you put in a prompt can steer the model (prompt injection). Keep the instructions in
system, mark user text as data, and do not let an answer decide anything that needs a permission check. - Do not send passwords, keys or personal data the provider does not need.
- Calls cost money and take seconds. Do not call a model in a loop over user input or on every page view; cache answers you reuse.
Providers and drivers
Four drivers cover the providers: anthropic (Claude Messages API), openai_compatible (Chat Completions:
OpenAI, Gemini's OpenAI endpoint, Grok, Mistral, Kimi, DeepSeek, OpenRouter, Ollama and other self-hosted servers),
azure_openai (Azure OpenAI deployments, with Azure's own auth and URLs) and bedrock (the Amazon Bedrock Converse
API, signed with AWS Signature Version 4). A site adds a provider with a class site__llm_driver_<name> (or
yf_llm_driver_<name> in its own classes/llm/) that extends yf_llm_driver and implements
chat() and models(), and stream() when the provider can stream. Tool definitions, embeddings and
images are planned for later phases.