PHP code example of raulast / macro-llm-php

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

    

raulast / macro-llm-php example snippets


if ($llm->providers()->get('gemini') instanceof \MacroLLM\Contract\EmbeddingProviderInterface) {
    $response = $llm->embed(new EmbeddingRequest(['Hello world']), 'gemini');
}

use MacroLLM\MacroLLM;
use MacroLLM\Config\Config;
use MacroLLM\Message\InternalRequest;
use MacroLLM\Message\InternalMessage;

$llm = MacroLLM::standalone(Config::fromArray([
    'default_provider' => 'openai',
    'providers' => [
        'openai' => ['api_key' => '${OPENAI_API_KEY}', 'default_model' => 'gpt-4o'],
    ],
]));

$response = $llm->chat(new InternalRequest([
    InternalMessage::user('Hello, world!'),
]));

echo $response->content;

use MacroLLM\Integration\Laravel\MacroLLMFacade as LLM;
use MacroLLM\Message\InternalRequest;
use MacroLLM\Message\InternalMessage;

$response = LLM::chat(new InternalRequest([
    InternalMessage::system('You are a helpful assistant.'),
    InternalMessage::user('What is Laravel?'),
]));

use MacroLLM\Message\InternalRequest;
use MacroLLM\Message\InternalMessage;

$response = Http::openai(new InternalRequest([
    InternalMessage::user('Explain macros in PHP.'),
]));

foreach ($llm->stream(new InternalRequest([InternalMessage::user('Tell me a story.')])) as $chunk) {
    if ($chunk->finished) {
        echo "\n\n[done — {$chunk->response->usage->totalTokens} tokens]\n";
        break;
    }
    echo $chunk->delta;
    flush();
}

// Fetches live model list from the provider's own API (may make HTTP request)
$models = $llm->models('openai');
// → ['gpt-4o', 'gpt-4o-mini', 'o1', 'o3', ...]

$models = $llm->models('anthropic');
// → ['claude-opus-4-5', 'claude-sonnet-4-5', ...]

// OpenCode Zen fetches from GET /zen/go/v1/models
$models = $llm->models('opencode-zen-go');
// → ['deepseek-v3-0324', 'glm-z1-flash', 'kimi-k2', ...]

// Ollama and llama.cpp reflect locally installed / loaded models
$models = $llm->models('ollama');
// → ['llama3.2:latest', 'codellama:7b', ...]

// Via the Facade (Laravel)
$models = \MacroLLM\Integration\Laravel\MacroLLMFacade::models('gemini');

// Via provider directly (no HTTP needed for provider object access)
$provider = $llm->providers()->get('groq');
$models = $provider->getModels();

use MacroLLM\Tool\ToolDefinition;

$llm->tools()->register(new ToolDefinition(
    name: 'get_weather',
    description: 'Get the current weather for a city.',
    parameters: [
        'type' => 'object',
        'properties' => [
            'city' => ['type' => 'string', 'description' => 'City name'],
        ],
        '

use MacroLLM\Skill\Skill;

// Inline skill — returns a GenericSkill (no subclassing needed)
$translatorSkill = Skill::create(
    name: 'translator',
    systemPrompt: 'You are a professional translator. Always respond in the target language.',
    tools: ['detect_language', 'translate_text'],
);

$llm->skills()->register($translatorSkill);

// From DB record — also returns a GenericSkill
$skillData = $db->find('skills', 1);
$skill = Skill::fromArray($skillData);
$llm->skills()->register($skill);

// Dynamic skill via subclass
class SupportSkill extends Skill
{
    public function __construct(private string $product) {}
    public function getName(): string { return 'support'; }
    public function getSystemPrompt(): string {
        return "You are a support agent for {$this->product}. Be helpful and concise.";
    }
}

use MacroLLM\Message\InternalMessage;

// Simplest — base64 by default (works with all vision-capable providers)
$response = $llm->chat(new InternalRequest([
    InternalMessage::userWithImage('What is in this image?', '/path/to/photo.jpg'),
]));

// From URL — auto-fetched and encoded to base64
$response = $llm->chat(new InternalRequest([
    InternalMessage::userWithImage('Describe this', 'https://example.com/img.jpg'),
]));

use MacroLLM\Message\ResponseFormat;

$response = $llm->chat(new InternalRequest(
    messages: [InternalMessage::user('Extract: name and age from "Ana is 28 years old"')],
    responseFormat: ResponseFormat::jsonSchema('person', [
        'type'       => 'object',
        'properties' => ['name' => ['type' => 'string'], 'age' => ['type' => 'integer']],
        '

use MacroLLM\Agent\AgentConfig;
use MacroLLM\Agent\AgentStep;
use MacroLLM\Agent\AgentStepType;

$agent = $llm->agent(new AgentConfig(
    provider: 'openai',
    maxIterations: 10,
    onStep: function (AgentStep $step): void {
        echo match ($step->type) {
            AgentStepType::LlmResponse    => "[{$step->iteration}] LLM responded with tool calls\n",
            AgentStepType::ToolCall       => "[{$step->iteration}] → calling {$step->toolCall->name}\n",
            AgentStepType::ToolResult     => "[{$step->iteration}] ← result: " . json_encode($step->toolResult->content) . "\n",
            AgentStepType::FinalResponse  => "[{$step->iteration}] Final: {$step->response->content}\n",
        };
    },
));

$response = $agent->run('What is the weather in Buenos Aires?');

use MacroLLM\Agent\AgentConfig;
use MacroLLM\Agent\Memory\InMemoryMemory;
use MacroLLM\Agent\Memory\SqliteMemory;
use MacroLLM\Agent\Memory\RedisMemory;
use MacroLLM\Agent\Memory\FileMemory;

$agent = $llm->agent(new AgentConfig(
    provider: 'anthropic',
    memory: new InMemoryMemory(),       // in-process
    // memory: new SqliteMemory('/var/data/conv.db', 'user-123'),  // persistent, no deps
    // memory: new RedisMemory($redis, 'user-123', ttl: 3600),     // redis
    // memory: new FileMemory('/tmp/conv-user-123.json'),          // file
));

$agent->run('My name is Ana.');
$response = $agent->run('What is my name?');
echo $response->content; // "Your name is Ana."

use MacroLLM\Orchestration\Orchestrator;
use MacroLLM\Orchestration\RoutingStrategy;
use MacroLLM\Orchestration\ErrorStrategy;

$orchestrator = new Orchestrator(
    routing: RoutingStrategy::Parallel,
    errorStrategy: ErrorStrategy::Continue,
);

$orchestrator->addAgent('researcher', $llm->agent(new AgentConfig(
    provider: 'openai',
    systemPrompt: 'Research and summarize information.',
)));

$orchestrator->addAgent('writer', $llm->agent(new AgentConfig(
    provider: 'anthropic',
    systemPrompt: 'Write engaging content based on research.',
)));

$result = $orchestrator->dispatch('Write an article about PHP 8.1 fibers.');

foreach ($result->outcomes as $outcome) {
    echo "Agent {$outcome->agentName} ({$outcome->durationMs}ms):\n";
    echo $outcome->response?->content . "\n\n";
}

use MacroLLM\Mcp\MCPClient;

$mcp = new MCPClient($llm->tools());
$mcp->connect('filesystem', 'http://localhost:3001', auth: 'my-token');
// Tools now available as "filesystem/read_file", "filesystem/write_file", etc.

$agent = $llm->agent(new AgentConfig(provider: 'openai'));
$response = $agent->run('Read the contents of /tmp/notes.txt');

// In a Laravel route or controller:
use MacroLLM\Mcp\MCPServer;
use MacroLLM\Mcp\MCPServerMiddleware;

// Mount as PSR-15 middleware on /mcp
$app->middleware(MCPServerMiddleware::class);
// External MCP clients can now call tools/list and tools/call on /mcp

use MacroLLM\Integration\Slim\MacroLLMSlimExtension;
use MacroLLM\Message\InternalRequest;
use MacroLLM\Message\InternalMessage;
use Slim\Factory\AppFactory;
use DI\Container;

// PHP-DI container (composer  '/config/macro-llm.php');
$extension->register();

// Use MacroLLM inside a route
$app->get('/chat', function ($request, $response) use ($container) {
    $llm    = $container->get(\MacroLLM\MacroLLM::class);
    $result = $llm->chat(new InternalRequest([
        InternalMessage::user('Hello!'),
    ]));
    $response->getBody()->write($result->content ?? '');
    return $response;
});

$app->run();

// your-project/config/macro-llm.php
return [
    'default_provider' => 'ollama',
    'providers' => [
        'ollama' => [
            'api_key'       => getenv('OLLAMA_API_KEY') ?: 'local',
            'default_model' => 'llama3.2',
            'base_url'      => 'http://localhost:11434/v1',
        ],
    ],
];
bash
composer 
bash
php artisan vendor:publish --tag=macro-llm-config