Search by

AI layer for Taphra: providers (Anthropic, OpenAI, Ollama), AgentLoop, MCP, tool use, structured output, conversations.

1.1.0 2026-12-03 10:24 UTC

This package is auto-updated.

Last update: 2026-12-03 10:25:19 UTC


README

Documentation: https://taphra.dev/docs/packages/ai/. This package is a read-only copy of a folder in taphra/taphra; send issues and pull requests there.

AI layer for PHP: one interface over Anthropic, OpenAI, Ollama and OpenAI-compatible servers, with streaming, conversations, embeddings, structured output, a tool-use agent loop and an MCP server. It has no dependency on the Taphra framework; inside the framework it is configured from app/Config/ai.yml.

Requirements

  • PHP 8.2+
  • ext-curl, ext-json
  • taphra/container, installed with it (it holds Taphra\TaphraExceptionInterface, which every Taphra exception implements)
  • Optional: psr/simple-cache (or any PSR-16 cache) to use CachedProvider outside the framework

Installation

composer require taphra/ai

Quick start

use Taphra\Ai\AI;

AI::configure([
    'default_provider' => 'anthropic',
    'providers' => [
        'anthropic' => ['api_key' => '${ANTHROPIC_API_KEY}', 'model' => 'claude-opus-5-5'],
        'openai'    => ['api_key' => '${OPENAI_API_KEY}',    'model' => 'gpt-4o'],
        'ollama'    => ['base_url' => 'http://localhost:11434', 'model' => 'llama3'],
    ],
]);

$reply = AI::complete([['role' => 'user', 'content' => 'Hello']]);
echo $reply['content'];

$gpt = AI::provider('openai');

${ENV_VAR} placeholders are resolved from the environment when the config is read. For another config source (a secrets manager, a database) register a resolver instead:

use Taphra\Ai\AiConfig;

AiConfig::setConfigResolver(fn() => MySecrets::get('ai'));

Inside the Taphra framework the same array lives in app/Config/ai.yml and is wired at boot, so AI::configure() is not needed.

Providers

You can also build providers directly. The config keys below can be set in the constructor array (or ai.yml) and most can be overridden per call in the $options argument of complete() and stream().

use Taphra\Ai\AnthropicProvider;
use Taphra\Ai\OpenAiProvider;
use Taphra\Ai\OllamaProvider;

$anthropic = new AnthropicProvider(['api_key' => getenv('ANTHROPIC_API_KEY')]);   // model defaults to claude-opus-5-5
$gpt    = new OpenAiProvider(['api_key' => getenv('OPENAI_API_KEY'), 'model' => 'gpt-4o']);
$local  = new OllamaProvider(['model' => 'llama3']);                         // http://localhost:11434 by default
Provider Default model Config keys
AnthropicProvider claude-opus-5-5 api_key, base_url, model, max_tokens, temperature, top_p, top_k, thinking, effort (low, medium, high, xhigh, max), betas, api_version, structured_output (output_format or tool), max_continuations, voyage_api_key (embeddings)
OpenAiProvider gpt-4o api_key, base_url, model, max_tokens, temperature, top_p, effort, strict, store, api, reasoning_model
OllamaProvider llama3 base_url, model, max_tokens, temperature, think, keep_alive

All providers also take timeout (seconds, default 120), stream_timeout (default 600) and transport (see below).

Settings a model does not accept are not sent. Anthropic models from Opus 4.7 on reject temperature, top_p and top_k, so those are dropped for them. OpenAI reasoning models (the o-series, GPT-5 and later) get max_completion_tokens or max_output_tokens and the reasoning effort, and no sampling settings; earlier models get max_tokens, temperature and top_p.

OpenAI: Responses API or Chat Completions

OpenAiProvider talks to either OpenAI API:

  • the Responses API (/v1/responses) for reasoning models on api.openai.com;
  • Chat Completions (/v1/chat/completions) for earlier models and for every other base_url, since OpenAI-compatible servers implement that one.

Force one with 'api' => 'responses' or 'api' => 'chat' in the config or per call. If a model id is not recognised, set 'reasoning_model' => true or false to choose the parameter family yourself.

Any OpenAI-compatible server

$compatible = new OpenAiProvider([
    'api_key'  => getenv('MY_SERVER_KEY'),
    'base_url' => 'http://localhost:8000/v1',   // any server that implements Chat Completions
    'model'    => 'my-model',
]);

The response array

complete() returns the same shape for every provider:

$r = $provider->complete([['role' => 'user', 'content' => 'Hello!']]);

$r['content'];      // the text answer
$r['role'];         // 'assistant'
$r['tool_calls'];   // [['id' => ..., 'name' => ..., 'input' => [...]], ...]
$r['stop_reason'];  // the provider's stop reason
$r['usage'];        // token counts, see below
$r['raw'];          // the provider's own response
$r['native'];       // the provider's copy of the turn, to send back unchanged (tool loops)
$r['thinking'];     // reasoning text, when the provider returns it
$r['parsed'];       // the decoded answer, when an output schema is set

stream() yields text chunks as they arrive, and embed() returns one vector for a string or a list of vectors for a list of strings. Anthropic embeddings go through Voyage AI (voyage_api_key or the VOYAGE_API_KEY environment variable).

foreach ($provider->stream([['role' => 'user', 'content' => 'Tell me a story']]) as $chunk) {
    echo $chunk;
}

$vector = AI::provider('openai')->embed('a sentence to embed');

Usage fields

$r['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 All input tokens: uncached plus cache read plus cache write
reasoning_tokens The part of output_tokens spent on reasoning, when the provider reports it
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.

Transport

Requests go through a Taphra\Ai\Http\HttpTransport. The default is CurlTransport (TLS verification on). Pass another one in the config as 'transport' => $transport or with withTransport(), for example to add a proxy or a recording layer. FakeTransport replays queued responses without any network, which is what tests use:

use Taphra\Ai\Http\FakeTransport;

$http = (new FakeTransport())->queueJson([
    'content'     => [['type' => 'text', 'text' => 'Hi there']],
    'stop_reason' => 'end_turn',
    'usage'       => ['input_tokens' => 5, 'output_tokens' => 3],
]);

$provider = (new AnthropicProvider(['api_key' => 'test']))->withTransport($http);
$provider->complete([['role' => 'user', 'content' => 'Hello']]);   // ['content' => 'Hi there', ...]
$http->lastRequest()->json();                                       // the exact body that was sent

A rate-limit answer (HTTP 429) is retried with exponential backoff; set rate_limiting.retry_attempts (default 3) and rate_limiting.retry_base_delay_ms (default 500) in the config.

Provider modifiers

Each returns a new provider and leaves the original unchanged:

$p = $provider->withTools([$weatherTool]);          // AiTool objects or raw provider tool definitions
$p = $provider->withOutputSchema($schema);          // structured output
$p = $provider->withTransport(new FakeTransport());

A raw tool definition is sent to the provider as it is. Use it for server tools the provider runs itself, for example ['type' => 'web_search_20260209', 'name' => 'web_search'] on Anthropic or ['type' => 'web_search'] on the OpenAI Responses API.

Conversations

Multi-turn history with a pluggable store. The oldest messages are dropped when the history gets close to the token budget.

use Taphra\Ai\Conversation;

$conv = new Conversation('chat-123', 'memory');   // backends: memory, or any registered name
$conv->addSystemMessage('You are a helpful assistant.');
$conv->addUserMessage('What is the capital of France?');

$reply = $provider->complete($conv->getMessages());
$conv->addAssistantMessage($reply['content']);

$conv->addImageMessage('What is in this photo?', 'https://example.com/photo.jpg');
$conv->estimatedTokens();   // rough token count
$conv->clear();

Inside the framework the session (the default) and cache backends are registered for you. Standalone, register your own store (any ConversationStoreInterface):

Conversation::registerBackend('redis', fn() => new MyRedisConversationStore());

An unregistered backend name falls back to memory, which keeps the history for the current request only.

Prompt templates

use Taphra\Ai\Prompt;

class SummarisePrompt extends Prompt
{
    public function system(): string { return 'You are a concise technical writer. Use {style} style.'; }
    public function user(): string   { return 'Summarise: {text}'; }
}

$messages = (new SummarisePrompt())
    ->with(['style' => 'bullet-point', 'text' => $document])
    ->toMessages();   // [['role' => 'system', ...], ['role' => 'user', ...]]

Prompts can also live in files: summarise.prompt.php returns new class extends Prompt { ... } and Prompt::load('summarise') loads it. Set the folder with Prompt::setPromptsPath('/path/to/prompts'); inside the framework it is app/Prompts.

Structured output

use Taphra\Ai\StructuredOutput;

$person = StructuredOutput::from($provider)
    ->schema([
        'type'       => 'object',
        'properties' => ['name' => ['type' => 'string'], 'age' => ['type' => 'integer']],
        'required'   => ['name', 'age'],
    ])
    ->extract([['role' => 'user', 'content' => 'Extract: Alice, aged 30']]);

// ['name' => 'Alice', 'age' => 30]

The answer is decoded and checked against the schema. AiStructuredOutputException is thrown when the model declines, the answer is cut off, it is not JSON, or it does not match.

Tool-use agent loop

use Taphra\Ai\AgentLoop;
use Taphra\Ai\AiTool;

class WeatherTool extends AiTool
{
    public function name(): string        { return 'get_weather'; }
    public function description(): string { return 'Get 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)
    {
        return ['city' => $params['city'], 'temp' => 18, 'condition' => 'Cloudy'];
    }
}

$agent = new AgentLoop($provider);
$agent->registerTool(new WeatherTool());
$agent->addProviderTool(['type' => 'web_search_20260209', 'name' => 'web_search']);   // optional server tool
$agent->onToolCall(function (string $name, array $params, string $result): void {
    echo "Tool called: $name\n";
});
$agent->maxIterations(10);

$response = $agent->run('What is the weather in Paris and London?');
echo $response['content'];

The loop stops when the model makes no more tool calls and returns the last response. A tool that throws, or a tool name the model invents, is reported back to the model as an error result. AiMaxIterationsException is thrown when the loop reaches the iteration limit. history() returns the conversation so far and reset() clears it.

FallbackProvider

Tries providers in order. An AiException moves on to the next provider; any other error is thrown at once.

use Taphra\Ai\FallbackProvider;

$provider = new FallbackProvider([$anthropic, $gpt]);
// or, with configured providers: AI::fallback('anthropic', 'openai')

CachedProvider

Caches complete() answers. The key covers everything that changes the answer: the messages, the call's options, and the provider's class, model and other settings, output schema and tools (credentials are left out). stream() and embed() are not cached.

use Taphra\Ai\CachedProvider;

// Any PSR-16 cache, for example symfony/cache:
$cache    = new \Symfony\Component\Cache\Psr16Cache(new \Symfony\Component\Cache\Adapter\FilesystemAdapter());
$provider = new CachedProvider($anthropic, 3600, $cache);   // TTL in seconds; 0 keeps entries with no expiry

$provider->complete($messages);   // calls the API
$provider->complete($messages);   // served from the cache

// With configured providers:
$provider = AI::withCache('anthropic', 3600, $cache);

Without a cache argument, CachedProvider uses the Taphra framework cache when the framework is installed, and caches nothing when it is not. If the cache fails, the call goes to the provider. Errors from the provider are passed on and not cached.

Request log

Inside a Taphra app every API request adds one JSON line to app/tmp/Log/ai.log: the time, provider, URL, model, and the token usage or the error. Prompts and answers often hold personal data, so they are not written unless you ask for them:

# app/Config/ai.yml
logging:
  enabled: true                          # the usage and error log (default true; false writes nothing)
  payloads: false                        # true adds each request and answer (default false)
  redact_fields: [api_key, authorization] # keys blanked in logged payloads

Config snapshots in tests

AiConfig::snapshot() and AiConfig::restore() save and put back the loaded config and the resolver, so a test can change the config without leaking it into the next test:

$saved = AiConfig::snapshot();
AiConfig::restore(['config' => ['default_provider' => 'ollama'], 'resolver' => null]);
// ... code that reads the AI config ...
AiConfig::restore($saved);

AiConfig::reset() drops the loaded config so it is read again, and AI::reset() drops the cached provider instances.

MCP server

Expose tools, resources and prompts over the Model Context Protocol. Mark public methods with the attributes:

use Taphra\Ai\Mcp\McpTool;
use Taphra\Ai\Mcp\McpResource;
use Taphra\Ai\Mcp\McpPrompt;

class OrdersMcp
{
    #[McpTool(name: 'list_orders', description: 'List recent orders',
              inputSchema: ['type' => 'object', 'properties' => ['limit' => ['type' => 'integer']]])]
    public function listOrders(array $params): array { /* ... */ }

    #[McpResource(uri: 'orders://recent', name: 'Recent orders', description: 'The last 20 orders')]
    public function recentOrders(array $params): array { /* ... */ }

    #[McpPrompt(name: 'summarise_order', description: 'Summarise an order')]
    public function summariseOrder(array $params): array { /* ... */ }
}

Standalone, build the server yourself:

use Taphra\Ai\Mcp\McpDiscovery;
use Taphra\Ai\Mcp\McpStdioServer;

$discovery = (new McpDiscovery())->discover(new OrdersMcp());
(new McpStdioServer($discovery))->serve();   // newline-delimited JSON-RPC on stdin and stdout

For HTTP, McpHttpTransport takes the request method, headers and body and returns the response to send. It refuses every request unless you pass an authorize callback, and it accepts an Origin header only from loopback origins or the allowed_origins you list.

Inside the framework, put the methods on an AppMcpController subclass and run php taphra mcp:serve (stdio; --list prints what was discovered). php taphra make:mcp Orders --from-datastore=OrderDataStore scaffolds CRUD tools from a DataStore.

Exceptions

Class Thrown when
AiException Base class for all AI errors (HTTP errors, invalid answers, connection errors)
AiRateLimitException The provider answered HTTP 429 after all retries
AiStructuredOutputException A structured answer was declined, cut off, not JSON, or did not match the schema
AiMaxIterationsException The agent loop reached its iteration limit

AiToolNotFoundException is available for your own tool lookups; the package does not throw it.

Package layout

src/
  AI.php, AiConfig.php                     facade and config
  ProviderInterface.php, AbstractProvider.php
  AnthropicProvider.php, OpenAiProvider.php, OllamaProvider.php
  FallbackProvider.php, CachedProvider.php
  AgentLoop.php, AiTool.php, ToolRegistry.php, Message.php, Usage.php
  Conversation.php, ConversationStoreInterface.php, MemoryConversationStore.php
  Prompt.php, StructuredOutput.php
  Ai*Exception.php
  Http/      HttpTransport, CurlTransport, FakeTransport, HttpRequest, HttpResponse
  Schema/    JSON Schema helpers and the structured answer check
  Stream/    SSE and NDJSON stream parsers
  Wire/      per-provider message and model rules
  Mcp/       attributes, discovery, McpServer, stdio and HTTP transports, session stores