PHP code example of crademaker / openrouter-wrapper

1. Go to this page and download the library: Download crademaker/openrouter-wrapper 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/ */

    

crademaker / openrouter-wrapper example snippets




declare(strict_types=1);

use Crademaker\OpenRouter\OpenRouterClient;
use Crademaker\OpenRouter\OpenRouterConfig;

    appName: 'My Composer App',
);

$client = new OpenRouterClient($config);

$response = $client->chatCompletions([
    'model' => 'openai/gpt-4o-mini',
    'messages' => [
        ['role' => 'system', 'content' => 'You are a helpful assistant.'],
        ['role' => 'user', 'content' => 'Say hello in one sentence.'],
    ],
]);

echo $response['choices'][0]['message']['content'] ?? 'No response';



declare(strict_types=1);

use Crademaker\OpenRouter\OpenRouterClient;
use Crademaker\OpenRouter\OpenRouterConfig;

$client = new OpenRouterClient(
    new OpenRouterConfig(
        apiKey: $_ENV['OPENROUTER_API_KEY'] ?? '',
        appUrl: 'https://your-app.example',
        appName: 'Your Project Name',
    ),
);



declare(strict_types=1);

use Crademaker\OpenRouter\DTO\Request\InferenceRequest;
use Crademaker\OpenRouter\DTO\Request\ListModelsQuery;
use Crademaker\OpenRouter\DTO\Request\ChatMessage;
use Crademaker\OpenRouter\Enum\ChatRole;
use Crademaker\OpenRouter\Enum\ModelCategory;
use Crademaker\OpenRouter\Enum\SupportedParameter;

$inference = $client->chatCompletionsDto(
    InferenceRequest::chat('openai/gpt-4o-mini', [
        ChatMessage::withRole(ChatRole::USER, 'Hello'),
    ]),
);

echo $inference->firstText() ?? 'No response';
echo $inference->firstChoice()?->message()?->role() ?? '';

$models = $client->listModelsDto(ListModelsQuery::create(
    category: ModelCategory::GENERAL,
    supportedParameters: SupportedParameter::TOOLS,
));
echo (string) $models->count();
echo $models->modelObjects()[0]->id();

$response = $client->requestRaw('POST', '/responses', [
    'model' => 'openai/gpt-4o-mini',
    'input' => 'stream test',
    'stream' => true,
]);

$rawSse = (string) $response->getBody();