1. Go to this page and download the library: Download eatzy/openrouter-php-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/ */
eatzy / openrouter-php-sdk example snippets
use OpenRouterSDK\Services\ChatService;
use OpenRouterSDK\Models\Chat\ChatCompletionRequest;
use OpenRouterSDK\Models\Chat\ChatMessage;
use OpenRouterSDK\Support\Configuration;
use GuzzleHttp\Client;
use OpenRouterSDK\Http\Client\GuzzleHttpClient;
// Configure the SDK
$config = new Configuration([
'api_key' => 'your-openrouter-api-key',
'default_model' => 'openai/gpt-4'
]);
// Create HTTP client
$httpClient = new GuzzleHttpClient(
new Client(['timeout' => 30]),
$config
);
// Create chat service
$service = new ChatService($httpClient, $config);
// Simple chat
$response = $service->simpleChat('What is the capital of France?');
echo $response; // "The capital of France is Paris."
// Advanced usage with full control
$request = new ChatCompletionRequest(
messages: [
ChatMessage::system('You are a helpful assistant.'),
ChatMessage::user('Explain quantum computing in simple terms.')
],
model: 'openai/gpt-4',
temperature: 0.7,
max_tokens: 150
);
$response = $service->create($request);
echo $response->getContent();
// Streaming responses
$service->stream($request, function ($chunk) {
if (isset($chunk['choices'][0]['delta']['content'])) {
echo $chunk['choices'][0]['delta']['content'];
flush();
}
});
use OpenRouterSDK\Laravel\Facade\OpenRouter;
use OpenRouterSDK\Models\Chat\ChatMessage;
use OpenRouterSDK\Models\Chat\ChatCompletionRequest;
use OpenRouterSDK\Models\Chat\ResponseFormat;
use Illuminate\Support\Facades\Log;
// Simple chat
$response = OpenRouter::simpleChat('Write a haiku about programming.');
echo $response;
// Advanced usage with full configuration
$request = new ChatCompletionRequest(
messages: [
ChatMessage::system('You are a professional marketing copywriter.'),
ChatMessage::user('Generate a compelling product description for a smart coffee maker.')
],
model: 'openai/gpt-4',
temperature: 0.8,
max_tokens: 300,
top_p: 0.9,
frequency_penalty: 0.5,
presence_penalty: 0.5
);
$response = OpenRouter::create($request);
echo $response->getContent();
// Streaming with real-time output
OpenRouter::stream($request, function ($chunk) {
if (isset($chunk['choices'][0]['delta']['content'])) {
echo $chunk['choices'][0]['delta']['content'];
flush();
ob_flush(); // Ensure output is sent immediately
}
});
// Laravel integration with error handling
try {
$response = OpenRouter::create(new ChatCompletionRequest(
messages: [ChatMessage::user('Process customer inquiry')],
timeout: 15 // Override default timeout
));
// Store in database or cache
DB::table('ai_responses')->insert([
'content' => $response->getContent(),
'model' => $response->getModel(),
'created_at' => now()
]);
} catch (Exception $e) {
Log::error('OpenRouter API error', [
'message' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return response()->json([
'error' => 'Service temporarily unavailable',
'retry_after' => 30
], 503);
}
// Queue job example
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProcessAIQuery implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $prompt;
protected $userId;
public function __construct($prompt, $userId)
{
$this->prompt = $prompt;
$this->userId = $userId;
}
public function handle()
{
try {
$response = OpenRouter::simpleChat($this->prompt);
// Save result
AiResult::create([
'user_id' => $this->userId,
'prompt' => $this->prompt,
'response' => $response,
'processed_at' => now()
]);
} catch (Exception $e) {
// Log error and potentially retry
Log::error('AI Query Processing Failed', [
'prompt' => $this->prompt,
'user_id' => $this->userId,
'error' => $e->getMessage()
]);
// Optionally re-queue with delay
if ($this->attempts() < 3) {
$this->release(60); // Retry after 60 seconds
}
}
}
}