swisnl / agents-sdk
A lightweight yet powerful framework for building multi-agent workflows inspired by the OpenAi Agents SDK
Requires
- php: ^8.2
- ext-json: *
- illuminate/support: ^12.1
- openai-php/client: ^0.10.3
- ramsey/uuid: ^4.7
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.73
- guzzlehttp/guzzle: ^7.3
- laravel/prompts: ^0.3.5
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^11.0 || ^12.0
- swisnl/php-http-fixture-client: ^3.1
- symfony/console: ^7.2
- vlucas/phpdotenv: ^5.6
- dev-master
- 0.2.1
- 0.2.0
- 0.1.1
- 0.1.0
- dev-feature/mcp-tool-support
- dev-refactor/remove-illuminate-support-dependency
- dev-test/add-missing-test-for-conversation-serializer
- dev-build/remove-http-factory-guzzle-dependency
- dev-docs/correct-link-to-bio
- dev-feature/lint-command
- dev-feature/ownablemessage-getowner
- dev-fix/update-readme-and-changelog
This package is auto-updated.
Last update: 2025-03-31 15:05:49 UTC
README
A lightweight yet powerful framework for building multi-agent workflows in PHP, inspired by the OpenAI Agents SDK.
Overview
Agents SDK provides an elegant abstraction for creating AI agent systems in PHP, allowing you to:
- Build specialized agents for different tasks
- Connect agents using a handoff mechanism
- Define and use custom tools for external operations
- Stream LLM responses for real-time interactions
- Monitor agent behavior with observers and traces
The SDK is designed to be flexible, extensible, and easy to use while providing a robust foundation for building complex multi-agent based systems.
Installation
composer require swisnl/agents-sdk
Basic Usage
Here's a simple example of creating and running an Agent that can use a Tool for retrieving weather information:
use Swis\Agents\Agent; use Swis\Agents\Orchestrator; use Swis\Agents\Tool; use Swis\Agents\Tool\Required; use Swis\Agents\Tool\ToolParameter; // Define a custom tool class WeatherTool extends Tool { #[ToolParameter('The name of the city.'), Required] public string $city; protected ?string $toolDescription = 'Gets the current weather by city.'; public function __invoke(): ?string { // Implementation to fetch weather data return "Current weather in {$this->city}: Sunny, 22°C"; } } // Create an agent with the tool $agent = new Agent( name: 'Weather Assistant', description: 'Provides weather information', instruction: 'You help users with weather-related questions. Use the WeatherTool to get accurate data.', tools: [new WeatherTool()] ); // Set up the orchestrator $orchestrator = new Orchestrator(); // Process a user message $orchestrator->withUserInstruction('What\'s the weather like in Amsterdam?'); // Run the agent and get the response $response = $orchestrator->run($agent); echo $response; // Or use streaming for real-time responses $orchestrator->runStreamed($agent, function ($token) { echo $token; });
Creating Agents
Agents are the core components of the SDK. They encapsulate a specific role or capability and can use tools to perform actions.
$agent = new Agent( name: 'Agent Name', // Required: Unique identifier for the agent description: 'Description', // Optional: Brief description of the agent's capabilities instruction: 'System prompt', // Optional: Detailed instructions for the agent tools: [$tool1, $tool2], // Optional: Array of tools the agent can use handoffs: [$otherAgent] // Optional: Other agents this agent can hand off to );
Defining Tools
Tools are capabilities that agents can use to perform actions. To create a custom tool:
- Extend the
Tool
class - Define parameters using attributes
- Implement the
__invoke
method with your tool's logic
class SearchTool extends Tool { #[ToolParameter('The search query.'), Required] public string $query; #[ToolParameter('The number of results to return.')] public int $limit = 5; protected ?string $toolDescription = 'Searches for information.'; public function __invoke(): ?string { // Implementation logic here return json_encode([ 'results' => [/* search results */] ]); } }
Multi-Agent Systems
The SDK supports creating systems of specialized agents that can hand off tasks to each other:
// Create specialized agents $weatherAgent = new Agent( name: 'Weather Agent', // ... configuration ); $travelAgent = new Agent( name: 'Travel Agent', // ... configuration handoffs: [$weatherAgent] // Travel agent can hand off to Weather agent ); // Main triage agent $triageAgent = new Agent( name: 'Triage Agent', description: 'Routes user requests to the appropriate specialized agent', handoffs: [$weatherAgent, $travelAgent] );
Orchestration
The Orchestrator
class manages the conversation flow and agent execution:
$orchestrator = new Orchestrator(); // Add a user message $orchestrator->withUserInstruction("I need help with planning a trip to Amsterdam"); // Run with a specific agent $response = $orchestrator->run($triageAgent); // Or stream the response $orchestrator->runStreamed($triageAgent, function ($token) { echo $token; });
Observability
The SDK provides an observer pattern to monitor agent behavior:
$orchestrator->withAgentObserver(new class extends AgentObserver { public function beforeHandoff(AgentInterface $agent, AgentInterface $handoffToAgent, RunContext $context): void { echo "Handing off from {$agent->name()} to {$handoffToAgent->name()}\n"; } public function onToolCall(AgentInterface $agent, Tool $tool, ToolCall $toolCall, RunContext $context): void { echo "Agent {$agent->name()} called tool: {$toolCall->tool}\n"; } });
Tracing
The SDK includes built-in tracing support using OpenAI Tracing format by default. This helps with debugging and monitoring agent execution.
Disabling Tracing
You can disable tracing in two ways:
- On a per-orchestrator basis:
$orchestrator = new Orchestrator(); $orchestrator->disableTracing();
- Globally via environment variable:
AGENTS_SDK_DISABLE_TRACING=true
Disabling tracing can be useful in production environments or when you don't need the debugging information.
Example Implementations
The repository includes examples for common use cases:
CustomerServiceAgent
: A multi-agent system for customer service with handoffsWeatherAgent
: A simple agent that fetches weather information
Run the examples using:
php examples/play.php
Conversation Serialization
The SDK provides a way to serialize and deserialize conversation state, allowing you to continue conversations at a later time:
use Swis\Agents\Helpers\ConversationSerializer; // After running some conversation with an orchestrator $data = ConversationSerializer::serializeFromOrchestrator($orchestrator); saveToStorage($data); // Your storage implementation // Later, when you want to continue the conversation $data = retrieveFromStorage(); // Your retrieval implementation // Create a new orchestrator with the serialized conversation $orchestrator = new Orchestrator(); $orchestrator->withContextFromData($data); $agent = new Agent(/* Create your agent */); // Continue the conversation $orchestrator->withUserInstruction('New message'); $response = $orchestrator->run($agent);
Requirements
- PHP 8.2 or higher
- OpenAI API key for LLM access (or other OpenAI compatible API)
- Composer for dependency management
Testing
The SDK includes a test suite built with PHPUnit. To run the tests:
# Install dependencies composer install # Run the tests composer run test
Test Structure
- Unit Tests: Test individual components in isolation
- Integration Tests: Test the full agent workflow with actual API calls (skipped by default)
Changelog
Please see CHANGELOG for more information on what has changed recently.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
This package is open-sourced software licensed under the MIT license.
This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.
SWIS ❤️ Open Source
SWIS is a web agency from Leiden, the Netherlands. We love working with open source software.