PHP code example of swisnl / agents-sdk

1. Go to this page and download the library: Download swisnl/agents-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

swisnl / agents-sdk example snippets


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;
});

$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
);

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.';
    
    ...
}

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');

// 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]
);

// Create a connection to a local MCP server with process management
$mcpConnection = McpConnection::forProcess(
    command: 'node path/to/mcp-server.js',
    autoRestartAmount: 5
);

// Add caching support
$mcpConnection->withCache($psr6CacheImplementation)
    ->withCacheTtl(1800); // 30 minute cache

// 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]
);

$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;
});

$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";
    }
});

$orchestrator = new Orchestrator();
$orchestrator->disableTracing();

php examples/play.php

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