-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add OpenRouter adapter #27
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| #!/usr/bin/env php | ||
| <?php | ||
|
|
||
| /** | ||
| * Fetches the OpenRouter model catalog and generates Models.php | ||
| * | ||
| * Usage: php scripts/sync-openrouter-models.php [output-path] | ||
| * | ||
| * Only models from curated providers get named constants. | ||
| * The full catalog is available via the MODELS array. | ||
| */ | ||
| $endpoint = getenv('OPENROUTER_MODELS_ENDPOINT') ?: 'https://openrouter.ai/api/v1/models'; | ||
| $defaultOutput = __DIR__.'/../src/Agents/Adapters/OpenRouter/Models.php'; | ||
| $outputPath = $argv[1] ?? $defaultOutput; | ||
|
|
||
| // Providers whose models get named class constants | ||
| $curatedProviders = [ | ||
| 'anthropic', | ||
| 'openai', | ||
| 'google', | ||
| 'meta-llama', | ||
| 'deepseek', | ||
| 'mistralai', | ||
| 'x-ai', | ||
| ]; | ||
|
|
||
| // Skip model IDs matching these patterns (old/niche variants) | ||
| $skipPatterns = [ | ||
| '/:extended$/', // extended-context variants | ||
| '/:free$/', // free-tier duplicates | ||
| '/:beta$/', // beta tags | ||
| '/-\d{4}-\d{2}-\d{2}/', // date-pinned snapshots (e.g. gpt-4o-2024-08-06) | ||
| '/-\d{4}$/', // short date pins (e.g. gpt-4-0314) | ||
| '/-\d{4}-preview/', // date preview variants (e.g. gpt-4-1106-preview) | ||
| '/gpt-3\.5/', // legacy GPT-3.5 models | ||
| '/gpt-4-turbo/', // legacy GPT-4 turbo | ||
| '/-preview$/', // generic preview suffixes | ||
| ]; | ||
|
|
||
| $headers = ['Accept: application/json']; | ||
|
|
||
| $apiKey = getenv('OPENROUTER_API_KEY') ?: getenv('LLM_KEY_OPENROUTER'); | ||
| if ($apiKey) { | ||
| $headers[] = "Authorization: Bearer {$apiKey}"; | ||
| } | ||
|
|
||
| $context = stream_context_create([ | ||
| 'http' => [ | ||
| 'header' => implode("\r\n", $headers), | ||
| 'timeout' => 30, | ||
| ], | ||
| ]); | ||
|
|
||
| $response = file_get_contents($endpoint, false, $context); | ||
| if ($response === false) { | ||
| fwrite(STDERR, "Failed to fetch OpenRouter models from {$endpoint}\n"); | ||
| exit(1); | ||
| } | ||
|
|
||
| $payload = json_decode($response, true); | ||
| if (! is_array($payload) || ! isset($payload['data']) || ! is_array($payload['data'])) { | ||
| fwrite(STDERR, "OpenRouter models response did not include a data array\n"); | ||
| exit(1); | ||
| } | ||
|
|
||
| $models = array_filter($payload['data'], fn ($m) => is_array($m) && isset($m['id']) && is_string($m['id']) && $m['id'] !== ''); | ||
| $models = array_values($models); | ||
| usort($models, fn ($a, $b) => strcmp($a['id'], $b['id'])); | ||
|
|
||
| if (count($models) === 0) { | ||
| fwrite(STDERR, "OpenRouter models response was empty\n"); | ||
| exit(1); | ||
| } | ||
|
|
||
| $modelIds = array_map(fn ($m) => $m['id'], $models); | ||
|
|
||
| /** | ||
| * Convert a model ID to a PHP constant name (MODEL_PROVIDER_NAME). | ||
| */ | ||
| function toConstantName(string $id): string | ||
| { | ||
| $name = strtoupper($id); | ||
| $name = preg_replace('/[^A-Z0-9]+/', '_', $name); | ||
| $name = preg_replace('/_+/', '_', $name); | ||
| $name = trim($name, '_'); | ||
|
|
||
| if ($name === '') { | ||
| return 'MODEL_UNKNOWN'; | ||
| } | ||
|
|
||
| return "MODEL_{$name}"; | ||
| } | ||
|
|
||
| // Build curated constants (named) and the full ID list | ||
| $curatedConstants = []; // name => id | ||
| $usedNames = []; | ||
|
|
||
| foreach ($modelIds as $id) { | ||
| $provider = explode('/', $id, 2)[0]; | ||
|
|
||
| if (! in_array($provider, $curatedProviders, true)) { | ||
| continue; | ||
| } | ||
|
|
||
| // Skip date-pinned snapshots, free/beta/extended variants | ||
| $dominated = false; | ||
| foreach ($skipPatterns as $pattern) { | ||
| if (preg_match($pattern, $id)) { | ||
| $dominated = true; | ||
| break; | ||
| } | ||
| } | ||
| if ($dominated) { | ||
| continue; | ||
| } | ||
|
|
||
| $name = toConstantName($id); | ||
|
|
||
| if (isset($usedNames[$name])) { | ||
| $name .= '_'.strtoupper(substr(sha1($id), 0, 8)); | ||
| } | ||
|
|
||
| $usedNames[$name] = true; | ||
| $curatedConstants[$name] = $id; | ||
| } | ||
|
|
||
| // Generate PHP | ||
| $now = gmdate('Y-m-d\TH:i:s\Z'); | ||
| $totalCount = count($modelIds); | ||
| $curatedCount = count($curatedConstants); | ||
|
|
||
| $lines = []; | ||
| $lines[] = '<?php'; | ||
| $lines[] = ''; | ||
| $lines[] = 'namespace Utopia\Agents\Adapters\OpenRouter;'; | ||
| $lines[] = ''; | ||
| $lines[] = '/**'; | ||
| $lines[] = ' * Generated by scripts/sync-openrouter-models.php — do not edit by hand.'; | ||
| $lines[] = " * Source: {$endpoint}"; | ||
| $lines[] = " * Synced at: {$now}"; | ||
| $lines[] = " * Named constants: {$curatedCount} (curated providers)"; | ||
| $lines[] = " * Total models: {$totalCount}"; | ||
| $lines[] = ' */'; | ||
| $lines[] = 'final class Models'; | ||
| $lines[] = '{'; | ||
|
|
||
| // Named constants grouped by provider | ||
| $currentProvider = ''; | ||
| foreach ($curatedConstants as $name => $id) { | ||
| $provider = explode('/', $id, 2)[0]; | ||
| if ($provider !== $currentProvider) { | ||
| if ($currentProvider !== '') { | ||
| $lines[] = ''; | ||
| } | ||
| $lines[] = " // {$provider}"; | ||
| $currentProvider = $provider; | ||
| } | ||
| $safeId = str_replace("'", "\\'", $id); | ||
| $lines[] = " public const {$name} = '{$safeId}';"; | ||
| } | ||
|
|
||
| $lines[] = ''; | ||
| // No DEFAULT_MODEL — the default is set in OpenRouter::__construct() | ||
|
|
||
| // Full MODELS array as plain strings | ||
| $lines[] = ''; | ||
| $lines[] = ' /**'; | ||
| $lines[] = ' * Full model catalog. Use model IDs directly or via named constants above.'; | ||
| $lines[] = ' *'; | ||
| $lines[] = ' * @var list<string>'; | ||
| $lines[] = ' */'; | ||
| $lines[] = ' public const MODELS = ['; | ||
| foreach ($modelIds as $id) { | ||
| $safeId = str_replace("'", "\\'", $id); | ||
| $lines[] = " '{$safeId}',"; | ||
| } | ||
| $lines[] = ' ];'; | ||
| $lines[] = '}'; | ||
| $lines[] = ''; | ||
|
|
||
| $dir = dirname($outputPath); | ||
| if (! is_dir($dir)) { | ||
| mkdir($dir, 0755, true); | ||
| } | ||
|
|
||
| file_put_contents($outputPath, implode("\n", $lines)); | ||
|
|
||
| echo "Wrote {$curatedCount} named constants + {$totalCount} model IDs to {$outputPath}\n"; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.