PHP code example of utopia-php / agents

1. Go to this page and download the library: Download utopia-php/agents 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/ */

    

utopia-php / agents example snippets




use Utopia\Agents\Agent;
use Utopia\Agents\Message;
use Utopia\Agents\Roles\User;
use Utopia\Agents\Conversation;
use Utopia\Agents\Adapters\OpenAI;

// Create an agent with OpenAI
$adapter = new OpenAI('your-api-key', OpenAI::MODEL_GPT_4_TURBO);
$agent = new Agent($adapter);

// Create a user
$user = new User('user-1', 'John');

// Start a conversation
$conversation = new Conversation($agent);
$conversation
    ->message($user, new Message('What is artificial intelligence?'))
    ->send();

use Utopia\Agents\Adapters\OpenAI;

$openai = new OpenAI(
    apiKey: 'your-api-key',
    model: OpenAI::MODEL_GPT_4_TURBO,
    maxTokens: 2048,
    temperature: 0.7
);

use Utopia\Agents\Adapters\Anthropic;

$anthropic = new Anthropic(
    apiKey: 'your-api-key',
    model: Anthropic::MODEL_CLAUDE_3_HAIKU,
    maxTokens: 2048,
    temperature: 0.7
);

use Utopia\Agents\Adapters\Deepseek;

$deepseek = new Deepseek(
    apiKey: 'your-api-key',
    model: Deepseek::MODEL_DEEPSEEK_CHAT,
    maxTokens: 2048,
    temperature: 0.7
);

use Utopia\Agents\Adapters\Perplexity;

$perplexity = new Perplexity(
    apiKey: 'your-api-key',
    model: Perplexity::MODEL_SONAR,
    maxTokens: 2048,
    temperature: 0.7
);

use Utopia\Agents\Adapters\XAI;

$xai = new XAI(
    apiKey: 'your-api-key',
    model: XAI::MODEL_GROK_3_MINI,
    maxTokens: 2048,
    temperature: 0.7
);

use Utopia\Agents\Adapters\OpenRouter;
use Utopia\Agents\Adapters\OpenRouter\Models as OpenRouterModels;

$openrouter = new OpenRouter(
    apiKey: 'your-api-key',
    model: OpenRouterModels::MODEL_OPENAI_GPT_4O,
    maxTokens: 2048,
    temperature: 0.7,
    httpReferer: 'https://your-app.example',
    xTitle: 'Your App Name'
);

use Utopia\Agents\Roles\User;
use Utopia\Agents\Roles\Assistant;
use Utopia\Agents\Message;

// Create a conversation with system instructions
$agent = new Agent($adapter);
$agent->setInstructions([
    'description' => 'You are a helpful assistant that can answer questions and help with tasks.',
    'tone' => 'friendly and helpful',
]);

// Initialize roles
$user = new User('user-1'); 
$assistant = new Assistant('assistant-1');

$conversation = new Conversation($agent);
$conversation
    ->message($user, new Message('Hello!'))
    ->message($assistant, new Message('Hi! How can I help you today?'))
    ->message($user, new Message('What is the capital of France?'));

// Add a user message with attachments
$conversation->message(
    $user,
    new Message('Please summarize this screenshot'),
    [new Message($imageBinaryContent)]
);

// Send and get response
$response = $conversation->send();

use Utopia\Agents\Agent;
use Utopia\Agents\Conversation;
use Utopia\Agents\Adapters\OpenAI;
use Utopia\Agents\Message;
use Utopia\Agents\Roles\User;

$agent = new Agent(new OpenAI('your-api-key', OpenAI::MODEL_GPT_4O));
$conversation = new Conversation($agent);
$user = new User('user-1', 'John');

$conversation
    ->listen(function (string $chunk): void {
        echo $chunk; // render partial output as soon as it is received
    })
    ->message($user, new Message('Explain vector databases in one paragraph.'));

$final = $conversation->send(); // final, complete assistant message

use Utopia\Agents\Agent;
use Utopia\Agents\Conversation;
use Utopia\Agents\Adapters\OpenAI;
use Utopia\Agents\Message;
use Utopia\Agents\Roles\User;

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

$agent = new Agent(new OpenAI('your-api-key', OpenAI::MODEL_GPT_4O));
$conversation = new Conversation($agent);
$user = new User('user-1', 'John');

$conversation
    ->listen(function (string $chunk): void {
        // Send each token delta as an SSE frame
        echo 'data: '.json_encode(['delta' => $chunk], JSON_UNESCAPED_UNICODE)."\n\n";

        if (function_exists('ob_flush')) {
            @ob_flush();
        }
        flush();
    })
    ->message($user, new Message('Write a short release note for today''s deployment.'));

$final = $conversation->send();

// Optional terminal event with complete text
echo 'event: done'."\n";
echo 'data: '.json_encode(['message' => $final->getContent()], JSON_UNESCAPED_UNICODE)."\n\n";
echo 'data: [DONE]'."\n\n";
flush();

use Utopia\Agents\Message;

// Message content is always text
$textMessage = new Message('Hello, how are you?');

// Attachments are binary payloads (for example images)
$imageMessage = new Message($imageBinaryContent);
$mimeType = $imageMessage->getMimeType(); // Get the MIME type of the image

// Attach image to a text prompt
$message = (new Message('Describe this image'))->addAttachment($imageMessage);

use Utopia\Agents\Conversation;
use Utopia\Agents\Message;
use Utopia\Agents\Roles\User;

$conversation = new Conversation($agent);
$user = new User('user-1', 'John');

// 1) Attach a single image in the same turn
$conversation->message(
    $user,
    new Message('What is shown here?'),
    [new Message(file_get_contents(__DIR__.'/images/screenshot.png'))]
);

// 2) Attach multiple images in one turn
$conversation->message(
    $user,
    new Message('Compare these two images and list differences.'),
    [
        new Message(file_get_contents(__DIR__.'/images/before.png')),
        new Message(file_get_contents(__DIR__.'/images/after.png')),
    ]
);

// 3) Build and reuse a message object with attachments
$prompt = (new Message('Extract visible text from this receipt'))
    ->addAttachment(new Message(file_get_contents(__DIR__.'/images/receipt.jpg')));

$conversation->message($user, $prompt);



use Utopia\Agents\Adapters\OpenAI;

class StrictOpenAI extends OpenAI
{
    public function getMaxAttachmentsPerMessage(): ?int
    {
        return 3;
    }

    public function getMaxAttachmentBytes(): ?int
    {
        return 2_000_000;
    }

    public function getMaxTotalAttachmentBytes(): ?int
    {
        return 6_000_000;
    }

    /**
     * @return list<string>|null
     */
    public function getAllowedAttachmentMimeTypes(): ?array
    {
        return ['image/png', 'image/jpeg'];
    }
}

use Utopia\Agents\Schema\Schema;
use Utopia\Agents\Schema\SchemaObject;

$object = new SchemaObject();
$object->addProperty('location', [
    'type' => SchemaObject::TYPE_STRING,
    'description' => 'The city and state, e.g. San Francisco, CA',
]);

$schema = new Schema(
    name: 'get_weather',
    description: 'Get the current weather in a given location in well structured JSON',
    object: $object,
    
bash
composer