class OllamaGateway implements EmbeddingGateway, StepTextGateway

Traits

Methods

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

Add structured output requirements to the instructions.

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

Build the request body for the current text generation step.

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

array
buildChatRequestBody(Provider $provider, string $model, array $chatMessages, array $tools, array|null $schema, TextGenerationOptions|null $options, bool $stream = false)

Build a request body from pre-mapped chat messages.

array
buildResponseFormat(array $schema)

Build the response format schema 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 Ollama API.

string
baseUrl(Provider $provider)

Get the base URL for the Ollama API.

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

Process an Ollama NDJSON streaming response and yield Hypervel stream events.

parseNdjsonStream(StreamInterface $streamBody)

Parse an Ollama NDJSON stream, yielding each parsed JSON object.

string
generateEventId()

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

array
mapAttachments(Collection $attachments)

Map the given Hypervel attachments to Ollama base64 image strings.

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 Ollama Chat API messages format.

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

Map a user message to Ollama Chat API format.

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

Map an assistant message to Ollama Chat API format.

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

Map a tool result message to Ollama Chat API format.

array
serializeToolCallToChat(ToolCall $toolCall)

Serialize a tool call DTO to Ollama Chat API array format.

array
mapTools(array $tools)

Map the given tools to Ollama function definitions.

array
mapTool(Tool $tool)

Map a regular tool to an Ollama function definition.

array
decodeStructuredOutput(string|null $text)

Decode a structured output payload, tolerating markdown code fences.

void
validateTextResponse(array $data)

Validate the Ollama response data.

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

Parse the Ollama response data into a single step response.

array
parseToolArguments(mixed $arguments)

Parse tool call arguments, handling both array and JSON string formats.

extractUsage(array $data)

Extract usage data from the Ollama response.

FinishReason
extractFinishReason(array $data)

Extract and map the finish reason from the Ollama response.

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.

__construct(Dispatcher $events)

Create an Ollama 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 Ollama Chat API step.

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 Ollama Chat API step.

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

Generate embeddings for the given inputs.

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 26
protected array buildStepBody(TextProvider $provider, string $model, string|null $instructions, array $messages, array $tools, array|null $schema, TextGenerationOptions|null $options, StepContext $stepContext)

Build the request body for the current text generation step.

Parameters

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

Return Value

array

in BuildsTextRequests at line 42
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 Ollama 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 64
protected array buildChatRequestBody(Provider $provider, string $model, array $chatMessages, array $tools, array|null $schema, TextGenerationOptions|null $options, bool $stream = false)

Build a request body from pre-mapped chat messages.

Parameters

Provider $provider
string $model
array $chatMessages
array $tools
array|null $schema
TextGenerationOptions|null $options
bool $stream

Return Value

array

in BuildsTextRequests at line 126
protected array buildResponseFormat(array $schema)

Build the response format schema 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 Ollama API.

Parameters

Provider $provider
int|null $timeout

Return Value

PendingRequest

protected string baseUrl(Provider $provider)

Get the base URL for the Ollama API.

Parameters

Provider $provider

Return Value

string

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

Process an Ollama NDJSON streaming response and yield Hypervel stream events.

Parameters

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

Return Value

Generator

in HandlesTextStreaming at line 256
protected Generator parseNdjsonStream(StreamInterface $streamBody)

Parse an Ollama NDJSON stream, yielding each parsed JSON object.

Parameters

StreamInterface $streamBody

Return Value

Generator

in HandlesTextStreaming at line 276
protected string generateEventId()

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

Return Value

string

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

Map the given Hypervel attachments to Ollama base64 image strings.

Parameters

Collection $attachments

Return Value

array

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

Determine if the given uploaded file is an image.

Parameters

UploadedFile $attachment

Return Value

bool

in MapsMessages at line 19
protected array mapMessagesToChat(array $messages, string|null $instructions = null)

Map the given Hypervel messages to Ollama Chat API messages format.

Parameters

array $messages
string|null $instructions

Return Value

array

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

Map a user message to Ollama Chat API format.

Parameters

UserMessage|Message $message
array $chatMessages

Return Value

void

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

Map an assistant message to Ollama Chat API format.

Parameters

AssistantMessage|Message $message
array $chatMessages

Return Value

void

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

Map a tool result message to Ollama Chat API format.

Parameters

ToolResultMessage|Message $message
array $chatMessages

Return Value

void

in MapsMessages at line 108
protected array serializeToolCallToChat(ToolCall $toolCall)

Serialize a tool call DTO to Ollama Chat API array format.

Ollama's /api/chat message history shape only uses the function object for assistant tool calls — no top-level type key.

That key belongs on the /api/chat tools definitions, not the message history.

Parameters

ToolCall $toolCall

Return Value

array

in MapsTools at line 19
protected array mapTools(array $tools)

Map the given tools to Ollama function definitions.

Parameters

array $tools

Return Value

array

in MapsTools at line 39
protected array mapTool(Tool $tool)

Map a regular tool to an Ollama function definition.

Parameters

Tool $tool

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

protected void validateTextResponse(array $data)

Validate the Ollama response data.

Parameters

array $data

Return Value

void

Exceptions

AiException

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

Parse the Ollama response data into a single step response.

Parameters

array $data
Provider $provider
bool $structured

Return Value

StepResponse

protected array parseToolArguments(mixed $arguments)

Parse tool call arguments, handling both array and JSON string formats.

Parameters

mixed $arguments

Return Value

array

protected TextUsage extractUsage(array $data)

Extract usage data from the Ollama response.

Parameters

array $data

Return Value

TextUsage

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

Extract and map the finish reason from the Ollama response.

Parameters

array $data

Return Value

FinishReason

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

at line 44
__construct(Dispatcher $events)

Create an Ollama gateway instance.

Parameters

Dispatcher $events

at line 51
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 Ollama Chat API step.

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 80
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 Ollama Chat API step.

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