class CohereGateway implements EmbeddingGateway, RerankingGateway, StepTextGateway

Traits

Methods

string|null
composeInstructions(string|null $instructions, array|null $schema)

Add structured output requirements to the instructions.

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 Cohere Chat API.

string|null
mapCohereToolChoice(ToolChoice $choice)

Map a tool choice to the Cohere tool_choice value.

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.

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.

processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody)

Process a Cohere Chat API event stream.

endReasoning(string $invocationId, string|null $reasoningId)

Emit a reasoning end event if a reasoning block is open.

string
generateEventId()

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

array
mapAttachments(Collection $attachments)

Map the given Hypervel attachments to Chat Completions content parts.

bool
isImage(UploadedFile $attachment)

Determine if the given uploaded file is an image.

array
mapMessagesToChat(array $messages, string|null $instructions = null)

Map the given Hypervel messages to Chat Completions messages format.

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

Map a user message to Chat Completions format.

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

Map an assistant message to Chat Completions format.

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

Map a tool result message to Chat Completions format.

array
serializeToolCallToChat(ToolCall $toolCall)

Serialize a tool call DTO to Chat Completions array format.

string
mapToolCallId(string $id)

Map a tool call or result ID to the provider's wire format.

array
mapTools(array $tools, Provider $provider)

Map the given tools to Chat Completions function definitions.

array
mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to a Chat Completions tool definition.

array
mapTool(Tool $tool)

Map a regular tool to a Chat Completions function definition.

string|array
mapToolChoice(ToolChoice $choice)

Map a tool choice to the Chat Completions tool_choice shape.

array
parseCohereEmbeddings(mixed $embeddings)

Normalize the embeddings of a Cohere response into a list of vectors.

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.

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(mixed $data)

Validate the Cohere response data.

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

Parse the Cohere response data into a single step response.

extractUsage(array $usage)

Extract usage data from a Cohere usage object.

FinishReason
extractFinishReason(string|null $finishReason)

Map a Cohere finish reason to the finish reason enum.

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.

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

Generate embedding vectors representing the given inputs.

rerank(RerankingProvider $provider, string $model, array $documents, string $query, int|null $limit = null, int $timeout = 30, array $providerOptions = [])

Rerank the given documents based on their relevance to the query.

client(Provider $provider, int $timeout = 30)

Get an HTTP client for the Cohere API.

Details

protected string|null composeInstructions(string|null $instructions, array|null $schema)

Add structured output requirements to the instructions.

Parameters

string|null $instructions
array|null $schema

Return Value

string|null

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 Cohere Chat 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 91
protected string|null mapCohereToolChoice(ToolChoice $choice)

Map a tool choice to the Cohere tool_choice value.

Parameters

ToolChoice $choice

Return Value

string|null

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 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

protected array overloadedStatusCodes()

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

Return Value

array

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 processTextStream(string $invocationId, Provider $provider, string $model, StreamInterface $streamBody)

Process a Cohere Chat API event stream.

Parameters

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

Return Value

Generator

in HandlesTextStreaming at line 201
protected Generator endReasoning(string $invocationId, string|null $reasoningId)

Emit a reasoning end event if a reasoning block is open.

Parameters

string $invocationId
string|null $reasoningId

Return Value

Generator

in HandlesTextStreaming at line 219
protected string generateEventId()

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

Return Value

string

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

Map the given Hypervel attachments to Chat Completions content parts.

Parameters

Collection $attachments

Return Value

array

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

Determine if the given uploaded file is an image.

Parameters

UploadedFile $attachment

Return Value

bool

protected array mapMessagesToChat(array $messages, string|null $instructions = null)

Map the given Hypervel messages to Chat Completions messages format.

Parameters

array $messages
string|null $instructions

Return Value

array

protected void mapUserMessage(UserMessage|Message $message, array $chatMessages)

Map a user message to Chat Completions format.

Parameters

UserMessage|Message $message
array $chatMessages

Return Value

void

protected void mapAssistantMessage(AssistantMessage|Message $message, array $chatMessages)

Map an assistant message to Chat Completions format.

Parameters

AssistantMessage|Message $message
array $chatMessages

Return Value

void

protected void mapToolResultMessage(ToolResultMessage|Message $message, array $chatMessages)

Map a tool result message to Chat Completions format.

Parameters

ToolResultMessage|Message $message
array $chatMessages

Return Value

void

protected array serializeToolCallToChat(ToolCall $toolCall)

Serialize a tool call DTO to Chat Completions array format.

Parameters

ToolCall $toolCall

Return Value

array

protected string mapToolCallId(string $id)

Map a tool call or result ID to the provider's wire format.

Parameters

string $id

Return Value

string

protected array mapTools(array $tools, Provider $provider)

Map the given tools to Chat Completions function definitions.

Parameters

array $tools
Provider $provider

Return Value

array

protected array mapProviderTool(ProviderTool $tool, Provider $provider)

Map a provider tool to a Chat Completions tool definition.

Parameters

ProviderTool $tool
Provider $provider

Return Value

array

protected array mapTool(Tool $tool)

Map a regular tool to a Chat Completions function definition.

Parameters

Tool $tool

Return Value

array

protected string|array mapToolChoice(ToolChoice $choice)

Map a tool choice to the Chat Completions tool_choice shape.

Parameters

ToolChoice $choice

Return Value

string|array

in ParsesEmbeddings at line 18
protected array parseCohereEmbeddings(mixed $embeddings)

Normalize the embeddings of a Cohere response into a list of vectors.

Parameters

mixed $embeddings

Return Value

array

Exceptions

AiException

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

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(mixed $data)

Validate the Cohere response data.

Parameters

mixed $data

Return Value

void

Exceptions

AiException

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

Parse the Cohere response data into a single step response.

Parameters

array $data
Provider $provider
string $model
bool $structured

Return Value

StepResponse

protected TextUsage extractUsage(array $usage)

Extract usage data from a Cohere usage object.

Parameters

array $usage

Return Value

TextUsage

protected FinishReason extractFinishReason(string|null $finishReason)

Map a Cohere finish reason to the finish reason enum.

Parameters

string|null $finishReason

Return Value

FinishReason

at line 50
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 79
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 112
EmbeddingsResponse generateEmbeddings(EmbeddingProvider $provider, string $model, array $inputs, int $dimensions, int $timeout = 30, array $providerOptions = [])

Generate embedding vectors representing the given inputs.

Parameters

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

Return Value

EmbeddingsResponse

at line 154
RerankingResponse rerank(RerankingProvider $provider, string $model, array $documents, string $query, int|null $limit = null, int $timeout = 30, array $providerOptions = [])

Rerank the given documents based on their relevance to the query.

Parameters

RerankingProvider $provider
string $model
array $documents
string $query
int|null $limit
int $timeout
array $providerOptions

Return Value

RerankingResponse

at line 195
protected PendingRequest client(Provider $provider, int $timeout = 30)

Get an HTTP client for the Cohere API.

Parameters

Provider $provider
int $timeout

Return Value

PendingRequest