adachsoft / ai-integration-anthropic
Anthropic Claude tool-calling SPI adapter for adachsoft/ai-integration.
Package info
gitlab.com/a.adach/ai-integration-anthropic
pkg:composer/adachsoft/ai-integration-anthropic
Requires
- php: >=8.3
- adachsoft/ai-conversation-model: ^0.2
- adachsoft/ai-integration: ^0.10
- adachsoft/http-transport: ^0.2
- adachsoft/model-pricing-contracts: ^0.2 || ^0.4.0
- guzzlehttp/guzzle: ^7.0 || ^8.0
Requires (Dev)
- adachsoft/ai-integration-tester: ^0.5.2
- adachsoft/php-code-style: ^0.7.2
- friendsofphp/php-cs-fixer: ^3.94
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^13.0
- rector/rector: ^2.3
- symplify/phpstan-rules: ^14.9
- vlucas/phpdotenv: ^5.6
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Integration of Anthropic Claude (tool calling) with the adachsoft/ai-integration library.
Requirements
- PHP
>= 8.3 guzzlehttp/guzzle^7.0 || ^8.0adachsoft/ai-integration^0.10adachsoft/ai-conversation-model^0.2adachsoft/model-pricing-contracts^0.2
Installation
composer require adachsoft/ai-integration-anthropic
Basic usage
The example model is claude-sonnet-5-5; provide the selected model through the request's modelId field.
Wire the Anthropic SPI provider into the tool-calling facade:
use AdachSoft\AiIntegration\PublicApi\Builder\ToolCallingChatFacadeBuilder;
use AdachSoft\AiIntegrationAnthropic\AnthropicToolCallingChatSpiFactory;
use RuntimeException;
$apiKey = getenv('ANTHROPIC_API_KEY');
if (!is_string($apiKey) || $apiKey === '') {
throw new RuntimeException('ANTHROPIC_API_KEY is required.');
}
$anthropicSpi = (new AnthropicToolCallingChatSpiFactory())->create($apiKey);
$facade = ToolCallingChatFacadeBuilder::create()
->withSpiProvider('anthropic', $anthropicSpi)
->build();
Shared conversation model
The adapter consumes provider-neutral messages and tools from adachsoft/ai-conversation-model and returns a ChatCompletionDto. An Anthropic response maps to one ChatChoiceDto; its finishReason contains the provider stop reason, and its content, toolCalls, and metadata remain attached to that choice.
Tool calls
Anthropic tool_use blocks are mapped to shared-model tool calls. Parallel tool calls remain in the same assistant choice. Matching tool results are mapped back to Anthropic tool_result blocks for the next request, preserving their call IDs and order.
Thinking blocks
Raw thinking and redacted_thinking blocks are preserved in choice metadata under anthropic_raw_thinking_blocks. When storing an assistant turn for a follow-up tool request, copy that value unchanged into the assistant message metadata:
$assistantMessage = ChatMessageDto::assistant(
$messageId,
$createdAt,
$choice->content,
$choice->toolCalls,
[
'anthropic_raw_thinking_blocks' => $choice->metadata['anthropic_raw_thinking_blocks'] ?? [],
],
);
Images and PDFs
User and tool-result content supports images and PDFs supplied as Base64 data or URLs. FileId content and audio are rejected; video and other unsupported media types are also rejected.
System message placement
System messages can be placed in Anthropic's top-level system field or inline with the conversation. Configure the behavior per request with ai_integration-system_messages_strategy:
all_top_level(default) - send all system messages in the top-levelsystemfield.leading_top_level- send only the initial consecutive system messages in the top-levelsystemfield; later system messages are included inline.
Initial system messages are always sent in the top-level system field; they are never converted to inline <system>...</system> user content.
Inline system messages are wrapped in <system>...</system> text blocks. System content must be text or a list of text blocks; other block types are rejected.
Set the strategy in the request parameters:
$parameters = [
'ai_integration-system_messages_strategy' => 'leading_top_level',
];
Anthropic requires an explicit instruction to treat inline system content as operator instructions. The adapter appends this instruction to the top-level system content whenever the selected strategy can emit inline system messages (leading_top_level). It is disabled by default for all_top_level, which does not emit inline system messages. Custom strategies declare this capability through SystemMessagesStrategyInterface::canProduceInlineMessages().
The instruction can be controlled per request:
ai_integration-system_messages_inline_instructionaccepts exactlyonoroff(default: enabled when an inline-capable strategy is selected).ai_integration-system_messages_inline_instruction_textsupplies non-empty custom text without trimming or rewriting it; it cannot be combined withoff.
The default instruction marks <system>...</system> as authoritative operator instructions. The adapter appends it after regular top-level system blocks, keeping it as the trailing block for stable cache prefixes. Inline system messages continue to be wrapped in <system>...</system> blocks.
Transport modes
AnthropicToolCallingChatSpiFactory::create() supports two transport modes:
non_streaming(default) - legacy buffered mode using classic non-streaming HTTP response read.streaming- request is sent as SSE stream and reconstructed back to the Anthropic JSON response format.
Factory parameters (transportMode, streamingPerChunkTimeoutSeconds) define application-level defaults.
Per-request parameters have higher priority and can override these defaults:
ai_integration-transport_mode(non_streamingorstreaming)ai_integration-streaming_per_chunk_timeout_seconds(positive integer, only for effectivestreamingmode)
Example request-level override:
$request = new ToolCallingChatRequestDto(
messages: $messages,
tools: $tools,
providerId: 'anthropic',
parameters: [
'ai_integration-transport_mode' => 'streaming',
'ai_integration-streaming_per_chunk_timeout_seconds' => 45,
],
metadata: [],
modelId: 'claude-sonnet-5-5',
);
ToolCallingContext::$timeoutSeconds keeps the same SPI meaning in both modes: it is the total request timeout.
In streaming mode, idle timeout between chunks is configured separately via ai_integration-streaming_per_chunk_timeout_seconds (or factory default).
Streaming mode requires allow_url_fopen=1. If it is disabled, the adapter throws a fail-fast SpiException with guidance to enable allow_url_fopen or switch to non_streaming.
With default non_streaming, long-running generations may again be exposed to idle connection drops in some environments.
When this matters, enable streaming explicitly per request.
Anthropic cache configuration
This package exposes explicit cache configuration via ToolCallingChatRequestDto::$parameters.
All cache-related keys are prefixed with ai_integration-. The adapter emits Anthropic cache_control markers; the existing cache strategies and selection semantics are unchanged.
Supported cache sections:
ai_integration-cache_system– cache for the system prompt (off,5min,1hour).ai_integration-cache_tools– cache for tool definitions (off,5min,1hour).ai_integration-cache_messages– cache for conversation messages (off,5min,1hour).ai_integration-cache_automatic– Anthropic automatic cache mode (off,5min,1hour).
When ai_integration-cache_messages is enabled (5min or 1hour), you can select strategy with:
ai_integration-cache_messages_strategy– supported strategies:offfirst_userlast_userthreshold_tokens
Additional parameters for threshold_tokens strategy:
ai_integration-cache_messages_threshold_tokens– positive integer threshold (default5000).ai_integration-cache_messages_last_cached_message_id– optional last cached user message identifier.
The cache layer is opt-in and non-intrusive: if you do not provide any ai_integration-* keys,
cache behaviour is disabled.
ai_integration-cache_automatic is mutually exclusive with explicit cache TTL keys (cache_system,
cache_tools, cache_messages). If both modes are enabled, configuration validation fails before request execution.
Response metadata
Cache-aware responses may include these metadata keys:
raw_responseraw_usagecache_breakpoint_message_id
The cache_breakpoint_message_id value is taken from the SPI user message metadata (message_id, falling back to id). Message identifiers are used internally only and are never sent to Anthropic as part of message objects.
Billing token counters are exposed through tokenUsage->details, not response metadata.
Token usage details
tokenUsage->details contains the original usage object returned by Anthropic, including nested objects; the parser does not flatten or rename usage fields. Typical token and cache fields are:
| Usage field | Meaning |
|---|---|
input_tokens | Input tokens not served from cache |
output_tokens | Output tokens, including thinking tokens |
cache_read_input_tokens | Input tokens read from cache |
cache_creation_input_tokens | Aggregate input tokens written to cache |
cache_creation.ephemeral_5m_input_tokens | Input tokens written with a five-minute TTL |
cache_creation.ephemeral_1h_input_tokens | Input tokens written with a one-hour TTL |
For compatibility with already flattened usage details, the normalizer also accepts cache_creation_ephemeral_5m_input_tokens and cache_creation_ephemeral_1h_input_tokens. The raw usage object can contain additional provider fields; non-zero numeric fields not recognized by the normalizer produce a warning so a consumer can mark its cost estimate incomplete.
totalTokens includes uncached input, cache-write tokens, cache-read tokens and output tokens because these input categories are mutually exclusive in the Anthropic API.
Request cost
AnthropicUsageNormalizer implements UsageNormalizerInterface and converts Anthropic usage into disjoint billable token items and pricing context. It validates cache-write TTL counters, reports unknown non-zero numeric usage fields, and preserves unknown service tiers with a warning. The adapter depends on adachsoft/model-pricing-contracts; it does not estimate prices or depend on the cost integration package.
Pricing conditions
The pricing context includes the service tier and adds speed=fast or inference_geo=us when Anthropic reports those values. speed=standard, inference_geo=global, and missing fields add no extra conditions; other values produce warnings. output_tokens_details.thinking_tokens is informational because its tokens are already included in output_tokens, so they are not counted twice.
In an application using adachsoft/ai-integration-cost ^0.3, add the provider normalizer to the usage-normalizer registry:
use AdachSoft\AiIntegrationAnthropic\Cost\AnthropicUsageNormalizer;
$usageNormalizers = $usageNormalizers->with(
'anthropic',
new AnthropicUsageNormalizer(),
);
A non-empty warning list means normalized usage may be incomplete and the resulting cost should be marked incomplete.
For full details (TTL semantics, beta headers, strategy behaviour and payload rules), see:
docs/CACHE_STRATEGIES.mddocs/architecture.md
Migration from 0.11 (BREAKING)
- Remove the
AnthropicUsageKindMapandUsageKindMapVoregistration; registerAnthropicUsageNormalizerwith the usage-normalizer registry fromadachsoft/ai-integration-cost^0.3instead. - This adapter no longer depends on
adachsoft/ai-integration-cost. The application may use that package to estimate costs from the sharedadachsoft/model-pricing-contractscontracts.
Migration from 0.10.x (BREAKING)
This update adopts adachsoft/ai-integration ^0.10 and the shared ai-conversation-model ^0.2 DTOs. It is not source-compatible with the older request and response DTO shape.
- Replace legacy message DTOs with
AdachSoft\AiConversationModel\Message\ChatMessageDtoandChatMessageDtoCollection, using typed content and tool DTOs. - Construct
ToolCallingChatRequestDtowithproviderId,parameters, and the requiredmetadatafield; usemodelIdto select the model. - Read completion text, tool calls,
finishReason, and provider metadata fromChatCompletionDto->choices[0]instead of legacy response fields. - Use
AdachSoft\AiConversationModel\Cost\CostDto(total,currency, anddetails) withadachsoft/ai-integration-cost^0.2. - Do not send deprecated
temperaturevalues for models that reject them; the Anthropic conformance profile omitstemperature.
Tests
The default phpunit.xml suite is unit; running it does not call the paid Anthropic API. The explicit production suite makes live, billable API requests. Provider conformance tests use the adachsoft/ai-integration-tester 0.5.2 profile.
Set ANTHROPIC_API_KEY to run production tests; ANTHROPIC_MODEL optionally overrides the conformance profile's default model (claude-haiku-5-5).
# Default unit suite
vendor/bin/phpunit
# Unit suite explicitly
vendor/bin/phpunit --testsuite unit
# Paid production API suite
ANTHROPIC_API_KEY=... ANTHROPIC_MODEL=claude-haiku-5-5 vendor/bin/phpunit --testsuite production