AnthropicGateway
class AnthropicGateway implements Gateway, StepTextGateway
Traits
Methods
Build the request body for the Anthropic Messages API.
Stamp the requested cache breakpoints onto the final request body.
Ensure longer-lived cache breakpoints precede shorter-lived breakpoints.
Build the cache control block for the given TTL.
Determine if the model accepts temperature and top_p.
Determine the tool_choice strategy for the request.
Determine if the provider supports native structured output via output_config.
Build the synthetic tool definition for structured output.
Create an HTTP client with the provider's request options.
Select a boot-registered connection without retaining dynamic provider names.
Get the content of the paused steps the turn being continued is made of.
Process a single Anthropic streaming turn and yield Hypervel stream events.
Generate a lowercase UUID v7 for use as a stream event ID.
Map the given Hypervel attachments to Anthropic content blocks.
Build the Anthropic document source block for the given mime type.
Build the Anthropic document source block for the given remote document.
Strip any parameters from the given mime type.
Map the given Hypervel messages to Anthropic Messages API format.
Map an assistant message to Anthropic format.
Map a tool result message to Anthropic format.
Ensure tool_use and server_tool_use content blocks encode empty input as an object for replay.
Map a provider tool to an Anthropic provider tool definition.
Map a code execution tool to an Anthropic server-side tool definition.
Map a web fetch tool to an Anthropic server-side tool definition.
Map a web search tool to an Anthropic server-side tool definition.
Decode a structured output payload, tolerating markdown code fences.
Join reasoning blocks, separating each block with a blank line.
Validate the Anthropic response data.
Parse the Anthropic response data into a single step response.
Build a single step response from Anthropic content blocks.
Extract the text content from Anthropic content blocks.
Get the separator between text written before a tool block and text written after it.
Determine if the given block type is a server tool call or its result.
Determine if the given block type is a provider tool result.
Extract the reasoning text from Anthropic content blocks.
Extract the server tool use and result blocks, each keyed by the tool use it belongs to.
Extract tool calls from Anthropic content blocks.
Extract citations from Anthropic content blocks.
Extract usage data from the Anthropic response.
Extract and map the finish reason from the Anthropic response.
Extract structured output from the synthetic tool call.
Execute a callback with failoverable error handling.
Get the short Retry-After delay of a rate limited or overloaded response, if it has one.
Determine if the response is a 402, or a 429 insufficient credits or quota error rather than a rate limit.
Get the status codes that indicate a provider is transiently unavailable and the request should fail over.
Get the patterns used to detect insufficient credits or quota errors.
Get the error codes or types that indicate insufficient credits or quota on a 429 response.
Parse an SSE stream body into decoded JSON data objects.
Read one line without waiting for a larger body buffer to fill.
Generate text for a single step in a conversation.
Stream text for a single step in a conversation.
Generate an image.
Generate audio from the given text.
Generate text from the given audio.
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.
in
BuildsTextRequests at line 87
protected array
applyPromptCacheBreakpoints(array $body, TextGenerationOptions|null $options)
Stamp the requested cache breakpoints onto the final request body.
in
BuildsTextRequests at line 118
protected void
ensureValidPromptCacheOrder(array $body, TextGenerationOptions|null $options)
Ensure longer-lived cache breakpoints precede shorter-lived breakpoints.
in
BuildsTextRequests at line 141
protected array
cacheControl(string|null $ttl)
Build the cache control block for the given TTL.
in
BuildsTextRequests at line 149
protected bool
supportsSamplingParameters(string $model)
Determine if the model accepts temperature and top_p.
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.
in
BuildsTextRequests at line 192
protected bool
supportsNativeStructuredOutput(Provider $provider)
Determine if the provider supports native structured output via output_config.
in
BuildsTextRequests at line 206
protected array
buildStructuredOutputTool(array $schema)
Build the synthetic tool definition for structured output.
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.
in
CreatesClient at line 43
protected string
httpConnection(Provider $provider)
Select a boot-registered connection without retaining dynamic provider names.
in
CreatesAnthropicClient at line 18
protected PendingRequest
client(Provider $provider, int|null $timeout = null)
Get an HTTP client for the Anthropic API.
in
CreatesAnthropicClient at line 39
protected string
baseUrl(Provider $provider)
Get the base URL for the Anthropic API.
in
HandlesTextStreaming at line 38
protected array
pausedContent(array $messages)
Get the content of the paused steps the turn being continued is made of.
in
HandlesTextStreaming at line 54
protected Generator
processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody, array $pausedContent = [])
Process a single Anthropic streaming turn and yield Hypervel stream events.
in
HandlesTextStreaming at line 402
protected string
generateEventId()
Generate a lowercase UUID v7 for use as a stream event ID.
in
MapsAttachments at line 29
protected array
mapAttachments(Collection $attachments)
Map the given Hypervel attachments to Anthropic content blocks.
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.
in
MapsAttachments at line 178
protected array
remoteDocumentSource(RemoteDocument $document)
Build the Anthropic document source block for the given remote document.
in
MapsAttachments at line 204
protected string|null
normalizeMimeType(string|null $mimeType)
Strip any parameters from the given mime type.
in
MapsAttachments at line 212
protected bool
isImage(UploadedFile $attachment)
Determine if the given uploaded file is an image.
in
MapsMessages at line 18
protected array
mapMessages(array $messages)
Map the given Hypervel messages to Anthropic Messages API format.
in
MapsMessages at line 38
protected void
mapUserMessage(UserMessage|Message $message, array $mapped)
Map a user message to Anthropic format.
in
MapsMessages at line 55
protected void
mapAssistantMessage(AssistantMessage|Message $message, array $mapped)
Map an assistant message to Anthropic format.
in
MapsMessages at line 100
protected void
mapToolResultMessage(ToolResultMessage|Message $message, array $mapped)
Map a tool result message to Anthropic format.
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.
in
MapsTools at line 34
protected array
mapTools(array $tools, Provider $provider)
Map the given tools to Anthropic tool definitions.
in
MapsTools at line 68
protected array
mapTool(Tool $tool, bool $defer = false)
Map a regular tool to an Anthropic tool definition.
in
MapsTools at line 97
protected array
mapProviderTool(ProviderTool $tool, Provider $provider)
Map a provider tool to an Anthropic provider tool definition.
in
MapsTools at line 110
protected array
mapCodeExecutionTool(CodeExecution $tool, Provider $provider)
Map a code execution tool to an Anthropic server-side tool definition.
in
MapsTools at line 126
protected array
mapWebFetchTool(WebFetch $tool, Provider $provider)
Map a web fetch tool to an Anthropic server-side tool definition.
in
MapsTools at line 142
protected array
mapWebSearchTool(WebSearch $tool, Provider $provider)
Map a web search tool to an Anthropic server-side tool definition.
in
DecodesStructuredOutput at line 12
protected array
decodeStructuredOutput(string|null $text)
Decode a structured output payload, tolerating markdown code fences.
in
JoinsReasoning at line 16
static protected string
joinReasoning(iterable $blocks)
Join reasoning blocks, separating each block with a blank line.
in
ParsesTextResponses at line 30
protected void
validateTextResponse(array $data)
Validate the Anthropic response data.
in
ParsesTextResponses at line 44
protected StepResponse
parseTextResponse(array $data, Provider $provider, bool $structured)
Parse the Anthropic response data into a single step response.
in
ParsesTextResponses at line 62
protected StepResponse
buildStepResponse(array $content, Provider $provider, string $model, TextUsage $usage, FinishReason $finishReason, bool $structured)
Build a single step response from Anthropic content blocks.
in
ParsesTextResponses at line 114
protected string
extractText(array $content)
Extract the text content from Anthropic content blocks.
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.
in
ParsesTextResponses at line 151
protected bool
isToolBlock(string $type)
Determine if the given block type is a server tool call or its result.
in
ParsesTextResponses at line 159
protected bool
isProviderToolResultBlock(string $type)
Determine if the given block type is a provider tool result.
in
ParsesTextResponses at line 167
protected string
extractReasoning(array $content)
Extract the reasoning text from Anthropic content blocks.
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.
in
ParsesTextResponses at line 192
protected array
extractToolCalls(array $content)
Extract tool calls from Anthropic content blocks.
in
ParsesTextResponses at line 207
protected Collection
extractCitations(array $content)
Extract citations from Anthropic content blocks.
in
ParsesTextResponses at line 252
protected TextUsage
extractUsage(array $data)
Extract usage data from the Anthropic response.
in
ParsesTextResponses at line 271
protected FinishReason
extractFinishReason(array $data)
Extract and map the finish reason from the Anthropic response.
in
ParsesTextResponses at line 286
protected array
extractStructuredOutput(array $content)
Extract structured output from the synthetic tool call.
in
HandlesFailoverErrors at line 26
protected mixed
withErrorHandling(string $providerName, Closure $callback)
Execute a callback with failoverable error handling.
in
HandlesFailoverErrors at line 91
protected int|null
retryAfterSeconds(Throwable $exception)
Get the short Retry-After delay of a rate limited or overloaded response, if it has one.
in
HandlesFailoverErrors at line 115
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.
at line 212
protected array
overloadedStatusCodes()
Get the status codes that indicate a provider is transiently unavailable and the request should fail over.
at line 221
protected array
insufficientCreditPatterns()
Get the patterns used to detect insufficient credits or quota errors.
in
HandlesFailoverErrors at line 158
protected array
insufficientCreditCodes()
Get the error codes or types that indicate insufficient credits or quota on a 429 response.
in
ParsesServerSentEvents at line 24
protected Generator
parseServerSentEvents(StreamInterface $streamBody)
Parse an SSE stream body into decoded JSON data objects.
in
ParsesServerSentEvents at line 52
protected string
readLine(StreamInterface $streamBody)
Read one line without waiting for a larger body buffer to fill.
at line 52
__construct(Dispatcher $events)
Create an Anthropic gateway instance.
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.
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.
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.
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.
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.
at line 197
EmbeddingsResponse
generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])
Generate embeddings for the given inputs.