Merge pull request #12046 from RomneyDa/dynamic-model-fetching
feat: fetch provider models dynamically and fix isOpenSource pollution
This commit is contained in:
commit
9f9ded770a
21 changed files with 708 additions and 208 deletions
|
|
@ -70,14 +70,20 @@ export function addModel(
|
|||
config.models = [];
|
||||
}
|
||||
|
||||
const capabilities: string[] = [];
|
||||
if (model.capabilities?.tools) capabilities.push("tool_use");
|
||||
if (model.capabilities?.uploadImage) capabilities.push("image_input");
|
||||
|
||||
const desc: ModelConfig = {
|
||||
name: model.title,
|
||||
provider: model.provider,
|
||||
model: model.model,
|
||||
apiKey: model.apiKey,
|
||||
apiBase: model.apiBase,
|
||||
contextLength: model.contextLength,
|
||||
maxStopWords: model.maxStopWords,
|
||||
defaultCompletionOptions: model.completionOptions,
|
||||
...(capabilities.length > 0 ? { capabilities } : {}),
|
||||
};
|
||||
config.models.push(desc);
|
||||
return config;
|
||||
|
|
|
|||
14
core/core.ts
14
core/core.ts
|
|
@ -17,6 +17,7 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
|
|||
import DocsService from "./indexing/docs/DocsService";
|
||||
import { countTokens } from "./llm/countTokens";
|
||||
import Lemonade from "./llm/llms/Lemonade";
|
||||
import { fetchModels } from "./llm/fetchModels";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
|
||||
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
|
||||
|
|
@ -1227,6 +1228,19 @@ export class Core {
|
|||
const isValid = setMdmLicenseKey(licenseKey);
|
||||
return isValid;
|
||||
});
|
||||
|
||||
on("models/fetch", async (msg) => {
|
||||
try {
|
||||
return await fetchModels(
|
||||
msg.data.provider,
|
||||
msg.data.apiKey,
|
||||
msg.data.apiBase,
|
||||
);
|
||||
} catch (error: any) {
|
||||
void this.ide.showToast("error", error.message);
|
||||
return [];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async handleToolCall(toolCall: ToolCall) {
|
||||
|
|
|
|||
1
core/index.d.ts
vendored
1
core/index.d.ts
vendored
|
|
@ -1724,6 +1724,7 @@ export interface JSONModelDescription {
|
|||
maxStopWords?: number;
|
||||
template?: TemplateType;
|
||||
completionOptions?: BaseCompletionOptions;
|
||||
capabilities?: ModelCapability;
|
||||
systemMessage?: string;
|
||||
requestOptions?: RequestOptions;
|
||||
cacheBehavior?: CacheBehavior;
|
||||
|
|
|
|||
|
|
@ -152,7 +152,7 @@ const MODEL_SUPPORTS_IMAGES: RegExp[] = [
|
|||
/pixtral/,
|
||||
/llama-?3\.2/,
|
||||
/llama-?4/, // might use something like /llama-?(?:[4-9](?:\.\d+)?|\d{2,}(?:\.\d+)?)/ for forward compat, if needed
|
||||
/\bgemma-?3(?!n)/, // gemma3 supports vision, but gemma3n doesn't!
|
||||
/\bgemma-?[34](?!n)/, // gemma3/gemma4 support vision, but gemma3n doesn't!
|
||||
/\b(pali|med)gemma/,
|
||||
/qwen(.*)vl/,
|
||||
/mistral-small/,
|
||||
|
|
|
|||
258
core/llm/fetchModels.ts
Normal file
258
core/llm/fetchModels.ts
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
import { LLMClasses, llmFromProviderAndOptions } from "./llms/index.js";
|
||||
|
||||
export interface FetchedModel {
|
||||
name: string;
|
||||
modelId?: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
contextLength?: number;
|
||||
maxTokens?: number;
|
||||
supportsTools?: boolean;
|
||||
}
|
||||
|
||||
const OLLAMA_EXCLUDED_CAPABILITIES = ["vision", "audio", "embedding"];
|
||||
|
||||
const OLLAMA_ICON_MAP: Record<string, string> = {
|
||||
llama: "meta.png",
|
||||
codellama: "meta.png",
|
||||
"phind-codellama": "meta.png",
|
||||
deepseek: "deepseek.png",
|
||||
deepcoder: "deepseek.png",
|
||||
deepscaler: "deepseek.png",
|
||||
mistral: "mistral.png",
|
||||
mixtral: "mistral.png",
|
||||
codestral: "mistral.png",
|
||||
devstral: "mistral.png",
|
||||
magistral: "mistral.png",
|
||||
mathstral: "mistral.png",
|
||||
ministral: "mistral.png",
|
||||
gemma: "gemini.png",
|
||||
codegemma: "gemini.png",
|
||||
"gemini-": "gemini.png",
|
||||
qwen: "qwen.png",
|
||||
codeqwen: "qwen.png",
|
||||
qwq: "qwen.png",
|
||||
command: "cohere.png",
|
||||
aya: "cohere.png",
|
||||
granite: "ibm.png",
|
||||
nemotron: "nvidia.png",
|
||||
kimi: "moonshot.png",
|
||||
glm: "zai.svg",
|
||||
codegeex: "zai.svg",
|
||||
wizardcoder: "wizardlm.png",
|
||||
wizardlm: "wizardlm.png",
|
||||
"wizard-": "wizardlm.png",
|
||||
olmo: "allenai.png",
|
||||
tulu: "allenai.png",
|
||||
firefunction: "fireworks.png",
|
||||
"gpt-oss": "openai.png",
|
||||
};
|
||||
|
||||
function getOllamaIcon(modelName: string): string {
|
||||
if (OLLAMA_ICON_MAP[modelName]) {
|
||||
return OLLAMA_ICON_MAP[modelName];
|
||||
}
|
||||
let bestMatch = "";
|
||||
for (const prefix of Object.keys(OLLAMA_ICON_MAP)) {
|
||||
if (modelName.startsWith(prefix) && prefix.length > bestMatch.length) {
|
||||
bestMatch = prefix;
|
||||
}
|
||||
}
|
||||
return bestMatch ? OLLAMA_ICON_MAP[bestMatch] : "ollama.png";
|
||||
}
|
||||
|
||||
async function fetchOllamaModels(): Promise<FetchedModel[]> {
|
||||
try {
|
||||
const response = await fetch("https://ollama.com/library");
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch Ollama library: ${response.status}`);
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
const models: FetchedModel[] = [];
|
||||
const items = html.split("x-test-model class=");
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (let i = 1; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const nameMatch = item.match(/href="\/library\/([^"]+)"/);
|
||||
if (!nameMatch) continue;
|
||||
const name = nameMatch[1];
|
||||
if (seen.has(name)) continue;
|
||||
|
||||
const capabilities: string[] = [];
|
||||
const capRegex = /x-test-capability[^>]*>([^<]+)</g;
|
||||
let capMatch;
|
||||
while ((capMatch = capRegex.exec(item)) !== null) {
|
||||
capabilities.push(capMatch[1].trim().toLowerCase());
|
||||
}
|
||||
if (
|
||||
capabilities.some((cap) => OLLAMA_EXCLUDED_CAPABILITIES.includes(cap))
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sizes: string[] = [];
|
||||
const sizeRegex = /x-test-size[^>]*>([^<]+)</g;
|
||||
let sizeMatch;
|
||||
while ((sizeMatch = sizeRegex.exec(item)) !== null) {
|
||||
sizes.push(sizeMatch[1].trim());
|
||||
}
|
||||
|
||||
const descMatch = item.match(/<p class="max-w-lg[^"]*">([^<]+)</);
|
||||
const sizeLabel = sizes.length > 0 ? ` (${sizes.join(", ")})` : "";
|
||||
const description = descMatch
|
||||
? descMatch[1].trim()
|
||||
: `Ollama model: ${name}${sizeLabel}`;
|
||||
|
||||
seen.add(name);
|
||||
models.push({
|
||||
name,
|
||||
description,
|
||||
icon: getOllamaIcon(name),
|
||||
supportsTools: capabilities.includes("tools"),
|
||||
});
|
||||
}
|
||||
|
||||
return models;
|
||||
} catch (error) {
|
||||
console.error("Error fetching Ollama library models:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchOpenRouterModels(): Promise<FetchedModel[]> {
|
||||
try {
|
||||
const response = await fetch("https://openrouter.ai/api/v1/models");
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch OpenRouter models: ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (!data.data || !Array.isArray(data.data)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return data.data
|
||||
.filter((m: any) => m.id && m.name)
|
||||
.map((m: any) => ({
|
||||
name: m.name,
|
||||
modelId: m.id,
|
||||
icon: "openrouter.png",
|
||||
contextLength: m.context_length,
|
||||
maxTokens: m.top_provider?.max_completion_tokens,
|
||||
supportsTools: (m.supported_parameters ?? []).includes("tools"),
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error fetching OpenRouter models:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchAnthropicModels(apiKey?: string): Promise<FetchedModel[]> {
|
||||
const response = await fetch(
|
||||
"https://api.anthropic.com/v1/models?limit=100",
|
||||
{
|
||||
headers: {
|
||||
"x-api-key": apiKey ?? "",
|
||||
"anthropic-version": "2023-06-01",
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch Anthropic models: ${response.status}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
return (data.data ?? []).map((m: any) => ({
|
||||
name: m.display_name ?? m.id,
|
||||
modelId: m.id,
|
||||
icon: "anthropic.png",
|
||||
contextLength: m.max_input_tokens,
|
||||
maxTokens: m.max_tokens,
|
||||
supportsTools: true,
|
||||
}));
|
||||
}
|
||||
|
||||
async function fetchGeminiModels(
|
||||
apiKey?: string,
|
||||
apiBase?: string,
|
||||
): Promise<FetchedModel[]> {
|
||||
const base = apiBase || "https://generativelanguage.googleapis.com/v1beta/";
|
||||
const url = new URL("models", base);
|
||||
url.searchParams.set("key", apiKey ?? "");
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch Gemini models: ${response.status}`);
|
||||
}
|
||||
const data = await response.json();
|
||||
return (data.models ?? [])
|
||||
.filter((m: any) => {
|
||||
const id: string = m.name?.replace("models/", "") ?? "";
|
||||
const methods: string[] = m.supportedGenerationMethods ?? [];
|
||||
return (
|
||||
!id.startsWith("gemini-2.0") &&
|
||||
!id.startsWith("gemma-") && // Gemma models are supported through Ollama, not the Gemini API
|
||||
!id.startsWith("nano-banana") &&
|
||||
!id.startsWith("lyria") &&
|
||||
methods.includes("generateContent") &&
|
||||
!methods.includes("embedContent") &&
|
||||
!methods.includes("predict") &&
|
||||
!methods.includes("predictLongRunning") &&
|
||||
!methods.includes("bidiGenerateContent") &&
|
||||
!id.includes("tts") &&
|
||||
!id.includes("image") &&
|
||||
!id.includes("robotics") &&
|
||||
!id.includes("computer-use")
|
||||
);
|
||||
})
|
||||
.map((m: any) => ({
|
||||
name: m.displayName ?? m.name?.replace("models/", ""),
|
||||
modelId: m.name?.replace("models/", ""),
|
||||
icon: "gemini.png",
|
||||
contextLength: m.inputTokenLimit,
|
||||
maxTokens: m.outputTokenLimit,
|
||||
supportsTools: true,
|
||||
}));
|
||||
}
|
||||
|
||||
async function fetchProviderModelsViaListModels(
|
||||
provider: string,
|
||||
apiKey?: string,
|
||||
apiBase?: string,
|
||||
): Promise<FetchedModel[]> {
|
||||
try {
|
||||
const cls = LLMClasses.find((llm) => llm.providerName === provider);
|
||||
const defaultApiBase = cls?.defaultOptions?.apiBase;
|
||||
|
||||
const llm = llmFromProviderAndOptions(provider, {
|
||||
apiKey,
|
||||
apiBase: apiBase || defaultApiBase,
|
||||
model: "",
|
||||
});
|
||||
const modelIds = await llm.listModels();
|
||||
return modelIds.map((id) => ({ name: id }));
|
||||
} catch (error: any) {
|
||||
throw new Error(
|
||||
`Failed to fetch models for ${provider}: ${error?.message ?? error}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchModels(
|
||||
provider: string,
|
||||
apiKey?: string,
|
||||
apiBase?: string,
|
||||
): Promise<FetchedModel[]> {
|
||||
switch (provider) {
|
||||
case "ollama":
|
||||
return fetchOllamaModels();
|
||||
case "openrouter":
|
||||
return fetchOpenRouterModels();
|
||||
case "anthropic":
|
||||
return fetchAnthropicModels(apiKey);
|
||||
case "gemini":
|
||||
return fetchGeminiModels(apiKey, apiBase);
|
||||
default:
|
||||
return fetchProviderModelsViaListModels(provider, apiKey, apiBase);
|
||||
}
|
||||
}
|
||||
|
|
@ -105,6 +105,12 @@ describe("BaseLLM", () => {
|
|||
baseLLM.model = "google/gemma-3-270m";
|
||||
expect(baseLLM.supportsImages()).toBe(true);
|
||||
|
||||
baseLLM.model = "gemma4:31b";
|
||||
expect(baseLLM.supportsImages()).toBe(true);
|
||||
|
||||
baseLLM.model = "google/gemma-4-31b-it";
|
||||
expect(baseLLM.supportsImages()).toBe(true);
|
||||
|
||||
baseLLM.model = "foo/paligemma-custom-100";
|
||||
expect(baseLLM.supportsImages()).toBe(true);
|
||||
|
||||
|
|
|
|||
|
|
@ -1048,7 +1048,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
this.providerName === "openai" &&
|
||||
this._llmOptions.useResponsesApi !== false &&
|
||||
typeof (this as any)._streamResponses === "function" &&
|
||||
(this as any).isOSeriesOrGpt5Model(options.model)
|
||||
(this as any).isOSeriesOrGpt5PlusModel(options.model)
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -5,30 +5,38 @@ describe("OpenAI", () => {
|
|||
const openai = new OpenAI({
|
||||
model: "o3-mini",
|
||||
});
|
||||
expect(openai.isOSeriesOrGpt5Model("o4-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5Model("o3-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5Model("o1-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5Model("o1")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5Model("o3")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o4-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o3-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o1-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o1")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o3")).toBeTruthy();
|
||||
|
||||
// artificially correct samples for future models
|
||||
expect(openai.isOSeriesOrGpt5Model("o5-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5Model("o6")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5Model("o77")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5Model("o54-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o5-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o6")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o77")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("o54-mini")).toBeTruthy();
|
||||
|
||||
// gpt-5+ models
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-5")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-5.4")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-5.4-mini")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-5.4-pro")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-6")).toBeTruthy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-7-turbo")).toBeTruthy();
|
||||
});
|
||||
test("should identify incorrect o-series models", () => {
|
||||
const openai = new OpenAI({
|
||||
model: "o3-mini",
|
||||
});
|
||||
expect(openai.isOSeriesOrGpt5Model("gpt-o4-mini")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5Model("gpt-4.5")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5Model("gpt-4.1")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-o4-mini")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-4.5")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("gpt-4.1")).toBeFalsy();
|
||||
|
||||
// artificially wrong samples
|
||||
expect(openai.isOSeriesOrGpt5Model("os1")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5Model("so1")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5Model("ao31")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5Model("1os")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("os1")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("so1")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("ao31")).toBeFalsy();
|
||||
expect(openai.isOSeriesOrGpt5PlusModel("1os")).toBeFalsy();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -218,8 +218,8 @@ class OpenAI extends BaseLLM {
|
|||
return model;
|
||||
}
|
||||
|
||||
public isOSeriesOrGpt5Model(model?: string): boolean {
|
||||
return !!model && (!!model.match(/^o[0-9]+/) || model.includes("gpt-5"));
|
||||
public isOSeriesOrGpt5PlusModel(model?: string): boolean {
|
||||
return !!model && (!!model.match(/^o[0-9]+/) || !!model.match(/gpt-[5-9]/));
|
||||
}
|
||||
|
||||
private isFireworksAiModel(model?: string): boolean {
|
||||
|
|
@ -284,7 +284,7 @@ class OpenAI extends BaseLLM {
|
|||
finalOptions.stop = options.stop?.slice(0, this.getMaxStopWords());
|
||||
|
||||
// OpenAI o1-preview and o1-mini or o3-mini:
|
||||
if (this.isOSeriesOrGpt5Model(options.model)) {
|
||||
if (this.isOSeriesOrGpt5PlusModel(options.model)) {
|
||||
// a) use max_completion_tokens instead of max_tokens
|
||||
finalOptions.max_completion_tokens = options.maxTokens;
|
||||
finalOptions.max_tokens = undefined;
|
||||
|
|
@ -400,7 +400,7 @@ class OpenAI extends BaseLLM {
|
|||
) {
|
||||
if (!this.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.json",
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.yaml",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -440,7 +440,7 @@ class OpenAI extends BaseLLM {
|
|||
body.stop = body.stop?.slice(0, this.getMaxStopWords());
|
||||
|
||||
// OpenAI o1-preview and o1-mini or o3-mini:
|
||||
if (this.isOSeriesOrGpt5Model(body.model)) {
|
||||
if (this.isOSeriesOrGpt5PlusModel(body.model)) {
|
||||
// a) use max_completion_tokens instead of max_tokens
|
||||
body.max_completion_tokens = body.max_tokens;
|
||||
body.max_tokens = undefined;
|
||||
|
|
@ -573,7 +573,7 @@ class OpenAI extends BaseLLM {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<ChatMessage> {
|
||||
if (!this.isOSeriesOrGpt5Model(options.model)) {
|
||||
if (!this.isOSeriesOrGpt5PlusModel(options.model)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -624,7 +624,7 @@ class OpenAI extends BaseLLM {
|
|||
signal: AbortSignal,
|
||||
options: CompletionOptions,
|
||||
): Promise<ChatMessage | ChatMessage[]> {
|
||||
if (!this.isOSeriesOrGpt5Model(options.model)) {
|
||||
if (!this.isOSeriesOrGpt5PlusModel(options.model)) {
|
||||
// Minimal draft: only handle supported models for now
|
||||
return { role: "assistant", content: "" };
|
||||
}
|
||||
|
|
@ -694,13 +694,14 @@ class OpenAI extends BaseLLM {
|
|||
});
|
||||
|
||||
const data = await response.json();
|
||||
return data.data.map((m: any) => m.id);
|
||||
const models = Array.isArray(data) ? data : (data.data ?? []);
|
||||
return models.map((m: any) => m.id);
|
||||
}
|
||||
|
||||
private _getEmbedEndpoint() {
|
||||
if (!this.apiBase) {
|
||||
throw new Error(
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.json",
|
||||
"No API base URL provided. Please set the 'apiBase' option in config.yaml",
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
it("should return true for Gemma models", () => {
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/gemma")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/gemma3")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/gemma4")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true for O3 models", () => {
|
||||
|
|
@ -62,6 +63,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/GPT-4-turbo")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/Gemma3")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/openai/Gemma4")).toBe(true);
|
||||
expect(supportsFn("ownerSlug/packageSlug/gemini/GEMINI-pro")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
@ -107,6 +109,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
it("should return true for Gemma models", () => {
|
||||
expect(supportsFn("gemma")).toBe(true);
|
||||
expect(supportsFn("gemma3")).toBe(true);
|
||||
expect(supportsFn("gemma4")).toBe(true);
|
||||
});
|
||||
|
||||
it("should return undefined for unsupported models", () => {
|
||||
|
|
@ -118,6 +121,7 @@ describe("PROVIDER_TOOL_SUPPORT", () => {
|
|||
expect(supportsFn("GPT-4-turbo")).toBe(true);
|
||||
expect(supportsFn("O3-preview")).toBe(true);
|
||||
expect(supportsFn("Gemma3")).toBe(true);
|
||||
expect(supportsFn("Gemma4")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -14,8 +14,13 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
}
|
||||
} catch (e) {}
|
||||
|
||||
return ["claude", "gpt-4", "o3", "gemini", "gemma"].some((part) =>
|
||||
model.toLowerCase().startsWith(part),
|
||||
const lower = model.toLowerCase();
|
||||
return (
|
||||
lower.startsWith("claude") ||
|
||||
!!lower.match(/^gpt-[4-9]/) ||
|
||||
!!lower.match(/^o[1-9]/) ||
|
||||
lower.startsWith("gemini") ||
|
||||
lower.startsWith("gemma")
|
||||
);
|
||||
},
|
||||
anthropic: (model) => {
|
||||
|
|
@ -29,28 +34,16 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
},
|
||||
azure: (model) => {
|
||||
const lower = model.toLowerCase();
|
||||
if (
|
||||
lower.startsWith("gpt-4") ||
|
||||
lower.startsWith("gpt-5") ||
|
||||
lower.startsWith("gpt-4.1") ||
|
||||
lower.startsWith("o1") ||
|
||||
lower.startsWith("o3") ||
|
||||
lower.startsWith("o4")
|
||||
)
|
||||
return true;
|
||||
if (lower.match(/^gpt-[4-9]/) || lower.match(/^o[1-9]/)) return true;
|
||||
return false;
|
||||
},
|
||||
openai: (model) => {
|
||||
const lower = model.toLowerCase();
|
||||
// https://platform.openai.com/docs/guides/function-calling#models-supporting-function-calling
|
||||
if (
|
||||
lower.startsWith("gpt-4") ||
|
||||
lower.startsWith("gpt-5") ||
|
||||
lower.startsWith("o1") ||
|
||||
lower.startsWith("o3") ||
|
||||
lower.startsWith("o4") ||
|
||||
lower.startsWith("codex") ||
|
||||
lower.startsWith("gpt-4.1")
|
||||
lower.match(/^gpt-[4-9]/) ||
|
||||
lower.match(/^o[1-9]/) ||
|
||||
lower.startsWith("codex")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
|
@ -107,8 +100,9 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
},
|
||||
xAI: (model) => {
|
||||
const lowerCaseModel = model.toLowerCase();
|
||||
return ["grok-3", "grok-4", "grok-4-1", "grok-code"].some((val) =>
|
||||
lowerCaseModel.includes(val),
|
||||
return (
|
||||
!!lowerCaseModel.match(/grok-[3-9]/) ||
|
||||
lowerCaseModel.includes("grok-code")
|
||||
);
|
||||
},
|
||||
bedrock: (model) => {
|
||||
|
|
@ -331,19 +325,14 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
}
|
||||
|
||||
const supportedPrefixes = [
|
||||
"openai/gpt-3.5",
|
||||
"openai/gpt-4",
|
||||
"openai/gpt-5",
|
||||
"openai/o1",
|
||||
"openai/o3",
|
||||
"openai/o4",
|
||||
"openai/gpt-",
|
||||
"openai/codex",
|
||||
"openai/gpt-oss",
|
||||
"anthropic/claude",
|
||||
"microsoft/phi-3",
|
||||
"google/gemini-flash-1.5",
|
||||
"google/gemini-2",
|
||||
"google/gemini-3",
|
||||
"google/gemma-4",
|
||||
"google/gemini-pro",
|
||||
"x-ai/grok",
|
||||
"qwen/qwen3",
|
||||
|
|
@ -376,6 +365,11 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
}
|
||||
}
|
||||
|
||||
// OpenAI o-series (o1, o3, o4, ...)
|
||||
if (baseModel.match(/^openai\/o[1-9]/)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const specificModels = [
|
||||
"qwen/qwq-32b",
|
||||
"qwen/qwen-2.5-72b-instruct",
|
||||
|
|
@ -412,13 +406,7 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
|
||||
// Check for common tool-supporting model patterns
|
||||
const toolSupportingPatterns = [
|
||||
"gpt-4",
|
||||
"gpt-5",
|
||||
"o1",
|
||||
"o3",
|
||||
"o4",
|
||||
"claude-3",
|
||||
"claude-4",
|
||||
"claude",
|
||||
"sonnet",
|
||||
"opus",
|
||||
"haiku",
|
||||
|
|
@ -435,11 +423,15 @@ export const PROVIDER_TOOL_SUPPORT: Record<string, (model: string) => boolean> =
|
|||
"deepseek",
|
||||
];
|
||||
|
||||
return toolSupportingPatterns.some((pattern) => lower.includes(pattern));
|
||||
return (
|
||||
toolSupportingPatterns.some((pattern) => lower.includes(pattern)) ||
|
||||
!!lower.match(/gpt-[4-9]/) ||
|
||||
!!lower.match(/\bo[1-9]\b/)
|
||||
);
|
||||
},
|
||||
zAI: (model) => {
|
||||
const lower = model.toLowerCase();
|
||||
return lower.startsWith("glm-4") || lower.startsWith("glm-5");
|
||||
return !!lower.match(/^glm-[4-9]/);
|
||||
},
|
||||
moonshot: (model) => {
|
||||
// support moonshot models
|
||||
|
|
@ -519,14 +511,14 @@ export function isRecommendedAgentModel(modelName: string): boolean {
|
|||
[/deepseek/, /r1|reasoner/],
|
||||
[/gemini/, /2\.5/, /pro/],
|
||||
[/gemini/, /3\.1-pro|3-flash-preview/],
|
||||
[/gpt/, /-5|5\.1|5\.2/],
|
||||
[/gpt-[5-9]/],
|
||||
[/gpt-4\.1/],
|
||||
[/codex/],
|
||||
[/claude/, /sonnet/, /3\.7|3-7|-4/],
|
||||
[/claude/, /opus/, /-4/],
|
||||
[/claude/, /sonnet/, /3\.7|3-7|(?<!\d)-[4-9]/],
|
||||
[/claude/, /opus/, /(?<!\d)-[4-9]/],
|
||||
[/grok-code/],
|
||||
[/grok-4-1|grok-4\.1/],
|
||||
[/claude/, /4-5/],
|
||||
[/grok-[4-9][\.-]\d/],
|
||||
[/claude/, /[4-9]-[5-9]/],
|
||||
];
|
||||
for (const combo of recs) {
|
||||
if (combo.every((regex) => modelName.toLowerCase().match(regex))) {
|
||||
|
|
|
|||
|
|
@ -351,4 +351,17 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
"process/isBackgrounded": [{ toolCallId: string }, boolean];
|
||||
"process/killTerminalProcess": [{ toolCallId: string }, void];
|
||||
"mdm/setLicenseKey": [{ licenseKey: string }, boolean];
|
||||
"models/fetch": [
|
||||
{ provider: string; apiKey?: string; apiBase?: string },
|
||||
{
|
||||
name: string;
|
||||
modelId?: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
popular?: boolean;
|
||||
contextLength?: number;
|
||||
maxTokens?: number;
|
||||
supportsTools?: boolean;
|
||||
}[],
|
||||
];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -91,6 +91,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"process/markAsBackgrounded",
|
||||
"process/isBackgrounded",
|
||||
"process/killTerminalProcess",
|
||||
"models/fetch",
|
||||
];
|
||||
|
||||
// Message types to pass through from core to webview
|
||||
|
|
|
|||
|
|
@ -66,9 +66,9 @@ If you prefer to use an open-weight model, then the Gemma family of Models from
|
|||
schema: v1
|
||||
|
||||
models:
|
||||
- name: "Gemma 3 27B"
|
||||
- name: "Gemma 4"
|
||||
provider: "ollama"
|
||||
model: "gemma3:27b"
|
||||
model: "gemma4"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Together">
|
||||
|
|
|
|||
|
|
@ -155,7 +155,8 @@ class MessageTypes {
|
|||
"isItemTooBig",
|
||||
"process/markAsBackgrounded",
|
||||
"process/isBackgrounded",
|
||||
"process/killTerminalProcess"
|
||||
"process/killTerminalProcess",
|
||||
"models/fetch"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ interface ModelSelectionListboxProps {
|
|||
setSelectedProvider: (val: DisplayInfo) => void;
|
||||
topOptions?: DisplayInfo[];
|
||||
otherOptions?: DisplayInfo[];
|
||||
otherOptionsLabel?: string;
|
||||
searchPlaceholder?: string;
|
||||
}
|
||||
|
||||
|
|
@ -55,6 +56,7 @@ function ModelSelectionListbox({
|
|||
setSelectedProvider,
|
||||
topOptions = [],
|
||||
otherOptions = [],
|
||||
otherOptionsLabel = "Additional providers",
|
||||
searchPlaceholder = "Search models...",
|
||||
}: ModelSelectionListboxProps) {
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
|
@ -197,7 +199,7 @@ function ModelSelectionListbox({
|
|||
{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
|
||||
{otherOptionsLabel}
|
||||
</div>
|
||||
{filteredOtherOptions.map((option, index) => (
|
||||
<ListboxOption
|
||||
|
|
|
|||
|
|
@ -1,20 +1,25 @@
|
|||
import { ArrowTopRightOnSquareIcon } from "@heroicons/react/24/outline";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import {
|
||||
ArrowPathIcon,
|
||||
ArrowTopRightOnSquareIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { useCallback, useContext, useEffect, useState } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { Button, Input, StyledActionButton } from "../components";
|
||||
import Alert from "../components/gui/Alert";
|
||||
import ModelSelectionListbox from "../components/modelSelection/ModelSelectionListbox";
|
||||
import { ModelProviderTags } from "../components/modelSelection/utils";
|
||||
import { useAuth } from "../context/Auth";
|
||||
import { IdeMessengerContext } from "../context/IdeMessenger";
|
||||
import { completionParamsInputs } from "../pages/AddNewModel/configs/completionParamsInputs";
|
||||
import { DisplayInfo } from "../pages/AddNewModel/configs/models";
|
||||
import {
|
||||
initializeOpenRouterModels,
|
||||
fetchProviderModels,
|
||||
initializeDynamicModels,
|
||||
} from "../pages/AddNewModel/configs/fetchProviderModels";
|
||||
import { DisplayInfo, ModelPackage } from "../pages/AddNewModel/configs/models";
|
||||
import {
|
||||
ProviderInfo,
|
||||
providers,
|
||||
} from "../pages/AddNewModel/configs/providers";
|
||||
import { useAppDispatch } from "../redux/hooks";
|
||||
import { updateSelectedModelByRole } from "../redux/thunks/updateSelectedModelByRole";
|
||||
|
||||
interface AddModelFormProps {
|
||||
onDone: () => void;
|
||||
|
|
@ -33,7 +38,6 @@ export function AddModelForm({
|
|||
const [selectedProvider, setSelectedProvider] = useState<ProviderInfo>(
|
||||
providers["openai"]!,
|
||||
);
|
||||
const dispatch = useAppDispatch();
|
||||
const { selectedProfile } = useAuth();
|
||||
const [selectedModel, setSelectedModel] = useState(
|
||||
selectedProvider.packages[0],
|
||||
|
|
@ -41,11 +45,43 @@ export function AddModelForm({
|
|||
const formMethods = useForm();
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
// Initialize OpenRouter models from API on component mount
|
||||
const [fetchedModelsList, setFetchedModelsList] = useState<ModelPackage[]>(
|
||||
[],
|
||||
);
|
||||
const [isFetchingModels, setIsFetchingModels] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
void initializeOpenRouterModels();
|
||||
void initializeDynamicModels(ideMessenger);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setFetchedModelsList([]);
|
||||
}, [selectedProvider]);
|
||||
|
||||
const handleFetchModels = useCallback(async () => {
|
||||
const apiKey = formMethods.watch("apiKey");
|
||||
const apiBase = formMethods.watch("apiBase");
|
||||
if (!apiKey) return;
|
||||
|
||||
const providerAtFetchTime = selectedProvider.provider;
|
||||
setIsFetchingModels(true);
|
||||
try {
|
||||
const models = await fetchProviderModels(
|
||||
ideMessenger,
|
||||
providerAtFetchTime,
|
||||
apiKey,
|
||||
apiBase,
|
||||
);
|
||||
setFetchedModelsList((prev) =>
|
||||
selectedProvider.provider === providerAtFetchTime ? models : prev,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch models:", error);
|
||||
} finally {
|
||||
setIsFetchingModels(false);
|
||||
}
|
||||
}, [ideMessenger, selectedProvider, formMethods]);
|
||||
|
||||
const popularProviderTitles = [
|
||||
providers["openai"]?.title || "",
|
||||
providers["anthropic"]?.title || "",
|
||||
|
|
@ -92,6 +128,9 @@ export function AddModelForm({
|
|||
|
||||
useEffect(() => {
|
||||
setSelectedModel(selectedProvider.packages[0]);
|
||||
if (!selectedProvider.tags?.includes(ModelProviderTags.RequiresApiKey)) {
|
||||
formMethods.setValue("apiKey", "");
|
||||
}
|
||||
}, [selectedProvider]);
|
||||
|
||||
const requiresSkPrefix =
|
||||
|
|
@ -131,14 +170,15 @@ export function AddModelForm({
|
|||
profileId: "local",
|
||||
});
|
||||
|
||||
void dispatch(
|
||||
updateSelectedModelByRole({
|
||||
selectedProfile,
|
||||
if (selectedProfile) {
|
||||
ideMessenger.post("config/updateSelectedModel", {
|
||||
profileId: selectedProfile.id,
|
||||
role: "chat",
|
||||
modelTitle: model.title,
|
||||
}),
|
||||
);
|
||||
title: model.title,
|
||||
});
|
||||
}
|
||||
|
||||
formMethods.setValue("apiKey", "");
|
||||
onDone();
|
||||
}
|
||||
|
||||
|
|
@ -199,7 +239,27 @@ export function AddModelForm({
|
|||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Model</label>
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="block text-sm font-medium">Model</label>
|
||||
<button
|
||||
type="button"
|
||||
title="Use entered API key to fetch available models"
|
||||
className={`cursor-pointer border-none bg-transparent p-0 ${
|
||||
apiKeyValue &&
|
||||
apiKeyValue.length > 0 &&
|
||||
selectedProvider.provider !== "ollama" &&
|
||||
selectedProvider.provider !== "openrouter"
|
||||
? `text-description-muted hover:text-foreground`
|
||||
: "invisible"
|
||||
}`}
|
||||
onClick={handleFetchModels}
|
||||
disabled={isFetchingModels}
|
||||
>
|
||||
<ArrowPathIcon
|
||||
className={`h-3.5 w-3.5 ${isFetchingModels ? "animate-spin" : ""}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<ModelSelectionListbox
|
||||
selectedProvider={selectedModel}
|
||||
setSelectedProvider={(val: DisplayInfo) => {
|
||||
|
|
@ -208,19 +268,49 @@ export function AddModelForm({
|
|||
([, provider]) =>
|
||||
provider?.title === selectedProvider.title,
|
||||
)?.[1]?.packages ?? [];
|
||||
const match = options.find(
|
||||
const allOptions = [...options, ...fetchedModelsList];
|
||||
const match = allOptions.find(
|
||||
(option) => option.title === val.title,
|
||||
);
|
||||
if (match) {
|
||||
setSelectedModel(match);
|
||||
}
|
||||
}}
|
||||
topOptions={
|
||||
Object.entries(providers).find(
|
||||
topOptions={(() => {
|
||||
const providerInfo = Object.entries(providers).find(
|
||||
([, provider]) =>
|
||||
provider?.title === selectedProvider.title,
|
||||
)?.[1]?.packages
|
||||
}
|
||||
)?.[1];
|
||||
return (
|
||||
providerInfo?.popularPackages ?? providerInfo?.packages
|
||||
);
|
||||
})()}
|
||||
otherOptions={(() => {
|
||||
const providerInfo = Object.entries(providers).find(
|
||||
([, provider]) =>
|
||||
provider?.title === selectedProvider.title,
|
||||
)?.[1];
|
||||
const staticOther = providerInfo?.popularPackages
|
||||
? providerInfo.packages.filter(
|
||||
(p) =>
|
||||
!new Set(
|
||||
providerInfo.popularPackages!.map((pp) => pp.title),
|
||||
).has(p.title),
|
||||
)
|
||||
: undefined;
|
||||
// Merge dynamically fetched models (deduplicated)
|
||||
if (fetchedModelsList.length > 0) {
|
||||
const existingTitles = new Set(
|
||||
(providerInfo?.packages ?? []).map((p) => p.title),
|
||||
);
|
||||
const newModels = fetchedModelsList.filter(
|
||||
(m) => !existingTitles.has(m.title),
|
||||
);
|
||||
return [...(staticOther ?? []), ...newModels];
|
||||
}
|
||||
return staticOther;
|
||||
})()}
|
||||
otherOptionsLabel="Additional models"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
144
gui/src/pages/AddNewModel/configs/fetchProviderModels.ts
Normal file
144
gui/src/pages/AddNewModel/configs/fetchProviderModels.ts
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import { ModelProviderTags } from "../../../components/modelSelection/utils";
|
||||
import { IIdeMessenger } from "../../../context/IdeMessenger";
|
||||
import { ModelPackage } from "./models";
|
||||
import { models } from "./models";
|
||||
import { ollamaStaticModels, providers } from "./providers";
|
||||
|
||||
interface FetchedModel {
|
||||
name: string;
|
||||
modelId?: string;
|
||||
description?: string;
|
||||
icon?: string;
|
||||
contextLength?: number;
|
||||
maxTokens?: number;
|
||||
supportsTools?: boolean;
|
||||
}
|
||||
|
||||
function modelParams(model: FetchedModel): Record<string, any> {
|
||||
const params: Record<string, any> = {};
|
||||
if (model.contextLength) params.contextLength = model.contextLength;
|
||||
if (model.maxTokens) {
|
||||
params.completionOptions = { maxTokens: model.maxTokens };
|
||||
}
|
||||
if (model.supportsTools) {
|
||||
params.capabilities = { tools: true };
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
function toOllamaPackage(model: FetchedModel): ModelPackage {
|
||||
return {
|
||||
title: model.name,
|
||||
description: model.description || model.name,
|
||||
refUrl: `https://ollama.com/library/${model.name}`,
|
||||
params: {
|
||||
title: model.name,
|
||||
model: model.name,
|
||||
...(model.supportsTools ? { capabilities: { tools: true } } : {}),
|
||||
},
|
||||
isOpenSource: true,
|
||||
tags: [ModelProviderTags.Local, ModelProviderTags.OpenSource],
|
||||
providerOptions: ["ollama"],
|
||||
icon: model.icon ?? "ollama.png",
|
||||
};
|
||||
}
|
||||
|
||||
function toOpenRouterPackage(model: FetchedModel): ModelPackage {
|
||||
const id = model.modelId ?? model.name;
|
||||
return {
|
||||
title: model.name,
|
||||
description: model.name,
|
||||
refUrl: `https://openrouter.ai/models/${id}`,
|
||||
params: {
|
||||
title: model.name,
|
||||
model: id,
|
||||
...modelParams(model),
|
||||
},
|
||||
isOpenSource: false,
|
||||
tags: [ModelProviderTags.RequiresApiKey],
|
||||
providerOptions: ["openrouter"],
|
||||
icon: model.icon ?? "openrouter.png",
|
||||
};
|
||||
}
|
||||
|
||||
function toGenericPackage(model: FetchedModel, provider: string): ModelPackage {
|
||||
const id = model.modelId ?? model.name;
|
||||
return {
|
||||
title: model.name,
|
||||
description: model.name,
|
||||
params: {
|
||||
title: model.name,
|
||||
model: id,
|
||||
...modelParams(model),
|
||||
},
|
||||
isOpenSource: false,
|
||||
providerOptions: [provider],
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchModels(
|
||||
ideMessenger: IIdeMessenger,
|
||||
provider: string,
|
||||
apiKey?: string,
|
||||
apiBase?: string,
|
||||
): Promise<FetchedModel[]> {
|
||||
const response = await ideMessenger.request("models/fetch", {
|
||||
provider,
|
||||
apiKey,
|
||||
apiBase,
|
||||
});
|
||||
if (response.status === "error" || !response.content) {
|
||||
return [];
|
||||
}
|
||||
return response.content.sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
export async function fetchProviderModels(
|
||||
ideMessenger: IIdeMessenger,
|
||||
provider: string,
|
||||
apiKey: string,
|
||||
apiBase?: string,
|
||||
): Promise<ModelPackage[]> {
|
||||
const models = await fetchModels(ideMessenger, provider, apiKey, apiBase);
|
||||
return models.map((m) => toGenericPackage(m, provider));
|
||||
}
|
||||
|
||||
export async function initializeDynamicModels(ideMessenger: IIdeMessenger) {
|
||||
const ollamaAutodetect = {
|
||||
...models.AUTODETECT,
|
||||
params: { ...models.AUTODETECT.params, title: "Ollama" },
|
||||
};
|
||||
|
||||
if (providers.ollama) {
|
||||
providers.ollama.popularPackages = [
|
||||
ollamaAutodetect,
|
||||
...ollamaStaticModels,
|
||||
];
|
||||
|
||||
try {
|
||||
const fetched = await fetchModels(ideMessenger, "ollama");
|
||||
const fetchedPkgs = fetched.map(toOllamaPackage);
|
||||
const popularTitles = new Set(
|
||||
providers.ollama.popularPackages.map((p) => p.title),
|
||||
);
|
||||
const additional = fetchedPkgs.filter((p) => !popularTitles.has(p.title));
|
||||
providers.ollama.packages = [
|
||||
...providers.ollama.popularPackages,
|
||||
...additional,
|
||||
];
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize Ollama models:", error);
|
||||
providers.ollama.packages = [...providers.ollama.popularPackages];
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const fetched = await fetchModels(ideMessenger, "openrouter");
|
||||
const packages = fetched.map(toOpenRouterPackage);
|
||||
if (packages.length > 0 && providers.openrouter) {
|
||||
providers.openrouter.packages = packages;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to initialize OpenRouter models:", error);
|
||||
}
|
||||
}
|
||||
|
|
@ -25,7 +25,7 @@ export interface ModelPackage {
|
|||
params: {
|
||||
model: ILLM["model"];
|
||||
templateMessages?: ILLM["templateMessages"];
|
||||
contextLength: ILLM["contextLength"];
|
||||
contextLength?: ILLM["contextLength"];
|
||||
stopTokens?: string[];
|
||||
promptTemplates?: ILLM["promptTemplates"];
|
||||
replace?: [string, string][];
|
||||
|
|
@ -2240,6 +2240,48 @@ export const models: { [key: string]: ModelPackage } = {
|
|||
icon: "openai.png",
|
||||
isOpenSource: false,
|
||||
},
|
||||
gpt5_4Pro: {
|
||||
title: "GPT-5.4 Pro",
|
||||
description:
|
||||
"OpenAI's smartest model with increased compute for more precise responses.",
|
||||
params: {
|
||||
model: "gpt-5.4-pro",
|
||||
contextLength: 1_050_000,
|
||||
completionOptions: { maxTokens: 128_000 },
|
||||
title: "GPT-5.4 Pro",
|
||||
},
|
||||
providerOptions: ["openai"],
|
||||
icon: "openai.png",
|
||||
isOpenSource: false,
|
||||
},
|
||||
gpt5_4: {
|
||||
title: "GPT-5.4",
|
||||
description:
|
||||
"OpenAI's high-intelligence flagship model with 1M context window.",
|
||||
params: {
|
||||
model: "gpt-5.4",
|
||||
contextLength: 1_050_000,
|
||||
completionOptions: { maxTokens: 128_000 },
|
||||
title: "GPT-5.4",
|
||||
},
|
||||
providerOptions: ["openai"],
|
||||
icon: "openai.png",
|
||||
isOpenSource: false,
|
||||
},
|
||||
gpt5_4Mini: {
|
||||
title: "GPT-5.4 Mini",
|
||||
description:
|
||||
"OpenAI's strongest mini model for coding, computer use, and high-volume workloads.",
|
||||
params: {
|
||||
model: "gpt-5.4-mini",
|
||||
contextLength: 400_000,
|
||||
completionOptions: { maxTokens: 128_000 },
|
||||
title: "GPT-5.4 Mini",
|
||||
},
|
||||
providerOptions: ["openai"],
|
||||
icon: "openai.png",
|
||||
isOpenSource: false,
|
||||
},
|
||||
codexMini: {
|
||||
title: "Codex Mini",
|
||||
description:
|
||||
|
|
@ -2438,6 +2480,19 @@ export const models: { [key: string]: ModelPackage } = {
|
|||
},
|
||||
isOpenSource: true,
|
||||
},
|
||||
gemma4: {
|
||||
title: "Gemma 4",
|
||||
description:
|
||||
"Gemma 4 is a multimodal open model from Google, supporting text, image, tool use, and up to 128k context.",
|
||||
params: {
|
||||
title: "Gemma 4",
|
||||
model: "gemma4",
|
||||
contextLength: 128_000,
|
||||
},
|
||||
icon: "gemini.png",
|
||||
providerOptions: ["ollama"],
|
||||
isOpenSource: true,
|
||||
},
|
||||
phi3mini: {
|
||||
title: "Microsoft Phi 3 mini",
|
||||
description:
|
||||
|
|
|
|||
|
|
@ -1,77 +0,0 @@
|
|||
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);
|
||||
}
|
||||
|
|
@ -3,7 +3,6 @@ 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;
|
||||
|
|
@ -28,6 +27,7 @@ export interface ProviderInfo {
|
|||
longDescription?: string;
|
||||
tags?: ModelProviderTags[];
|
||||
packages: ModelPackage[];
|
||||
popularPackages?: ModelPackage[];
|
||||
params?: any;
|
||||
collectInputFor?: InputDescriptor[];
|
||||
refPage?: string;
|
||||
|
|
@ -41,38 +41,9 @@ 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 ollamaStaticModels = Object.values(models).filter(
|
||||
({ providerOptions }) => providerOptions?.includes("ollama"),
|
||||
);
|
||||
|
||||
export const apiBaseInput: InputDescriptor = {
|
||||
inputType: "text",
|
||||
|
|
@ -145,12 +116,15 @@ export const providers: Partial<Record<string, ProviderInfo>> = {
|
|||
openai: {
|
||||
title: "OpenAI",
|
||||
provider: "openai",
|
||||
description: "Use gpt-5.1, gpt-5, gpt-4, or any other OpenAI model",
|
||||
description: "Use gpt-5.4, gpt-5, or any other OpenAI model",
|
||||
longDescription:
|
||||
"Use gpt-5.1, gpt-5, gpt-4, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.",
|
||||
"Use gpt-5.4, gpt-5, or any other OpenAI model. See [here](https://openai.com/product#made-for-developers) to obtain an API key.",
|
||||
icon: "openai.png",
|
||||
tags: [ModelProviderTags.RequiresApiKey],
|
||||
packages: [
|
||||
models.gpt5_4Pro,
|
||||
models.gpt5_4,
|
||||
models.gpt5_4Mini,
|
||||
models.gpt5_2,
|
||||
models.gpt5_1,
|
||||
models.gpt5,
|
||||
|
|
@ -240,7 +214,14 @@ export const providers: Partial<Record<string, ProviderInfo>> = {
|
|||
},
|
||||
...completionParamsInputsConfigs,
|
||||
],
|
||||
packages: openRouterModelsList,
|
||||
packages: [
|
||||
{
|
||||
title: "Loading models...",
|
||||
description: "Fetching available models from OpenRouter",
|
||||
params: { model: "placeholder" },
|
||||
isOpenSource: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
moonshot: {
|
||||
|
|
@ -502,7 +483,7 @@ Select the \`GPT-4o\` model below to complete your provider configuration, but n
|
|||
title: "Ollama",
|
||||
},
|
||||
},
|
||||
...openSourceModels,
|
||||
...ollamaStaticModels,
|
||||
],
|
||||
collectInputFor: [
|
||||
...completionParamsInputsConfigs,
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue