AnthropicProvider

Use Anthropic Claude with native API support – structured output is guaranteed, never falling back to free-form prose.

Anthropic uses its own wire format, and the provider hides it: call sites use the same messages interface as every other provider, and retry is delegated to the official anthropic-ai/sdk.

Construction

public function __construct(
    ProviderConfig $config,
    AnthropicClient|null $client = null,
)
config
ProviderConfig
Resolved per-provider configuration.
client
\\Anthropic\\Client | null
Inject a custom Anthropic client. Defaults to the SDK client with the provider's timeout applied.

Methods

generateObject

Structured output is a forced tool call, so the response always matches your schema.

$provider->generateObject(
    messages: [
        ['role' => 'system', 'content' => 'Return JSON only.'],
        ['role' => 'user', 'content' => 'Pick three colors.'],
    ],
    schema: [
        'type' => 'object',
        'properties' => ['colors' => ['type' => 'array', 'items' => ['type' => 'string']]],
        'required' => ['colors'],
    ],
);

Throws ProviderException on any upstream error (with httpCode set to the status), or when the response contains no tool_use block.

generateText

Sends a plain message request and returns the response text.

$provider->generateText(
    messages: [
        ['role' => 'user', 'content' => 'Describe three primary colors.'],
    ],
);

Throws ProviderException on any upstream error, or when the response contains no text block.

Provider-Specific Options

Anything in providers.anthropic that isn't apiKey, model, baseUrl, completionModel, api, options, or timeout is forwarded with every request:

'providers' => [
    'anthropic' => [
        'apiKey' => 'your-anthropic-api-key',
        'maxTokens' => 8000,
        'thinking' => ['type' => 'enabled', 'budgetTokens' => 4000],
    ],
],
Anthropic requires max_tokens on every request. The provider defaults to 32000 – override via providers.anthropic.maxTokens when you need a tighter cap.

Option names follow the SDK's camelCase parameters (maxTokens, topP); a snake_case key such as max_tokens is rejected.