AI
AI
Taphra's AI layer talks to Anthropic, OpenAI, OpenAI-compatible servers and Ollama through one interface: completions, token streaming, structured output, tool use with an agent loop, conversations, prompt templates and embeddings. It lives in the bundled taphra/ai package (Taphra\Ai). This page covers it inside an app; the package README covers using it without the framework.
Every PHP example below runs as written, in order, with the network replaced by recorded provider responses (see Testing).
Contents
#- Configuration
- A first call
- Providers
- Streaming
- Structured output
- Tools and agents
- Usage and prompt caching
- Conversations
- Prompt templates
- Embeddings
- Fallback and caching
- Errors
- Logging
- Testing
Configuration
#Providers are configured in app/Config/ai.yml:
default_provider: anthropic
providers:
anthropic:
api_key: "${ANTHROPIC_API_KEY}"
model: claude-opus-5-5
max_tokens: 4096
openai:
api_key: "${OPENAI_API_KEY}"
model: gpt-5.2
ollama:
base_url: http://localhost:11434
model: llama3
vllm: # an OpenAI-compatible server, see below
base_url: http://localhost:8000/v1
api_key: "${VLLM_API_KEY}"
model: qwen3${NAME} placeholders are replaced with the environment variable of that name each time a value is read, so keys stay out of the file and out of the config cache. Taphra does not read a .env file at runtime: set the variables in your shell, your web server or PHP-FPM pool, or your container. Like other config files, ai.yml can be split into all:, dev:, stg: and prod: sections (see configuration).
Provider keys, all optional except the API key of a hosted provider:
| Provider | Default model | Keys |
|---|---|---|
anthropic |
claude-opus-5-5 |
api_key, base_url, model, max_tokens (default 16000), temperature, top_p, top_k, thinking, effort, betas, api_version, structured_output, max_continuations, voyage_api_key |
openai |
gpt-4o |
api_key, base_url, model, max_tokens (default 4096), temperature, top_p, effort, strict, store, api, reasoning_model |
ollama |
llama3 |
base_url (default http://localhost:11434), model, max_tokens (default 4096), temperature, think, keep_alive |
Every provider also takes timeout (seconds, default 120) and stream_timeout (default 600). Most keys can be overridden per call in the $options array of complete() and stream().
Other top-level settings:
| Key | Default | Meaning |
|---|---|---|
agent.max_iterations |
10 | Model calls an agent run may make |
agent.timeout_seconds |
120 | Request timeout when a provider sets no timeout |
rate_limiting.retry_attempts |
3 | Attempts for a request answered with HTTP 429 |
rate_limiting.retry_base_delay_ms |
500 | First retry delay, doubled for each later attempt |
logging.enabled |
true | Write a line per request to app/tmp/Log/ai.log: usage or error, no prompts (see Logging) |
logging.payloads |
false | Also write each request and answer (the prompts and replies) to that log |
logging.redact_fields |
[api_key, authorization] |
Fields replaced with [REDACTED] in logged requests and answers |
A first call
#AI::complete() sends a list of messages to the default provider and returns the answer:
use Taphra\Ai\AI;
$reply = AI::complete([
['role' => 'system', 'content' => 'Answer in one sentence.'],
['role' => 'user', 'content' => 'What is a DataStore in Taphra?'],
]);
echo $reply['content'], "\n";
echo $reply['stop_reason'], ', ', $reply['usage']['output_tokens'], " output tokens\n";Every provider returns the same array:
| Key | Value |
|---|---|
content |
The text answer |
role |
assistant |
tool_calls |
Tool calls the model made: [['id' => ..., 'name' => ..., 'input' => [...]], ...] |
stop_reason |
The provider's stop reason (end_turn, stop, tool_use, max_tokens, ...) |
usage |
Token counts, see Usage |
thinking |
The model's reasoning text, when the provider returns one |
parsed |
The decoded answer, when an output schema is set |
native |
Anthropic and the OpenAI Responses API: the provider's own copy of the turn, sent back unchanged in tool loops |
raw |
The provider's response as decoded JSON |
Messages use one provider-neutral format: system, user and assistant roles with string content, plus tool messages for tool results. A user message can also carry a list of blocks, such as ['type' => 'text', 'text' => ...] and ['type' => 'image', 'url' => ...] or ['type' => 'image', 'base64' => ..., 'mime' => 'image/png']. Each provider converts the list to its own wire format, so a history built with one provider can be sent to another. Ollama takes images as base64 only.
Providers
#AI::provider() returns the default provider and AI::provider('openai') a named one; each is built once and kept for the life of the PHP process. The second argument of complete() overrides settings for one call:
use Taphra\Ai\AI;
$reply = AI::provider('openai')->complete(
[['role' => 'user', 'content' => 'Name three PHP array functions.']],
['max_tokens' => 300, 'effort' => 'low'],
);
echo $reply['content'], "\n";Settings a model does not accept are left out of the request:
- Anthropic.
temperature,top_pandtop_kare sent only to Anthropic models up to version 4.6; later models reject them.effort(low,medium,high,xhigh,max) is sent asoutput_config.effort.thinking, for example['type' => 'adaptive'], is sent as written;betasis a list ofanthropic-betavalues. - OpenAI. Reasoning models (the o-series and GPT-5 and later) are called through the Responses API (
/v1/responses) withmax_output_tokensand the reasoning effort, and without sampling settings. Earlier models such asgpt-4ouse Chat Completions (/v1/chat/completions) withmax_tokens,temperatureandtop_p. Force one API with'api' => 'responses'or'api' => 'chat'; for a model id the provider does not recognise, set'reasoning_model' => trueorfalse. - Ollama. Runs local models over
/api/chat.thinkandkeep_aliveare passed through.
OpenAI-compatible servers
#AI::provider() knows the names anthropic, openai and ollama. For a server that implements the OpenAI Chat Completions API (vLLM, LM Studio, a hosted vendor), either point the openai section's base_url at it, or give it its own section and build the provider from it. Any base_url other than api.openai.com uses Chat Completions:
use Taphra\Ai\AiConfig;
use Taphra\Ai\OpenAiProvider;
$local = new OpenAiProvider(AiConfig::provider('vllm')); // providers.vllm in ai.yml
echo $local->complete([['role' => 'user', 'content' => 'Ping?']])['content'], "\n";Streaming
#stream() returns a generator that yields the text as the provider sends it: Server-Sent Events for Anthropic and OpenAI, NDJSON for Ollama. The same loop works for each provider:
use Taphra\Ai\AI;
foreach (['anthropic', 'openai', 'ollama'] as $name) {
echo $name, ': ';
foreach (AI::provider($name)->stream([['role' => 'user', 'content' => 'Say hello.']]) as $chunk) {
echo $chunk;
}
echo "\n";
}stream() yields text only; use complete() when you need tool calls, usage or structured output. An error event in the stream throws an AiException.
Streaming to the browser
#A controller's protected sse() helper sends a generator (or a closure that returns one) as text/event-stream: one data: event per chunk, a chunk with line breaks split over several data: lines, and a final data: [DONE]. It turns off output buffering, flushes after each chunk, stops when the client disconnects, and ends the request when the stream is done.
// app/Controllers/ChatController.php
namespace App\Controllers;
use Taphra\Ai\AI;
use Taphra\Request;
class ChatController extends AppController
{
public function stream(): void
{
$question = Request::str('q');
$this->sse(AI::stream([['role' => 'user', 'content' => $question]]));
}
}GET /chat/stream?q=hello then answers:
data: Hello
data: there
data: friend
data: [DONE]and the browser reads it with EventSource, which joins the data: lines of one event with a line break:
const source = new EventSource('/chat/stream?q=' + encodeURIComponent(question));
source.onmessage = (event) => {
if (event.data === '[DONE]') { source.close(); return; }
output.textContent += event.data;
};See routing and controllers for routes and the other response helpers.
Structured output
#StructuredOutput asks for an answer that matches a JSON Schema, decodes it and checks it against the schema:
use Taphra\Ai\AI;
use Taphra\Ai\StructuredOutput;
$invoice = StructuredOutput::from(AI::provider())
->schema([
'type' => 'object',
'properties' => [
'customer' => ['type' => 'string'],
'total' => ['type' => 'number'],
'paid' => ['type' => 'boolean'],
],
'required' => ['customer', 'total', 'paid'],
])
->extract([['role' => 'user', 'content' => 'Invoice for Ada Lovelace, 120.50 EUR, settled on 3 May.']]);
echo json_encode($invoice), "\n"; // {"customer":"Ada Lovelace","total":120.5,"paid":true}How each provider asks for it:
| Provider | Request |
|---|---|
| Anthropic | output_config.format with the schema (objects closed with additionalProperties: false), for Anthropic models from 4.1 on. Earlier models get the schema as a tool they must call; force either with structured_output: output_format or tool. |
| OpenAI | response_format (Chat Completions) or text.format (Responses) of type json_schema. Strict mode is on when the schema meets its rules; set strict: true or false to choose. |
| Ollama | The schema as format, with temperature 0 unless you set one |
The answer is always checked here too. When the model declines, the answer is cut at the token limit, it is not JSON, or it does not match, extract() throws AiStructuredOutputException:
use Taphra\Ai\AI;
use Taphra\Ai\AiStructuredOutputException;
use Taphra\Ai\StructuredOutput;
try {
StructuredOutput::from(AI::provider())
->schema(['type' => 'object', 'properties' => ['age' => ['type' => 'integer']], 'required' => ['age']])
->extract([['role' => 'user', 'content' => 'How old is the Eiffel Tower?']]);
} catch (AiStructuredOutputException $e) {
echo $e->getMessage(), "\n";
}withOutputSchema($schema) does the same on any provider and puts the decoded answer in $reply['parsed'].
Tools and agents
#A tool is a class your code runs when the model asks for it. php taphra make:tool Weather writes app/AiTools/WeatherTool.php; its name() is the snake_case form of the class name (weather, web_search):
<?php
namespace App\AiTools;
use Taphra\Ai\AiTool;
class WeatherTool extends AiTool
{
public function name(): string
{
return 'get_weather';
}
public function description(): string
{
return 'Current weather for a city.';
}
public function inputSchema(): array
{
return [
'type' => 'object',
'properties' => ['city' => ['type' => 'string', 'description' => 'City name']],
'required' => ['city'],
];
}
public function execute(array $params)
{
$city = trim((string) ($params['city'] ?? ''));
if ($city === '') {
throw new \InvalidArgumentException('city is required');
}
return ['city' => $city, 'temp_c' => 18, 'sky' => 'cloudy'];
}
}AgentLoop sends the messages with the tools, runs each tool the model calls, sends the results back, and repeats until the model answers without calling a tool:
use App\AiTools\WeatherTool;
use Taphra\Ai\AI;
$agent = AI::agent() // the default provider; AI::agent('openai') for another
->registerTool(new WeatherTool())
->maxIterations(5)
->onToolCall(function (string $name, array $params, string $result): void {
echo "called $name(", json_encode($params), ")\n";
});
$answer = $agent->run('Should I take an umbrella in Paris today?');
echo $answer['content'], "\n";What the loop does:
- The tool's return value is sent to the model as JSON (a string as it is). An exception in
execute(), or a tool name the model made up, goes back to the model as an error result, so it can correct itself. - The loop does not check the model's arguments against
inputSchema(). Validate them inexecute(), as above, and treat them like any other user input. - When the limit of model calls is reached,
run()throwsAiMaxIterationsException. history()returns the conversation so far, in the provider-neutral format, and the nextrun()continues it;reset()clears it.useRegisteredTools()loadsapp/AiTools/*.phpand registers every concreteAiToolclass declared there (or in theApp\AiToolsnamespace) whose constructor takes no required arguments. Register any other tool withregisterTool().
The history keeps each assistant turn in the provider's own form as well (native): Anthropic thinking blocks with their signatures, and OpenAI reasoning items, which those APIs require back unchanged during tool use. Another provider reading the same history uses the plain content and tool_calls.
Without the loop, withTools([...]) returns a provider that offers the tools, and the calls arrive in $reply['tool_calls'] for you to handle.
Thinking
#Ask Anthropic for extended thinking with the thinking option (or key); the reasoning text arrives in thinking, next to the answer. OpenAI reasoning summaries and Ollama's think output use the same key.
use Taphra\Ai\AI;
$reply = AI::complete(
[['role' => 'user', 'content' => 'Is 1001 a prime number?']],
['thinking' => ['type' => 'adaptive'], 'effort' => 'high'],
);
echo $reply['thinking'], "\n", $reply['content'], "\n";Server tools
#A server tool runs at the provider, such as Anthropic's or OpenAI's web search. Pass its raw definition; it is sent to the provider as written:
use Taphra\Ai\AI;
$reply = AI::agent()
->addProviderTool(['type' => 'web_search_20260209', 'name' => 'web_search', 'max_uses' => 3])
->run('What is the latest PHP release?');
echo $reply['content'], "\n";
echo json_encode($reply['usage']['server_tool_use']), "\n"; // {"web_search_requests":1}On the OpenAI Responses API the definition is ['type' => 'web_search']. When Anthropic pauses a long server-tool turn (pause_turn), the provider resumes it, up to max_continuations times (default 5), and adds up the usage.
Usage and prompt caching
#$reply['usage'] has the same keys for every provider:
| Key | Meaning |
|---|---|
input_tokens |
Input tokens as the provider reports them (Anthropic counts only uncached input here; OpenAI and Ollama count all input) |
output_tokens |
Output tokens, reasoning included |
cache_read_tokens |
Input tokens served from the prompt cache |
cache_write_tokens |
Input tokens written to the prompt cache |
uncached_input_tokens |
Input tokens billed at the base input rate |
total_input_tokens |
Uncached plus cache read plus cache write |
reasoning_tokens |
The part of output_tokens spent on reasoning, when reported |
server_tool_use |
Server tool calls by kind, for example ['web_search_requests' => 2] |
To price a call, multiply uncached_input_tokens, cache_read_tokens, cache_write_tokens and output_tokens by their rates and add the server tool calls. With Anthropic, a text block can carry cache_control to mark a long, repeated prefix for the prompt cache; extra keys on text blocks are sent as written:
use Taphra\Ai\AI;
$manual = str_repeat('Section 4.2: refunds are issued within 14 days. ', 200);
$reply = AI::complete([
['role' => 'user', 'content' => [
['type' => 'text', 'text' => $manual, 'cache_control' => ['type' => 'ephemeral']],
['type' => 'text', 'text' => 'How long do refunds take?'],
]],
]);
printf("uncached %d, cache read %d, total input %d\n",
$reply['usage']['uncached_input_tokens'],
$reply['usage']['cache_read_tokens'],
$reply['usage']['total_input_tokens']);Conversations
#A Conversation keeps a message history between requests:
use Taphra\Ai\AI;
$chat = AI::conversation('support-42', 'cache'); // backends: session (the default), cache, memory
$chat->addSystemMessage('You are the support assistant of an online shop.');
$chat->addUserMessage('Where is my order?');
$reply = AI::complete($chat->getMessages());
$chat->addAssistantMessage($reply['content']);
echo $chat->count(), " messages, about ", $chat->estimatedTokens(), " tokens\n";| Backend | Where the history lives |
|---|---|
session |
The user's session (started on first use); the default of AI::conversation() |
cache |
The app cache (see cache), for one hour |
memory |
The current request only |
When a new user message would take the history past its token budget (100000 estimated tokens, about four characters each; set another as the third argument of new Conversation($key, $backend, $maxTokens)), the oldest messages are dropped. The system message is kept. addImageMessage($text, $images) adds a user message with image URLs or base64 images, and clear() empties the history. Register another store with Conversation::registerBackend('name', fn() => new MyStore()), where MyStore implements ConversationStoreInterface (get() and put()).
The key names the history: build it from something the user cannot choose freely, such as their user id or session id, so one user cannot read another's conversation.
Prompt templates
#A prompt template is a file in app/Prompts/ that returns a Prompt subclass. php taphra make:prompt summarise writes a stub with a {topic} placeholder to replace.
<?php
use Taphra\Ai\Prompt;
return new class extends Prompt {
public function system(): string
{
return 'You write {style} summaries for busy readers.';
}
public function user(): string
{
return "Summarise this text:\n\n{text}";
}
};use Taphra\Ai\Prompt;
$messages = Prompt::load('summarise')
->with(['style' => 'three-bullet', 'text' => 'Taphra 1.0 ships today.'])
->toMessages();
echo $messages[0]['content'], "\n"; // You write three-bullet summaries for busy readers.{name} placeholders are replaced with the values you pass, as they are; a placeholder without a value stays in the text. render() returns the user prompt alone. Values from users go into the prompt unchanged, so the model sees anything they wrote, instructions included.
Embeddings
#embed() returns a vector for a string, or a list of vectors for a list of strings:
use Taphra\Ai\AI;
$vector = AI::provider('openai')->embed('A small, explicit PHP framework.');
echo count($vector), " dimensions\n";OpenAI uses text-embedding-3-small unless you pass ['model' => ...]. Ollama calls /api/embeddings once per string with the configured model. Anthropic has no embeddings API: embed() on the Anthropic provider calls Voyage AI (voyage-3 by default) with voyage_api_key or the VOYAGE_API_KEY environment variable.
Fallback and caching
#AI::fallback() tries providers in order. An AiException (an HTTP error, a timeout, an invalid answer) moves on to the next provider; any other exception is thrown at once.
use Taphra\Ai\AI;
$reply = AI::fallback('anthropic', 'openai')
->complete([['role' => 'user', 'content' => 'Summarise HTTP 529 in five words.']]);
echo $reply['content'], "\n"; // answered by openai: the first provider was overloadedstream() falls back too, but only before the first chunk: once text has reached the caller, an error is thrown rather than starting again with another provider.
AI::withCache() keeps complete() answers in the app cache, keyed on the messages, the options and the provider name:
use Taphra\Ai\AI;
$cached = AI::withCache('anthropic', 600); // TTL in seconds; 0 keeps answers until the cache is cleared
$question = [['role' => 'user', 'content' => 'Which HTTP status means Too Many Requests?']];
$first = $cached->complete($question); // calls the API
$second = $cached->complete($question); // served from the cache
echo $second['content'], "\n";stream() and embed() are not cached, errors are not cached, and a cache failure sends the call to the provider. The key does not include an output schema or a tool list set on the provider, so use the cache for plain completions.
Errors
#| Exception | Thrown when |
|---|---|
AiException |
Base class: an HTTP error answer (with the provider's message), a connection error or timeout, an invalid response, an error event in a stream, an unknown provider name |
AiRateLimitException |
HTTP 429 after every retry (rate_limiting.retry_attempts) |
AiStructuredOutputException |
A structured answer was declined, cut off, not JSON, or did not match the schema |
AiMaxIterationsException |
An agent run reached its iteration limit |
All are in Taphra\Ai. A rate-limited complete() is retried with exponential backoff; streamed requests are not retried.
Logging
#With logging.enabled on (the default), each request adds one line to app/tmp/Log/ai.log: the time, the provider, the URL, the model, and the token usage, or the error when the request failed. Prompts and answers often hold personal data, so they are written only when you turn on logging.payloads (with the logging.redact_fields keys replaced):
# app/Config/ai.yml
logging:
enabled: true # false writes nothing
payloads: true # add each request and answer (off by default)Testing
#Providers send their requests through an HTTP transport. FakeTransport (Taphra\Ai\Http) replays queued responses instead of calling the network and records every request, so a test can check both the answer and the exact body that was sent. AiConfig::snapshot() and AiConfig::restore() swap the configuration for the test and put it back afterwards; AI::reset() drops the provider instances built from the old one:
use Taphra\Ai\AI;
use Taphra\Ai\AiConfig;
use Taphra\Ai\Http\FakeTransport;
$fake = (new FakeTransport())->queueJson([
'content' => [['type' => 'text', 'text' => 'Bonjour']],
'stop_reason' => 'end_turn',
'usage' => ['input_tokens' => 9, 'output_tokens' => 2],
]);
$saved = AiConfig::snapshot();
AiConfig::restore(['config' => [
'default_provider' => 'anthropic',
'providers' => ['anthropic' => ['api_key' => 'test', 'transport' => $fake]],
], 'resolver' => null]);
AI::reset();
$reply = AI::complete([['role' => 'user', 'content' => 'Say hello in French.']]);
$sent = $fake->lastRequest()->json();
echo $reply['content'], ' / ', $sent['messages'][0]['content'], "\n"; // Bonjour / Say hello in French.
AiConfig::restore($saved);
AI::reset();queueStream([...chunks]) replays a streamed response chunk by chunk, queueJson($body, 429) an error status, and queueConnectionError() a failed connection. requests() lists every request sent and pending() counts the responses not used yet. In an app, a provider can also take any HttpTransport as 'transport' => $transport in its config, or through $provider->withTransport($transport), for example to add a proxy or record traffic.