Download the PHP package vluzrmos/ollama without Composer
On this page you can find all versions of the php package vluzrmos/ollama. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package ollama
Ollama PHP Client
PHP client for the Ollama native API and OpenAI-compatible endpoints, with support for PHP 5.6+.
This library provides:
- Native Ollama API access
- OpenAI-compatible API access
- Reusable model configuration objects
- Typed message helpers for chat, tools, and multimodal inputs
- Streaming and async requests
- Tool calling and tool execution helpers
- High-level chat orchestration with automatic tool recursion
- Agent and agent-group abstractions
- Image helpers for vision models
- Embeddings, model management, and runtime utilities
Features
- Compatible with PHP 5.6+
- Native Ollama client
- OpenAI-compatible client
- Sync and async APIs
- Streaming responses
- Chat completions and text completions
- Embeddings
- Vision and image message helpers
- Function calling and tool execution
- Built-in tool registry and result conversion
- High-level chat session wrapper
- Agent and agent group abstractions
- Model lifecycle operations for Ollama
- Response wrappers with array-style access
- Configurable HTTP client options and Bearer token support
Requirements
- PHP >= 5.6.0
- ext-curl
- ext-json
Installation
Quick Start
Ollama Native API
OpenAI-Compatible API
Core Concepts
Model
The Model class lets you define a reusable model plus default request parameters.
Supported convenience setters include:
setTemperature()setTopP()setTopK()setRepeatPenalty()setSeed()setNumCtx()setNumPredict()setStop()setParameter()andsetOption()for custom values
Message
The Message helper supports standard chat roles, tool messages, and multimodal payloads.
Available constructors:
Message::system($content)Message::user($content, array $images = null)Message::assistant($content)Message::tool($content, $toolName)Message::image($text, $imageUrl, $role = 'user')
Response Wrappers
Responses are returned as wrapper objects that implement array-style access and can also be converted back to raw arrays.
ResponseResponseMessageResponseEmbedding
Useful helpers include:
toArray()getMessages()getToolCalls()hasToolCalls()getEmbeddings()
Ollama Client
Class: Vluzrmos\Ollama\Ollama
Default base URL: http://localhost:11434
Main Operations
Text generation
Chat completions
Embeddings
Model and Runtime Management
The native Ollama client exposes the following operations:
listModels()andlistModelsAsync()showModel()andshowModelAsync()copyModel()andcopyModelAsync()deleteModel()anddeleteModelAsync()pullModel()andpullModelAsync()pushModel()andpushModelAsync()createModel()andcreateModelAsync()listRunningModels()andlistRunningModelsAsync()version()andversionAsync()blobExists()andblobExistsAsync()pushBlob()andpushBlobAsync()
Example:
Authentication
If your Ollama-compatible endpoint requires a Bearer token:
OpenAI-Compatible Client
Class: Vluzrmos\Ollama\OpenAI
Default base URL: http://localhost:11434/v1
Default API key: ollama
Supported Endpoints
/v1/chat/completions/v1/completions/v1/embeddings/v1/models/v1/models/{model}/v1/responses/v1/responses/{id}/v1/responses/{id}/input_items
High-Level Convenience Methods
chat()andchatAsync()chatStream()andchatStreamAsync()complete()andcompleteAsync()completeStream()andcompleteStreamAsync()embed()andembedAsync()listModels()andlistModelsAsync()retrieveModel()andretrieveModelAsync()respond()andrespondAsync()respondStream()andrespondStreamAsync()getResponse()andgetResponseAsync()deleteResponse()anddeleteResponseAsync()cancelResponse()andcancelResponseAsync()listResponseInputItems()andlistResponseInputItemsAsync()
Low-Level Request Methods
chatCompletions()andchatCompletionsAsync()completions()andcompletionsAsync()embeddings()andembeddingsAsync()createResponse()andcreateResponseAsync()
Chat Example
Text Completion Example
Embedding Example
Responses API
The OpenAI client supports the Responses API, which provides a stateful alternative to Chat Completions with built-in support for multi-turn conversations, tool calling, and structured output.
Simple Response
Multi-Turn Conversation
Use previous_response_id to chain multiple turns without manually tracking messages:
Streaming
Tool Calling
Structured Output
Retrieve, Delete and Cancel
Response Model
The ResponsesResponse wrapper provides typed access to the response fields:
getId()— response IDgetStatus()— status (completed,in_progress,incomplete,cancelled,failed)getOutputText()— first text outputgetOutputTexts()— all text outputsgetOutput()— raw output items arrayhasFunctionCalls()andgetFunctionCalls()— tool call detectionhasError()andgetError()— error detectiongetUsage()— token usage informationgetModel(),getTemperature(),getTopP(),getInstructions()getPreviousResponseId()— for conversation chaining
Streaming
Both clients support streamed responses through a callback that receives decoded chunks.
Ollama Streaming
OpenAI Streaming
Async Requests
Async variants are available on both clients and return Guzzle promises.
Examples:
generateAsync()chatAsync()embeddingsAsync()chatCompletionsAsync()completeAsync()embedAsync()
Concurrent Requests (Pool)
Use the pool() method to send multiple requests concurrently via Guzzle's Pool. Each yielded value must be a callable that returns a promise (not a promise directly).
Pool configuration options:
| Option | Type | Description |
|---|---|---|
concurrency |
int | Maximum number of requests to send concurrently |
fulfilled |
callable | Callback invoked when a request completes. Receives ($response, $index) |
rejected |
callable | Callback invoked when a request fails. Receives ($reason, $index) |
Important: Each yielded value must be a closure that returns a promise (e.g. wrapping an
*Async()call), not the promise itself. Passing promises directly will throw anInvalidArgumentException.
The pool() method is available on both OpenAI and Ollama clients. You can use any async method (chatAsync(), completeAsync(), embedAsync(), etc.) inside the generator.
Vision and Images
Use Message::image() together with ImageHelper for vision-capable models.
Available helpers:
ImageHelper::encodeImage()ImageHelper::encodeImages()ImageHelper::encodeImageUrl()ImageHelper::encodeImagesUrl()ImageHelper::isValidImage()ImageHelper::getImageInfo()
JSON Mode and Structured Output
OpenAI-compatible chat requests accept response_format options, including json_object and json_schema.
Tools and Function Calling
The library includes a complete tool system with registration, serialization, execution, and conversion of tool results back into chat messages.
Creating a Custom Tool
ToolManager
Available operations:
registerTool()unregisterTool()getTool()hasTool()listTools()toArray()jsonSerialize()executeTool()executeToolCalls()decodeToolCallArguments()toolCallResultsToMessages()getStats()
OpenAI-Compatible Tool Calling Flow
For dynamic values such as the current date or current time, do not include the answer itself in the system prompt or conversation context if you expect a tool call. If the model already sees that value in the prompt, it may answer directly and skip the tool. Add an explicit instruction to use the tool for time-sensitive questions and, when your OpenAI-compatible provider supports it, consider passing
tool_choicefor deterministic tool selection.
Built-In Tools
TimeToolBrasilAPI\CEPInfoToolBrasilAPI\CNPJInfoToolBrasilAPI\FeriadosNacionaisTool
High-Level Chat Orchestrator
Class: Vluzrmos\Ollama\Chat\Chat
This wrapper maintains conversation history, registers tools, sends messages through a chat adapter, and automatically re-enters the model when tool calls are returned.
Main operations:
withModel()addMessage()addMessages()registerTool()registerTools()getModel()getMessages()getTools()chat()
Agents
The agent layer builds on top of the clients and tool manager to provide reusable role-based assistants.
Agent
Class: Vluzrmos\Ollama\Agents\Agent
An agent has:
- name
- description
- system instructions
- a model
- a client adapter
- optional tools
- default request options
Agent operations:
processQuery()canHandle()addTool()removeTool()getTools()setOptions()getOptions()
AgentGroup
Class: Vluzrmos\Ollama\Agents\AgentGroup
An agent group uses a selector prompt to either:
- answer directly
- route the query to the most appropriate specialized agent
Available operations:
processQuery()addAgent()removeAgent()getAgents()getAgent()getTools()setSelectorInstructions()
Client Adapters
The agent system includes adapters for both client styles:
Vluzrmos\Ollama\Agents\OpenAIClientAdapterVluzrmos\Ollama\Agents\OllamaClientAdapter
HTTP Client Configuration
Both top-level clients accept HTTP options in the constructor and expose the underlying HttpClient through getHttpClient().
Error Handling
Custom exceptions include:
OllamaExceptionHttpExceptionRequiredParameterExceptionToolExecutionException
Examples
The repository includes working examples for the main library features:
examples/basic_usage.phpexamples/openai_usage.phpexamples/openai_responses.phpexamples/advanced_chat.phpexamples/agents_demo.phpexamples/simple_agent.phpexamples/tool_execution_demo.phpexamples/simple_tool_test.phpexamples/test_tool_manager.phpexamples/brasilapi.php
Custom example tools are available in:
examples/tools/CalculatorTool.phpexamples/tools/WeatherTool.php
Testing
Run the test suite with Docker:
Docker Development Environment
The included Docker image can also be used to run examples or custom commands.
Supported environment variables:
OPENAI_API_URLwith defaulthttp://localhost:11434/v1OLLAMA_API_URLwith defaulthttp://localhost:11434RUN_INTEGRATION_TESTSwith default1TEST_MODELwith defaultqwen2.5:3bTEST_VISION_MODELwith defaultqwen2.5vl:3b
Run a custom command:
Mount your local project into the container if needed:
License
MIT
Contributing
Contributions are welcome. See CONTRIBUTING.md for project guidelines.