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\Roles\User;
use Utopia\Agents\Messages\Text;
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 Text('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_SONNET,
    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_2_LATEST,
    maxTokens: 2048,
    temperature: 0.7
);

use Utopia\Agents\Roles\User;
use Utopia\Agents\Roles\Assistant;
use Utopia\Agents\Messages\Text;

// 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 Text('Hello!'))
    ->message($assistant, new Text('Hi! How can I help you today?'))
    ->message($user, new Text('What is the capital of France?'));

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

use Utopia\Agents\Messages\Text;
use Utopia\Agents\Messages\Image;

// Text message
$textMessage = new Text('Hello, how are you?');

// Image message
$imageMessage = new Image($imageBinaryContent);
$mimeType = $imageMessage->getMimeType(); // Get the MIME type of the image
bash
composer