feat: Add OpenRouter Provider Support with Dynamic Model Loading (#8738)

* Add OpenRouter provider configuration to Add Model Form

* feat: add search functionality to model selection listbox

* Update gui/src/components/modelSelection/ModelSelectionListbox.tsx

ai suggestion

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix: update isOpenSource determination based on hugging_face_id

* Trigger CI/CD

* refactor: propery cleanup openrouter

* feat: add initialization function for OpenRouter models

- Replaced the import of openRouterModelsList with getOpenRouterModelsList.
- Added a new function `initializeOpenRouterModels` to fetch and initialize OpenRouter models from the API.
- Updated the providers object with the fetched models upon successful retrieval.
- Added error handling to reset the models list in case of a fetch failure.

* feat: enhance OpenRouter model initialization with loading placeholder and effect hook

* fix: openrouter model fetching cleanup

* fix: open router model fetching cleanup

* lint: cli

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Dallin Romney <dallinromney@gmail.com>
This commit is contained in:
Partha 2026-02-03 11:29:44 +05:30 • committed by GitHub
parent 2c1a85683c
commit 9ac154d2a0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 336 additions and 92 deletions

View file

@ -1,5 +1,5 @@
import tsParser from "@typescript-eslint/parser";
import tsPlugin from "@typescript-eslint/eslint-plugin";
import tsParser from "@typescript-eslint/parser";
import importPlugin from "eslint-plugin-import";
import unusedImports from "eslint-plugin-unused-imports";
@ -40,7 +40,7 @@ export default [
"error",
{ max: 500, skipBlankLines: true, skipComments: true },
],
complexity: ["error", { max: 20 }],
complexity: ["error", { max: 30 }],
// "max-lines-per-function": [
// "error",
// { max: 150, skipBlankLines: true, skipComments: true },

View file

@ -7,14 +7,14 @@ import { configureConsoleForHeadless } from "../init.js";
import { logger } from "../util/logger.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
import type { ReviewState } from "./review/ReviewProgress.js";
import { ReviewProgress } from "./review/ReviewProgress.js";
import type { WorkerConfig, WorkerResult } from "./review/reviewWorker.js";
import type { DiffContext } from "./review/diffContext.js";
import { computeDiffContext } from "./review/diffContext.js";
import type { ReviewResult } from "./review/renderReport.js";
import { renderReport } from "./review/renderReport.js";
import { resolveReviews } from "./review/resolveReviews.js";
import { ReviewProgress } from "./review/ReviewProgress.js";
import type { ReviewState } from "./review/ReviewProgress.js";
import type { WorkerConfig, WorkerResult } from "./review/reviewWorker.js";
import { createWorktree, cleanupWorktree } from "./review/worktree.js";
export interface ReviewOptions extends ExtendedCommandOptions {

View file

@ -6,12 +6,12 @@ import "./init.js";
import { Command } from "commander";
import { chat } from "./commands/chat.js";
import { review } from "./commands/review.js";
import { login } from "./commands/login.js";
import { logout } from "./commands/logout.js";
import { listSessionsCommand } from "./commands/ls.js";
import { remoteTest } from "./commands/remote-test.js";
import { remote } from "./commands/remote.js";
import { review } from "./commands/review.js";
import { serve } from "./commands/serve.js";
import {
handleValidationErrors,

View file

@ -183,7 +183,6 @@ function useChatHandlers(
};
}
// eslint-disable-next-line complexity
const TUIChat: React.FC<TUIChatProps> = ({
remoteUrl,
configPath,

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View file

@ -2,8 +2,9 @@ import {
CheckIcon,
ChevronUpDownIcon,
CubeIcon,
MagnifyingGlassIcon,
} from "@heroicons/react/24/outline";
import { Fragment } from "react";
import { Fragment, useEffect, useMemo, useState } from "react";
import {
Listbox,
ListboxButton,
@ -19,6 +20,34 @@ interface ModelSelectionListboxProps {
setSelectedProvider: (val: DisplayInfo) => void;
topOptions?: DisplayInfo[];
otherOptions?: DisplayInfo[];
searchPlaceholder?: string;
}
/**
* Simple fuzzy search algorithm
* Returns a score based on how well the query matches the text
*/
function fuzzyScore(query: string, text: string): number {
const q = query.toLowerCase();
const t = text.toLowerCase();
if (!q) return 1; // Empty query matches everything
if (!t) return 0;
let score = 0;
let queryIdx = 0;
let lastMatchIdx = -1;
for (let i = 0; i < t.length && queryIdx < q.length; i++) {
if (t[i] === q[queryIdx]) {
score += 1 + (lastMatchIdx === i - 1 ? 5 : 0); // Bonus for consecutive matches
lastMatchIdx = i;
queryIdx++;
}
}
// Return 0 if not all query characters were found
return queryIdx === q.length ? score / t.length : 0;
}
function ModelSelectionListbox({
@ -26,9 +55,51 @@ function ModelSelectionListbox({
setSelectedProvider,
topOptions = [],
otherOptions = [],
searchPlaceholder = "Search models...",
}: ModelSelectionListboxProps) {
const [searchQuery, setSearchQuery] = useState("");
// Clear search query when provider changes
useEffect(() => {
setSearchQuery("");
}, [selectedProvider]);
// Combine and filter options based on fuzzy search
const filteredTopOptions = useMemo(() => {
if (!searchQuery) return topOptions;
return topOptions
.map((opt) => ({
option: opt,
score: fuzzyScore(searchQuery, opt.title),
}))
.filter(({ score }) => score > 0)
.sort((a, b) => b.score - a.score)
.map(({ option }) => option);
}, [searchQuery, topOptions]);
const filteredOtherOptions = useMemo(() => {
if (!searchQuery) return otherOptions;
return otherOptions
.map((opt) => ({
option: opt,
score: fuzzyScore(searchQuery, opt.title),
}))
.filter(({ score }) => score > 0)
.sort((a, b) => b.score - a.score)
.map(({ option }) => option);
}, [searchQuery, otherOptions]);
const hasResults =
filteredTopOptions.length > 0 || filteredOtherOptions.length > 0;
return (
<Listbox value={selectedProvider} onChange={setSelectedProvider}>
<Listbox
value={selectedProvider}
onChange={(value) => {
setSelectedProvider(value);
setSearchQuery("");
}}
>
<div className="relative mb-2 mt-1">
<ListboxButton className="bg-background border-border text-foreground hover:bg-input relative m-0 grid h-full w-full cursor-pointer grid-cols-[1fr_auto] items-center rounded-lg border border-solid py-2 pl-3 pr-10 text-left focus:outline-none">
<span className="flex items-center">
@ -54,87 +125,120 @@ function ModelSelectionListbox({
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<ListboxOptions className="bg-input rounded-default absolute left-0 top-full z-10 mt-1 h-fit w-3/5 overflow-y-auto p-0 focus:outline-none [&]:!max-h-[30vh]">
{topOptions.length > 0 && (
<div className="py-1">
<div className="text-description-muted px-3 py-1 text-xs font-medium uppercase tracking-wider">
Popular
</div>
{topOptions.map((option, index) => (
<ListboxOption
key={index}
className={({ selected }: { selected: boolean }) =>
` ${selected ? "bg-list-active" : "bg-input"} hover:bg-list-active hover:text-list-active-foreground relative flex cursor-default cursor-pointer select-none items-center justify-between gap-2 p-1.5 px-3 py-2 pr-4`
}
value={option}
>
{({ selected }) => (
<>
<div className="flex items-center">
{option.title === "Autodetect" ? (
<CubeIcon className="mr-2 h-4 w-4" />
) : (
window.vscMediaUrl &&
option.icon && (
<img
src={`${window.vscMediaUrl}/logos/${option.icon}`}
className="mr-2 h-4 w-4 object-contain object-center"
/>
)
)}
<span className="text-xs">{option.title}</span>
</div>
{selected && (
<CheckIcon className="h-3 w-3" aria-hidden="true" />
)}
</>
)}
</ListboxOption>
))}
<ListboxOptions className="bg-input rounded-default absolute left-0 top-full z-10 mt-1 flex h-fit w-3/5 flex-col overflow-y-auto p-0 focus:outline-none [&]:!max-h-[30vh]">
{/* Search Box */}
<div className="border-border sticky top-0 border-b p-2">
<div className="bg-background border-border flex items-center rounded border pl-2">
<MagnifyingGlassIcon className="text-description-muted h-4 w-4" />
<input
type="text"
placeholder={searchPlaceholder}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="bg-background text-foreground placeholder-description-muted w-full border-0 px-2 py-1.5 outline-none"
onClick={(e) => e.stopPropagation()}
/>
</div>
)}
{topOptions.length > 0 && otherOptions.length > 0 && (
<div className="bg-border my-1 h-px min-h-px" />
)}
{otherOptions.length > 0 && (
<div className="py-1">
<div className="text-description-muted px-3 py-1 text-xs font-medium uppercase tracking-wider">
Additional providers
</div>
{otherOptions.map((option, index) => (
<ListboxOption
key={index}
className={({ selected }: { selected: boolean }) =>
` ${selected ? "bg-list-active" : "bg-input"} hover:bg-list-active hover:text-list-active-foreground relative flex cursor-default cursor-pointer select-none items-center justify-between gap-2 p-1.5 px-3 py-2 pr-4`
}
value={option}
>
{({ selected }) => (
<>
<div className="flex items-center">
{option.title === "Autodetect" ? (
<CubeIcon className="mr-2 h-4 w-4" />
) : (
window.vscMediaUrl &&
option.icon && (
<img
src={`${window.vscMediaUrl}/logos/${option.icon}`}
className="mr-2 h-4 w-4 object-contain object-center"
/>
)
)}
<span className="text-xs">{option.title}</span>
</div>
</div>
{selected && (
<CheckIcon className="h-3 w-3" aria-hidden="true" />
)}
</>
{/* Results */}
<div className="flex-1 overflow-y-auto">
{!hasResults ? (
<div className="text-description-muted px-3 py-4 text-center text-xs">
No models found matching "{searchQuery}"
</div>
) : (
<>
{filteredTopOptions.length > 0 && (
<div className="py-1">
<div className="text-description-muted px-3 py-1 text-xs font-medium uppercase tracking-wider">
Popular
</div>
{filteredTopOptions.map((option, index) => (
<ListboxOption
key={index}
className={({ selected }: { selected: boolean }) =>
` ${selected ? "bg-list-active" : "bg-input"} hover:bg-list-active hover:text-list-active-foreground relative flex cursor-pointer select-none items-center justify-between gap-2 p-1.5 px-3 py-2 pr-4`
}
value={option}
>
{({ selected }) => (
<>
<div className="flex items-center">
{option.title === "Autodetect" ? (
<CubeIcon className="mr-2 h-4 w-4" />
) : (
window.vscMediaUrl &&
option.icon && (
<img
src={`${window.vscMediaUrl}/logos/${option.icon}`}
className="mr-2 h-4 w-4 object-contain object-center"
/>
)
)}
<span className="text-xs">{option.title}</span>
</div>
{selected && (
<CheckIcon
className="h-3 w-3"
aria-hidden="true"
/>
)}
</>
)}
</ListboxOption>
))}
</div>
)}
{filteredTopOptions.length > 0 &&
filteredOtherOptions.length > 0 && (
<div className="bg-border my-1 h-px min-h-px" />
)}
</ListboxOption>
))}
</div>
)}
{filteredOtherOptions.length > 0 && (
<div className="py-1">
<div className="text-description-muted px-3 py-1 text-xs font-medium uppercase tracking-wider">
Additional providers
</div>
{filteredOtherOptions.map((option, index) => (
<ListboxOption
key={index}
className={({ selected }: { selected: boolean }) =>
` ${selected ? "bg-list-active" : "bg-input"} hover:bg-list-active hover:text-list-active-foreground relative flex cursor-pointer select-none items-center justify-between gap-2 p-1.5 px-3 py-2 pr-4`
}
value={option}
>
{({ selected }) => (
<>
<div className="flex items-center">
{option.title === "Autodetect" ? (
<CubeIcon className="mr-2 h-4 w-4" />
) : (
window.vscMediaUrl &&
option.icon && (
<img
src={`${window.vscMediaUrl}/logos/${option.icon}`}
className="mr-2 h-4 w-4 object-contain object-center"
/>
)
)}
<span className="text-xs">{option.title}</span>
</div>
{selected && (
<CheckIcon
className="h-3 w-3"
aria-hidden="true"
/>
)}
</>
)}
</ListboxOption>
))}
</div>
)}
</>
)}
</div>
</ListboxOptions>
</Transition>
</div>

View file

@ -9,6 +9,7 @@ import { IdeMessengerContext } from "../context/IdeMessenger";
import { completionParamsInputs } from "../pages/AddNewModel/configs/completionParamsInputs";
import { DisplayInfo } from "../pages/AddNewModel/configs/models";
import {
initializeOpenRouterModels,
ProviderInfo,
providers,
} from "../pages/AddNewModel/configs/providers";
@ -40,6 +41,11 @@ export function AddModelForm({
const formMethods = useForm();
const ideMessenger = useContext(IdeMessengerContext);
// Initialize OpenRouter models from API on component mount
useEffect(() => {
void initializeOpenRouterModels();
}, []);
const popularProviderTitles = [
providers["openai"]?.title || "",
providers["anthropic"]?.title || "",
@ -47,6 +53,7 @@ export function AddModelForm({
providers["gemini"]?.title || "",
providers["azure"]?.title || "",
providers["ollama"]?.title || "",
providers["openrouter"]?.title || "",
];
const allProviders = Object.entries(providers)
@ -63,11 +70,10 @@ export function AddModelForm({
.filter((provider) => !popularProviderTitles.includes(provider.title))
.sort((a, b) => a.title.localeCompare(b.title));
const selectedProviderApiKeyUrl = selectedModel.params.model.startsWith(
"codestral",
)
? CODESTRAL_URL
: selectedProvider.apiKeyUrl;
const selectedProviderApiKeyUrl =
selectedModel && selectedModel.params.model.startsWith("codestral")
? CODESTRAL_URL
: selectedProvider.apiKeyUrl;
function isDisabled() {
if (selectedProvider.downloadUrl) {
@ -149,6 +155,7 @@ export function AddModelForm({
}}
topOptions={popularProviders}
otherOptions={otherProviders}
searchPlaceholder="Search providers..."
/>
<span className="text-description-muted mt-1 block text-xs">
Don't see your provider?{" "}

View file

@ -0,0 +1,77 @@
import { ModelProviderTags } from "../../../components/modelSelection/utils";
import { ModelPackage } from "./models";
interface OpenRouterModel {
id: string;
name: string;
description: string;
context_length: number;
hugging_face_id: string;
}
function convertOpenRouterModelToPackage(model: OpenRouterModel): ModelPackage {
return {
title: model.name,
description: model.description,
refUrl: `https://openrouter.ai/models/${model.id}`,
params: {
title: model.name,
model: model.id,
contextLength: model.context_length,
},
isOpenSource: !!model.hugging_face_id,
tags: [ModelProviderTags.RequiresApiKey],
providerOptions: ["openrouter"],
icon: "openrouter.png",
};
}
async function fetchOpenRouterModelsFromAPI(): Promise<OpenRouterModel[]> {
const OPENROUTER_API_URL = "https://openrouter.ai/api/v1/models";
try {
const response = await fetch(OPENROUTER_API_URL);
if (!response.ok) {
throw new Error(
`Failed to fetch OpenRouter models: ${response.status} ${response.statusText}`,
);
}
const data = await response.json();
if (!data.data || !Array.isArray(data.data)) {
console.warn("Invalid OpenRouter models data structure from API");
return [];
}
return data.data;
} catch (error) {
console.error("Error fetching OpenRouter models from API:", error);
return [];
}
}
export async function getOpenRouterModelsList(): Promise<ModelPackage[]> {
const models: { [key: string]: ModelPackage } = {};
const apiModels = await fetchOpenRouterModelsFromAPI();
apiModels.forEach((model: OpenRouterModel) => {
if (!model.id || !model.name) {
console.warn("Skipping model with missing id or name", model);
return;
}
// Create a unique key from the model id (replace slashes and dots with underscores)
const key = model.id.replace(/[\/.]/g, "_");
try {
models[key] = convertOpenRouterModelToPackage(model);
} catch (error) {
console.error(`Failed to convert model ${model.id}:`, error);
}
});
return Object.values(models);
}

View file

@ -3,6 +3,7 @@ import { ModelProviderTags } from "../../../components/modelSelection/utils";
import { completionParamsInputs } from "./completionParamsInputs";
import type { ModelPackage } from "./models";
import { models } from "./models";
import { getOpenRouterModelsList } from "./openRouterModel";
export interface InputDescriptor {
inputType: HTMLInputTypeAttribute;
@ -40,6 +41,39 @@ const openSourceModels = Object.values(models).filter(
({ isOpenSource }) => isOpenSource,
);
// Initialize OpenRouter models placeholder with a loading placeholder
const OPENROUTER_LOADING_PLACEHOLDER: ModelPackage = {
title: "Loading models...",
description: "Fetching available models from OpenRouter",
params: {
model: "placeholder",
contextLength: 0,
},
isOpenSource: false,
};
let openRouterModelsList: ModelPackage[] = [OPENROUTER_LOADING_PLACEHOLDER];
/**
* Initialize OpenRouter models by fetching from the API
* This should be called once when the component mounts
*/
export async function initializeOpenRouterModels() {
try {
const models = await getOpenRouterModelsList();
if (models.length > 0) {
openRouterModelsList = models;
// Update the providers object with the fetched models
if (providers.openrouter) {
providers.openrouter.packages = openRouterModelsList;
}
}
} catch (error) {
console.error("Failed to initialize OpenRouter models:", error);
// Keep placeholder on error so the UI doesn't break
}
}
export const apiBaseInput: InputDescriptor = {
inputType: "text",
key: "apiBase",
@ -178,6 +212,29 @@ export const providers: Partial<Record<string, ProviderInfo>> = {
],
apiKeyUrl: "https://console.anthropic.com/account/keys",
},
openrouter: {
title: "OpenRouter",
provider: "openrouter",
description:
"OpenRouter provides access to a variety of LLMs including open-source and proprietary models.",
longDescription: `To get started with OpenRouter, sign up for an account at [openrouter.ai](https://openrouter.ai/) and obtain your API key from the dashboard.`,
icon: "openrouter.png",
tags: [ModelProviderTags.RequiresApiKey],
refPage: "openrouter",
apiKeyUrl: "https://openrouter.ai/settings/keys",
collectInputFor: [
{
inputType: "text",
key: "apiKey",
label: "API Key",
placeholder: "Enter your OpenRouter API key",
required: true,
},
...completionParamsInputsConfigs,
],
packages: openRouterModelsList,
},
moonshot: {
title: "Moonshot",
provider: "moonshot",