swisnl/agents-sdk
Composer 安装命令:
composer require swisnl/agents-sdk
包简介
A lightweight yet powerful framework for building multi-agent workflows inspired by the OpenAi Agents SDK
关键字:
README 文档
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
- Serialize and deserialize conversations for state management
- Connect to external tools using the Model Context Protocol (MCP)
- Use both the Responses- and Chat Completions API
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 );
Using Chat Completions API
By default, agents will use the Responses API. You can control what endpoint the agent will use by giving it the correct Transporter.
Note that Native Tools are only supported by the Responses API.
$agent = new Agent( name: 'Agent Name', transporter: new ChatCompletionsTransporter() ); // Or $agent->withTransporter(new ChatCompletionsTransporter());
Stateful vs stateless Responses API
The default ResponsesTransporter runs the Responses API in stateless mode: every request sends store: false plus include: ['reasoning.encrypted_content'], and the full conversation — including reasoning items with their encrypted blob — is replayed on each turn. Nothing is retained on OpenAI's servers, which makes it safe for ZDR-compliant orgs and keeps conversations replayable past the ~30 day server-state expiry.
If you need the legacy behaviour (server-side state via previous_response_id, smaller request payloads, no encrypted reasoning returned to the client), opt in explicitly:
use Swis\Agents\Transporters\StatefulResponsesTransporter; $agent = new Agent( name: 'Agent Name', transporter: new StatefulResponsesTransporter(), );
A conversation captured in stateful mode cannot be resumed statelessly without losing reasoning continuity — stateful runs never see the encrypted reasoning items.
Defining Tools
Tools are capabilities that agents can use to perform actions. To create a custom tool:
- Extend the
Toolclass - Define parameters using attributes
- Implement the
__invokemethod 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 */] ]); } }
// Examples with array and object parameters class ProductSearchTool extends Tool { #[ToolParameter('The product categories to search in.', itemsType: 'string')] public array $categories = []; #[ToolParameter('Filters to apply to the search.', objectClass: SearchFilter:class)] public object $filters; protected ?string $toolDescription = 'Searches for products with advanced filtering.'; ... } class SearchFilter { #[ToolParameter('The property to filter.'), Required] public string $property; #[ToolParameter('The value of the filter.'), Required] public string $values;; #[ToolParameter('The operator of the filter.')] #[Enum(['eq', 'neq', 'gt', 'lt', 'gte', 'lte'])] public string $operator = 'eq'; protected ?string $toolDescription = 'Searches for products with advanced filtering.'; ... }
MCP Tool Support
The SDK supports the Model Context Protocol (MCP) through the McpConnection class, allowing you to integrate external data sources and tools with your agents.
What is MCP?
MCP (Model Context Protocol) is an open protocol that enables seamless integration between LLM applications and external data sources and tools. It provides a standardized way to connect LLMs with the context they need, offering:
- Dynamic discovery of available tools
- Tool filtering to restrict which tools are available to agents
- Remote tool invocation
Using MCP
It's recommended to use the swis/mcp-client package for MCP client implementations.
composer require swisnl/mcp-client
To use MCP tools with your agents:
use Swis\Agents\Agent; use Swis\Agents\Mcp\McpConnection; use Swis\McpClient\Client; // Create an MCP connection $mcpConnection = McpConnection::forSse('http://localhost:3000'); // Optionally restrict which tools are available $mcpConnection->withTools('calculator', 'weather'); // Optionally expose MCP tools under alternate names for the agent $mcpConnection->withAlternateToolNames([ 'get_current_weather' => 'weather', ]); // Optionally expose MCP tools with alternate descriptions for the agent $mcpConnection->withAlternateToolDescriptions([ 'get_current_weather' => 'Get current weather conditions by location.', ]); // Create an agent with the MCP connection $agent = new Agent( name: 'Assistant with MCP Tools', description: 'An assistant that can use external MCP tools', mcpConnections: [$mcpConnection] );
Advanced MCP Usage
The SDK supports advanced MCP features:
- Tool caching with PSR-6 compatible cache adapters
- Process-based MCP clients for local tools
- Metadata that can be sent with each MCP call
Example with a local MCP server:
// Create a connection to a local MCP server with process management [$mcpConnection, $process] = McpConnection::forProcess( command: 'node path/to/mcp-server.js', autoRestartAmount: 5 ); // Add caching support $mcpConnection->withCache($psr6CacheImplementation) ->withCacheTtl(1800); // 30 minute cache // Add metadata that will be sent with each MCP call $mcpConnection->withMeta(['traceparent' => '0000-0000-00-00x']);
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.
swisnl/agents-sdk 适用场景与选型建议
swisnl/agents-sdk 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10.92k 次下载、GitHub Stars 达 23, 最近一次更新时间为 2025 年 03 月 20 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「swisnl」 「agents-sdk」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 swisnl/agents-sdk 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 swisnl/agents-sdk 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 swisnl/agents-sdk 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Fixture handler for Guzzle 6+
Model Context Protocol client implementation in PHP
PHP server integration for AG-UI - standardized AI agent frontend communication via Server-Sent Events
NDW Melvin API client
Laravel lti provider
Integrates spatie/laravel-activitylog with Filament
统计信息
- 总下载量: 10.92k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 23
- 点击次数: 10
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-03-20