<?php
use Cognesy\Polyglot\Inference\Inference;
use Cognesy\Http\Exceptions\HttpRequestException;
function withModelFallback(array $models, string $prompt): string {
$inference = new Inference();
$lastException = null;
foreach ($models as $model) {
try {
return $inference->with(
messages: $prompt,
model: $model
)->get();
} catch (HttpRequestException $e) {
$lastException = $e;
echo "Model '$model' failed: " . $e->getMessage() . "\n";
echo "Trying next model...\n";
}
}
throw new \Exception("All models failed. Last error: " .
($lastException ? $lastException->getMessage() : "Unknown error"));
}
// Try advanced models first, then fall back to simpler ones
$models = ['gpt-4o', 'gpt-4o-mini', 'gpt-3.5-turbo'];
try {
$response = withModelFallback($models, "What is the capital of France?");
echo "Response: $response\n";
} catch (\Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
// @doctest id="598f"