class AnthropicGateway implements Gateway, StepTextGateway

Traits

Methods

array
buildTextRequestBody(Provider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options)

Build the request body for the Anthropic Messages API.

array
applyPromptCacheBreakpoints(array $body, TextGenerationOptions|null $options)

Stamp the requested cache breakpoints onto the final request body.

void
ensureValidPromptCacheOrder(array $body, TextGenerationOptions|null $options)

Ensure longer-lived cache breakpoints precede shorter-lived breakpoints.

array
cacheControl(string|null $ttl)

Build the cache control block for the given TTL.

bool
supportsSamplingParameters(string $model)

Determine if the model accepts temperature and top_p.

array
resolveToolChoice(array|null $schema, array $tools, array $providerOptions, ToolChoice|null $toolChoice = null)

Determine the tool_choice strategy for the request.

bool
supportsNativeStructuredOutput(Provider $provider)

Determine if the provider supports native structured output via output_config.

array
buildStructuredOutputTool(array $schema)

Build the synthetic tool definition for structured output.

createClient(string $baseUrl, array $headers = [], array $configuredHeaders = [], int|null $timeout = 60, bool $throw = true)

Create an HTTP client with the provider's request options.

string
httpConnection(Provider $provider)

Select a boot-registered connection without retaining dynamic provider names.

client(Provider $provider, int|null $timeout = null)

Get an HTTP client for the Anthropic API.

string
baseUrl(Provider $provider)

Get the base URL for the Anthropic API.

array
pausedContent(array $messages)

Get the content of the paused steps the turn being continued is made of.

processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody, array $pausedContent = [])

Process a single Anthropic streaming turn and yield Hypervel stream events.

string
generateEventId()

Generate a lowercase UUID v7 for use as a stream event ID.

array
mapAttachments(Collection $attachments)

Map the given Hypervel attachments to Anthropic content blocks.

array
documentSource(string|null $mimeType, callable $rawResolver, callable $base64Resolver)

Build the Anthropic document source block for the given mime type.

array
remoteDocumentSource(RemoteDocument $document)

Build the Anthropic document source block for the given remote document.

string|null
normalizeMimeType(string|null $mimeType)

Strip any parameters from the given mime type.

bool
isImage(UploadedFile $attachment)

Determine if the given uploaded file is an image.

array
mapMessages(array $messages)

Map the given Hypervel messages to Anthropic Messages API format.

void
mapUserMessage(UserMessage|Message $message, array $mapped)

Map a user message to Anthropic format.

void
mapAssistantMessage(AssistantMessage|Message $message, array $mapped)

Map an assistant message to Anthropic format.

void
mapToolResultMessage(ToolResultMessage|Message $message, array $mapped)

Map a tool result message to Anthropic format.

array
ensureToolInputIsObject(array $content)

Ensure tool_use and server_tool_use content blocks encode empty input as an object for replay.

array
mapTools(array $tools, Provider $provider)

Map the given tools to Anthropic tool definitions.

array
mapTool(Tool $tool, bool $defer = false)

Map a regular tool to an Anthropic tool definition.

array
mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to an Anthropic provider tool definition.

array
mapCodeExecutionTool(CodeExecution $tool, Provider $provider)

Map a code execution tool to an Anthropic server-side tool definition.

array
mapWebFetchTool(WebFetch $tool, Provider $provider)

Map a web fetch tool to an Anthropic server-side tool definition.

array
mapWebSearchTool(WebSearch $tool, Provider $provider)

Map a web search tool to an Anthropic server-side tool definition.

array
decodeStructuredOutput(string|null $text)

Decode a structured output payload, tolerating markdown code fences.

static string
joinReasoning(iterable $blocks)

Join reasoning blocks, separating each block with a blank line.

void
validateTextResponse(array $data)

Validate the Anthropic response data.

parseTextResponse(array $data, Provider $provider, bool $structured)

Parse the Anthropic response data into a single step response.

buildStepResponse(array $content, Provider $provider, string $model, TextUsage $usage, FinishReason $finishReason, bool $structured)

Build a single step response from Anthropic content blocks.

string
extractText(array $content)

Extract the text content from Anthropic content blocks.

string
textSeparator(string $before, string $after)

Get the separator between text written before a tool block and text written after it.

bool
isToolBlock(string $type)

Determine if the given block type is a server tool call or its result.

bool
isProviderToolResultBlock(string $type)

Determine if the given block type is a provider tool result.

string
extractReasoning(array $content)

Extract the reasoning text from Anthropic content blocks.

array
extractProviderToolCalls(array $content)

Extract the server tool use and result blocks, each keyed by the tool use it belongs to.

array
extractToolCalls(array $content)

Extract tool calls from Anthropic content blocks.

extractCitations(array $content)

Extract citations from Anthropic content blocks.

extractUsage(array $data)

Extract usage data from the Anthropic response.

FinishReason
extractFinishReason(array $data)

Extract and map the finish reason from the Anthropic response.

array
extractStructuredOutput(array $content)

Extract structured output from the synthetic tool call.

mixed
withErrorHandling(string $providerName, Closure $callback)

Execute a callback with failoverable error handling.

int|null
retryAfterSeconds(Throwable $exception)

Get the short Retry-After delay of a rate limited or overloaded response, if it has one.

bool
isInsufficientCredits(RequestException $exception)

Determine if the response is a 402, or a 429 insufficient credits or quota error rather than a rate limit.

array
overloadedStatusCodes()

Get the status codes that indicate a provider is transiently unavailable and the request should fail over.

array
insufficientCreditPatterns()

Get the patterns used to detect insufficient credits or quota errors.

array
insufficientCreditCodes()

Get the error codes or types that indicate insufficient credits or quota on a 429 response.

parseServerSentEvents(StreamInterface $streamBody)

Parse an SSE stream body into decoded JSON data objects.

string
readLine(StreamInterface $streamBody)

Read one line without waiting for a larger body buffer to fill.

__construct(Dispatcher $events)

Create an Anthropic gateway instance.

generateTextStep(TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, int|null $timeout, StepContext $stepContext)

Generate text for a single step in a conversation.

generateStreamStep(string $invocationId, TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, int|null $timeout, StepContext $stepContext)

Stream text for a single step in a conversation.

generateImage(ImageProvider $provider, string $model, string $prompt, array $attachments = [], string|null $size = null, string|null $quality = null, int|null $timeout = null, array $providerOptions = [])

Generate an image.

generateAudio(AudioProvider $provider, string $model, string $text, string $voice, string|null $instructions = null, int $timeout = 30, array $providerOptions = [])

Generate audio from the given text.

generateTranscription(TranscriptionProvider $provider, string $model, TranscribableAudio $audio, string|null $language = null, bool $diarize = false, int $timeout = 30, array $providerOptions = [])

Generate text from the given audio.

generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])

Generate embeddings for the given inputs.

Details

in BuildsTextRequests at line 22
protected array buildTextRequestBody(Provider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options)

Build the request body for the Anthropic Messages API.

Parameters

Provider $provider
string $model
string|null $instructions
array $messages
array $tools
array|null $schema
TextGenerationOptions|null $options

Return Value

array

in BuildsTextRequests at line 87
protected array applyPromptCacheBreakpoints(array $body, TextGenerationOptions|null $options)

Stamp the requested cache breakpoints onto the final request body.

Parameters

array $body
TextGenerationOptions|null $options

Return Value

array

in BuildsTextRequests at line 118
protected void ensureValidPromptCacheOrder(array $body, TextGenerationOptions|null $options)

Ensure longer-lived cache breakpoints precede shorter-lived breakpoints.

Parameters

array $body
TextGenerationOptions|null $options

Return Value

void

in BuildsTextRequests at line 141
protected array cacheControl(string|null $ttl)

Build the cache control block for the given TTL.

Parameters

string|null $ttl

Return Value

array

in BuildsTextRequests at line 149
protected bool supportsSamplingParameters(string $model)

Determine if the model accepts temperature and top_p.

Parameters

string $model

Return Value

bool

in BuildsTextRequests at line 157
protected array resolveToolChoice(array|null $schema, array $tools, array $providerOptions, ToolChoice|null $toolChoice = null)

Determine the tool_choice strategy for the request.

Parameters

array|null $schema
array $tools
array $providerOptions
ToolChoice|null $toolChoice

Return Value

array

in BuildsTextRequests at line 192
protected bool supportsNativeStructuredOutput(Provider $provider)

Determine if the provider supports native structured output via output_config.

Parameters

Provider $provider

Return Value

bool

in BuildsTextRequests at line 206
protected array buildStructuredOutputTool(array $schema)

Build the synthetic tool definition for structured output.

Parameters

array $schema

Return Value

array

in CreatesClient at line 21
protected PendingRequest createClient(string $baseUrl, array $headers = [], array $configuredHeaders = [], int|null $timeout = 60, bool $throw = true)

Create an HTTP client with the provider's request options.

Parameters

string $baseUrl
array $headers
array $configuredHeaders
int|null $timeout
bool $throw

Return Value

PendingRequest

in CreatesClient at line 43
protected string httpConnection(Provider $provider)

Select a boot-registered connection without retaining dynamic provider names.

Parameters

Provider $provider

Return Value

string

protected PendingRequest client(Provider $provider, int|null $timeout = null)

Get an HTTP client for the Anthropic API.

Parameters

Provider $provider
int|null $timeout

Return Value

PendingRequest

protected string baseUrl(Provider $provider)

Get the base URL for the Anthropic API.

Parameters

Provider $provider

Return Value

string

protected array pausedContent(array $messages)

Get the content of the paused steps the turn being continued is made of.

Parameters

array $messages

Return Value

array

protected Generator processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody, array $pausedContent = [])

Process a single Anthropic streaming turn and yield Hypervel stream events.

Parameters

string $invocationId
Provider $provider
string $model
StreamInterface $streamBody
array $pausedContent

Return Value

Generator

in HandlesTextStreaming at line 402
protected string generateEventId()

Generate a lowercase UUID v7 for use as a stream event ID.

Return Value

string

in MapsAttachments at line 29
protected array mapAttachments(Collection $attachments)

Map the given Hypervel attachments to Anthropic content blocks.

Parameters

Collection $attachments

Return Value

array

in MapsAttachments at line 142
protected array documentSource(string|null $mimeType, callable $rawResolver, callable $base64Resolver)

Build the Anthropic document source block for the given mime type.

Parameters

string|null $mimeType
callable $rawResolver
callable $base64Resolver

Return Value

array

in MapsAttachments at line 178
protected array remoteDocumentSource(RemoteDocument $document)

Build the Anthropic document source block for the given remote document.

Parameters

RemoteDocument $document

Return Value

array

in MapsAttachments at line 204
protected string|null normalizeMimeType(string|null $mimeType)

Strip any parameters from the given mime type.

Parameters

string|null $mimeType

Return Value

string|null

in MapsAttachments at line 212
protected bool isImage(UploadedFile $attachment)

Determine if the given uploaded file is an image.

Parameters

UploadedFile $attachment

Return Value

bool

in MapsMessages at line 18
protected array mapMessages(array $messages)

Map the given Hypervel messages to Anthropic Messages API format.

Parameters

array $messages

Return Value

array

in MapsMessages at line 38
protected void mapUserMessage(UserMessage|Message $message, array $mapped)

Map a user message to Anthropic format.

Parameters

UserMessage|Message $message
array $mapped

Return Value

void

in MapsMessages at line 55
protected void mapAssistantMessage(AssistantMessage|Message $message, array $mapped)

Map an assistant message to Anthropic format.

Parameters

AssistantMessage|Message $message
array $mapped

Return Value

void

in MapsMessages at line 100
protected void mapToolResultMessage(ToolResultMessage|Message $message, array $mapped)

Map a tool result message to Anthropic format.

Parameters

ToolResultMessage|Message $message
array $mapped

Return Value

void

in MapsMessages at line 125
protected array ensureToolInputIsObject(array $content)

Ensure tool_use and server_tool_use content blocks encode empty input as an object for replay.

Parameters

array $content

Return Value

array

in MapsTools at line 34
protected array mapTools(array $tools, Provider $provider)

Map the given tools to Anthropic tool definitions.

Parameters

array $tools
Provider $provider

Return Value

array

in MapsTools at line 68
protected array mapTool(Tool $tool, bool $defer = false)

Map a regular tool to an Anthropic tool definition.

Parameters

Tool $tool
bool $defer

Return Value

array

in MapsTools at line 97
protected array mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to an Anthropic provider tool definition.

Parameters

ProviderTool $tool
Provider $provider

Return Value

array

in MapsTools at line 110
protected array mapCodeExecutionTool(CodeExecution $tool, Provider $provider)

Map a code execution tool to an Anthropic server-side tool definition.

Parameters

CodeExecution $tool
Provider $provider

Return Value

array

in MapsTools at line 126
protected array mapWebFetchTool(WebFetch $tool, Provider $provider)

Map a web fetch tool to an Anthropic server-side tool definition.

Parameters

WebFetch $tool
Provider $provider

Return Value

array

in MapsTools at line 142
protected array mapWebSearchTool(WebSearch $tool, Provider $provider)

Map a web search tool to an Anthropic server-side tool definition.

Parameters

WebSearch $tool
Provider $provider

Return Value

array

protected array decodeStructuredOutput(string|null $text)

Decode a structured output payload, tolerating markdown code fences.

Parameters

string|null $text

Return Value

array

in JoinsReasoning at line 16
static protected string joinReasoning(iterable $blocks)

Join reasoning blocks, separating each block with a blank line.

Parameters

iterable $blocks

Return Value

string

protected void validateTextResponse(array $data)

Validate the Anthropic response data.

Parameters

array $data

Return Value

void

Exceptions

AiException

protected StepResponse parseTextResponse(array $data, Provider $provider, bool $structured)

Parse the Anthropic response data into a single step response.

Parameters

array $data
Provider $provider
bool $structured

Return Value

StepResponse

protected StepResponse buildStepResponse(array $content, Provider $provider, string $model, TextUsage $usage, FinishReason $finishReason, bool $structured)

Build a single step response from Anthropic content blocks.

Parameters

array $content
Provider $provider
string $model
TextUsage $usage
FinishReason $finishReason
bool $structured

Return Value

StepResponse

in ParsesTextResponses at line 114
protected string extractText(array $content)

Extract the text content from Anthropic content blocks.

Parameters

array $content

Return Value

string

in ParsesTextResponses at line 143
protected string textSeparator(string $before, string $after)

Get the separator between text written before a tool block and text written after it.

Parameters

string $before
string $after

Return Value

string

in ParsesTextResponses at line 151
protected bool isToolBlock(string $type)

Determine if the given block type is a server tool call or its result.

Parameters

string $type

Return Value

bool

in ParsesTextResponses at line 159
protected bool isProviderToolResultBlock(string $type)

Determine if the given block type is a provider tool result.

Parameters

string $type

Return Value

bool

in ParsesTextResponses at line 167
protected string extractReasoning(array $content)

Extract the reasoning text from Anthropic content blocks.

Parameters

array $content

Return Value

string

in ParsesTextResponses at line 179
protected array extractProviderToolCalls(array $content)

Extract the server tool use and result blocks, each keyed by the tool use it belongs to.

Parameters

array $content

Return Value

array

in ParsesTextResponses at line 192
protected array extractToolCalls(array $content)

Extract tool calls from Anthropic content blocks.

Parameters

array $content

Return Value

array

in ParsesTextResponses at line 207
protected Collection extractCitations(array $content)

Extract citations from Anthropic content blocks.

Parameters

array $content

Return Value

Collection

in ParsesTextResponses at line 252
protected TextUsage extractUsage(array $data)

Extract usage data from the Anthropic response.

Parameters

array $data

Return Value

TextUsage

in ParsesTextResponses at line 271
protected FinishReason extractFinishReason(array $data)

Extract and map the finish reason from the Anthropic response.

Parameters

array $data

Return Value

FinishReason

in ParsesTextResponses at line 286
protected array extractStructuredOutput(array $content)

Extract structured output from the synthetic tool call.

Parameters

array $content

Return Value

array

protected mixed withErrorHandling(string $providerName, Closure $callback)

Execute a callback with failoverable error handling.

Parameters

string $providerName
Closure $callback

Return Value

mixed

protected int|null retryAfterSeconds(Throwable $exception)

Get the short Retry-After delay of a rate limited or overloaded response, if it has one.

Parameters

Throwable $exception

Return Value

int|null

protected bool isInsufficientCredits(RequestException $exception)

Determine if the response is a 402, or a 429 insufficient credits or quota error rather than a rate limit.

Parameters

RequestException $exception

Return Value

bool

at line 212
protected array overloadedStatusCodes()

Get the status codes that indicate a provider is transiently unavailable and the request should fail over.

Return Value

array

at line 221
protected array insufficientCreditPatterns()

Get the patterns used to detect insufficient credits or quota errors.

Return Value

array

protected array insufficientCreditCodes()

Get the error codes or types that indicate insufficient credits or quota on a 429 response.

Return Value

array

protected Generator parseServerSentEvents(StreamInterface $streamBody)

Parse an SSE stream body into decoded JSON data objects.

Parameters

StreamInterface $streamBody

Return Value

Generator

protected string readLine(StreamInterface $streamBody)

Read one line without waiting for a larger body buffer to fill.

Parameters

StreamInterface $streamBody

Return Value

string

at line 52
__construct(Dispatcher $events)

Create an Anthropic gateway instance.

Parameters

Dispatcher $events

at line 59
StepResponse generateTextStep(TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, int|null $timeout, StepContext $stepContext)

Generate text for a single step in a conversation.

Parameters

TextProvider $provider
string $model
string|null $instructions
array $messages
array $tools
array|null $schema
TextGenerationOptions|null $options
int|null $timeout
StepContext $stepContext

Return Value

StepResponse

at line 96
Generator generateStreamStep(string $invocationId, TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, int|null $timeout, StepContext $stepContext)

Stream text for a single step in a conversation.

Parameters

string $invocationId
TextProvider $provider
string $model
string|null $instructions
array $messages
array $tools
array|null $schema
TextGenerationOptions|null $options
int|null $timeout
StepContext $stepContext

Return Value

Generator

at line 142
ImageResponse generateImage(ImageProvider $provider, string $model, string $prompt, array $attachments = [], string|null $size = null, string|null $quality = null, int|null $timeout = null, array $providerOptions = [])

Generate an image.

Parameters

ImageProvider $provider
string $model
string $prompt
array $attachments
string|null $size
string|null $quality
int|null $timeout
array $providerOptions

Return Value

ImageResponse

Exceptions

LogicException

at line 161
AudioResponse generateAudio(AudioProvider $provider, string $model, string $text, string $voice, string|null $instructions = null, int $timeout = 30, array $providerOptions = [])

Generate audio from the given text.

Parameters

AudioProvider $provider
string $model
string $text
string $voice
string|null $instructions
int $timeout
array $providerOptions

Return Value

AudioResponse

Exceptions

LogicException

at line 179
TranscriptionResponse generateTranscription(TranscriptionProvider $provider, string $model, TranscribableAudio $audio, string|null $language = null, bool $diarize = false, int $timeout = 30, array $providerOptions = [])

Generate text from the given audio.

Parameters

TranscriptionProvider $provider
string $model
TranscribableAudio $audio
string|null $language
bool $diarize
int $timeout
array $providerOptions

Return Value

TranscriptionResponse

Exceptions

LogicException

at line 197
EmbeddingsResponse generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])

Generate embeddings for the given inputs.

Parameters

EmbeddingProvider $provider
string $model
array $inputs
int $dimensions
int $timeout
array $providerOptions

Return Value

EmbeddingsResponse

Exceptions

LogicException