Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(ai): suggest models when adding an OpenAI-compatible key (#16382)

Louai Boumediene73f5a5f44350
diff --git a/brain/knowledge/ai-intelligence/ai-providers.md b/brain/knowledge/ai-intelligence/ai-providers.md
index f41084309a1..6128a2c77df 100644
--- a/brain/knowledge/ai-intelligence/ai-providers.md
+++ b/brain/knowledge/ai-intelligence/ai-providers.md
@@ -157,6 +157,7 @@ after a file without chat keys it seeds the chat list from the live flow list.
- **A failed credential validation tells the admin nothing, for every provider except Cloudflare Gateway.** `aiProviderService.validateProviderCredentials` gates the upstream message behind `includeHttpErrorInMessage`, which is `provider === CLOUDFLARE_GATEWAY` and nothing else, so everyone else gets a bare `Failed to validate credentials for <name>`. The cause is not lost — it is logged one line earlier (`log.error({ error }, '[aiProviderService#validateProviderCredentials] ...')`) and passed as the `httpErrorResponse` error param — but **web never renders `httpErrorResponse`**, so the only way to diagnose a rejected key is the server log. Grep the log for `validateProviderCredentials` before assuming the provider integration is broken — that text is the whole diagnosis, and it is often not about credentials at all. Confirmed case: a brand-new xAI team with no credits purchased answers `GET /v1/models` with `403 permission-denied — Your newly created team doesn't have any credits or licenses yet`, naming the console page that fixes it, and we render that as "Failed to validate credentials for xAI" — sending the admin off to regenerate a key that was never wrong. Vendors also phrase real key failures inconsistently (xAI uses `400 Incorrect API key provided`, not a 401). The corollary: **a provider that saves without error is not a working provider.** A no-credits 403 and a bad key are indistinguishable in the UI, so only an actual generation proves a key end to end. This is an admin-only surface (`platformAdminOnly`), so there is little reason to keep hiding it.
- **A provider's logo is an asset someone has to upload, not something the code ships.** `AiProviderInfo.logoUrl` in `packages/web/src/features/agents/ai-providers.ts` is a plain string rendered into an `<img src>`, and every provider points at `https://cdn.activepieces.com/pieces/<slug>.png` — nothing is bundled. Adding a provider therefore carries a cross-team dependency with no compile-time or test signal: a slug with no asset behind it renders a broken-image icon in the platform admin list, and only a live request tells you. Check the URL with `curl -o /dev/null -w '%{http_code}'` before assuming it works — a vendor that already ships as a *piece* usually has its logo there already (`deepseek.png`, `grok-xai.png` did), so start the upload request only for the genuinely missing ones. A Vite asset import also satisfies `logoUrl` (see `GoogleIcon` in `platform/security/sso/index.tsx`) and removes the runtime CDN dependency for air-gapped installs, but it diverges from every other provider — treat it as a fallback, not the default.
- **The manual-models panel stores a model id and nothing else, so every model an admin adds is typed `TEXT`.** `MANUAL_MODEL_PROVIDERS` (Vertex, Custom, Cloudflare Gateway) persist a `ProviderModelConfig` of `{ modelId, modelName, modelType }`, but since #14825 the UI keeps only `string[]`: `ManualModelList` is a chip list of ids, and `config-detail.tsx` rebuilds the objects on save with `?? { modelId, modelName: modelId, modelType: TEXT }`. The old `universal-pieces/model-form-popover.tsx` had all three fields; replacing it with chips dropped two of them, and no schema or test noticed because the reconstruction is type-correct. The visible damage is not just a mislabelled model: `cloudflareGatewayProvider.validateConnection` pings **only text models** with a `/chat/completions` request, so one image model added through the UI is validated as chat, fails, and takes the whole key down with `These models have issues: ...` — the admin cannot save a key that has an image model on it at all. Anything reading `modelType` downstream (the agent text-model filter, `ap-list-ai-models`, the builder's image pickers) is wrong the same way. Fixed by holding `ProviderModelConfig[]` in the draft rather than `string[]` (no migration; stored rows always had the right shape), so the standing rule is that **a manual-models UI must carry `modelType` all the way to the payload** — a panel that collapses models to ids reintroduces exactly this, and nothing downstream will complain until an admin adds an image model. Keys saved while the bug was live still hold image models typed `TEXT`; the type badge on each chip flips one in place, which is why it is editable rather than display-only.
+- **Custom keys get model suggestions; Vertex and Cloudflare Gateway stay typed by hand on purpose.** `GET /v1/ai-providers/configs/:id/suggested-models` calls the strategy's optional `suggestModels`, which only `openAICompatibleProvider` implements: `GET {baseUrl}/models` with the key's own header, through `fetchOpenAiModelIds` (shared with the vendor list), filtered by `isChatModelId`. The ids feed a `<datalist>` on the manual-models input, so free text still works and the admin still picks `modelType` (`/models` does not say text or image). Suggestions never touch `listModels`, which stays `config.models` because tiers and key scope read it. A failed fetch returns `[]` and logs, so a LAN or localhost base URL that `safeHttp` blocks (self-hosted Ollama, unless in `AP_SSRF_ALLOW_LIST`) just shows no suggestions. Vertex is not listed for the reason in the Vertex bullet (one publisher per call), and Cloudflare's gateway has no models endpoint. Any fetch to an admin-supplied URL needs three bounds, not one: axios's `timeout` only fires when the connection goes idle, so a server that drips bytes holds it open, and a huge body is read into memory in full. `fetchOpenAiModelIds` passes `timeout`, `signal: AbortSignal.timeout(...)` and `maxContentLength`. Trim a trailing slash with `/\/$/`, not `/\/+$/`: the `+` form is quadratic on a long run of slashes and `baseUrl` has no length limit (both from review on #16382).
- **`AIProviderConfig` is an *untagged* `z.union`, so a new provider's config schema must sit ahead of the empty ones — and "empty" includes a schema whose every field is optional.** Zod strips unknown keys and a union returns the first member that parses, so `AnthropicProviderConfig` (`z.object({})`) matches *any* object: list it before a `{ baseUrl?: string }` config and a configured base URL is silently reduced to `{}` — no error, no log, the admin's override just stops existing on the next read. The file carries an `Order matters` comment, but it says "empty ones last", which reads as though only a literal `z.object({})` is at risk. The rule is **not** "after the last schema with a required field" — that phrasing reads as "append after `BedrockProviderConfig`" and is how a Vertex config got silently reduced to `{ region }`, losing `project` and `models` with no error. What matters is the *subset relation*, not the count: `BedrockProviderConfig` is `{ region }`, a strict subset of `{ project, region, models }`, so it matches a Vertex object first and strips the rest. Order by specificity — any schema whose required keys are a subset of yours must sit **after** you. Check with a one-line parse before trusting the order: `AIProviderConfig.parse(yourConfig)` must return every field it was given. `ProviderConfigUnion` is discriminated on `provider` and so is immune; only the two untagged unions (`AIProviderConfig`, `AIProviderAuthConfig`) bite. Both live twice — `packages/core/shared/.../management/ai-providers/index.ts` (zod classic) and `packages/core/piece-types/.../ai-providers.ts` (zod/mini, the copy pieces use) — and every provider edit has to land in both. **The third copy moved rather than disappearing.** `.../setup/ai/universal-pieces/` is gone and the connect dialog now builds from `PROVIDER_CREDENTIAL_FIELDS`, but `config-detail.tsx` declares its own `ManualProviderConfig = z.union([...])` that gates whether the manual-models panel sends `config` at all. A provider missing from it fails `safeParse`, its models are dropped from the payload, and they silently vanish on reload — which for a `MANUAL_MODEL_PROVIDERS` member means the only way to choose a model does not work. So it is still **three** unions per provider: the two shared copies plus this one, and it is the easiest to miss because it lives in a component and nothing references the provider by name. The rest of this sentence describes that deleted file and is kept only as history: `createFormSchema` in the admin dialog (`.../setup/ai/universal-pieces/upsert-provider-dialog.tsx`) re-declares a per-provider schema, branching explicitly on Azure / Cloudflare / Custom / Bedrock and falling through to a generic case whose `config` is a union of three empty objects. **A provider with a non-empty config and no branch there loses that config entirely** — `zodResolver` hands react-hook-form the *parsed* value, so the strip happens before submit and the setting is never sent, with no error anywhere. Fixing the shared union does not fix this one; grep for every union of config schemas when adding a provider. The dialog only diverges from the correct `ProviderConfigUnion` to make auth optional in edit mode, so collapsing it onto the shared discriminated union is the real repair. (Testing that file directly is awkward: importing it pulls in a transitive dep that touches `document` at import time, which a node-env vitest cannot load — the schema factory would have to move out of the component file first.)
- **Every catalog field is optional, and two providers never match at all.** Azure's `listModels`
diff --git a/packages/server/api/src/app/ai/ai-provider-controller.ts b/packages/server/api/src/app/ai/ai-provider-controller.ts
index e21bad2b0cc..54f6d98f9ef 100644
--- a/packages/server/api/src/app/ai/ai-provider-controller.ts
+++ b/packages/server/api/src/app/ai/ai-provider-controller.ts
@@ -26,6 +26,12 @@ export const aiProviderController: FastifyPluginAsyncZod = async (app) => {
configId: request.params.id,
})
})
+ app.get('/configs/:id/suggested-models', ListSuggestedModelsForConfig, async (request) => {
+ return aiProviderService(app.log).suggestModelsForConfig({
+ platformId: request.principal.platform.id,
+ configId: request.params.id,
+ })
+ })
app.get('/tiers', ListModelTiers, async () => ({
flow: modelTierCatalog.current('flow'),
chat: modelTierCatalog.current('chat'),
@@ -99,6 +105,20 @@ const ListModelsForConfig = {
},
}
+const ListSuggestedModelsForConfig = {
+ config: {
+ security: securityAccess.platformAdminOnly([PrincipalType.USER]),
+ },
+ schema: {
+ params: z.object({
+ id: z.string(),
+ }),
+ response: {
+ [StatusCodes.OK]: z.array(z.string()),
+ },
+ },
+}
+
const ModelTierList = z.object({
tiers: z.array(z.object({
id: z.string(),
diff --git a/packages/server/api/src/app/ai/ai-provider-service.ts b/packages/server/api/src/app/ai/ai-provider-service.ts
index 8fca1a9aab0..35da566ac31 100644
--- a/packages/server/api/src/app/ai/ai-provider-service.ts
+++ b/packages/server/api/src/app/ai/ai-provider-service.ts
@@ -93,6 +93,21 @@ export const aiProviderService = (log: FastifyBaseLogger) => ({
return fetchModels({ aiProvider, platformId, log })
},
+ async suggestModelsForConfig({ platformId, configId }: { platformId: PlatformId, configId: string }): Promise<string[]> {
+ const aiProvider = await getRowByIdOrThrow({ platformId, configId })
+ const strategy = aiProviders[aiProvider.provider]
+ if (isNil(strategy.suggestModels)) {
+ return []
+ }
+ const auth = await decryptRowAuth({ aiProvider, platformId, log })
+ const { data, error } = await tryCatch(async () => strategy.suggestModels?.(auth, aiProvider.config))
+ if (!isNil(error)) {
+ log.warn({ error, providerId: aiProvider.id }, '[aiProviderService#suggestModelsForConfig] could not fetch model suggestions')
+ return []
+ }
+ return data ?? []
+ },
+
async create(platformId: PlatformId, request: CreateAIProviderRequest): Promise<AIProviderWithoutSensitiveData> {
if (request.provider === AIProviderName.ACTIVEPIECES) {
throw new ActivepiecesError({
diff --git a/packages/server/api/src/app/ai/providers/ai-provider.ts b/packages/server/api/src/app/ai/providers/ai-provider.ts
index 7a7e1fee8fe..fbb60fc6c7f 100644
--- a/packages/server/api/src/app/ai/providers/ai-provider.ts
+++ b/packages/server/api/src/app/ai/providers/ai-provider.ts
@@ -8,5 +8,6 @@ export type AIProviderStrategy<T extends AIProviderAuthConfig, C extends AIProvi
modelIdsAreCustomerNamed?: boolean
validationSkipsModelEndpoint?: boolean
listModels(authConfig: T, config: C): Promise<AIProviderModel[]>
+ suggestModels?(authConfig: T, config: C): Promise<string[]>
validateConnection(authConfig: T, config: C, log: FastifyBaseLogger): Promise<void>
}
diff --git a/packages/server/api/src/app/ai/providers/openai-compatible-gateway-provider.ts b/packages/server/api/src/app/ai/providers/openai-compatible-gateway-provider.ts
index 6589a0bd83c..a86da6c42dc 100644
--- a/packages/server/api/src/app/ai/providers/openai-compatible-gateway-provider.ts
+++ b/packages/server/api/src/app/ai/providers/openai-compatible-gateway-provider.ts
@@ -1,6 +1,7 @@
-import { ActivepiecesError, AIProviderModel, ErrorCode, isNil, OpenAICompatibleProviderAuthConfig, OpenAICompatibleProviderConfig, tryCatchSync } from '@activepieces/shared'
+import { ActivepiecesError, AIProviderModel, aiProviderUtils, ErrorCode, isNil, OpenAICompatibleProviderAuthConfig, OpenAICompatibleProviderConfig, tryCatchSync } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { AIProviderStrategy } from './ai-provider'
+import { fetchOpenAiModelIds } from './openai-compatible-vendor'
export const openAICompatibleProvider: AIProviderStrategy<OpenAICompatibleProviderAuthConfig, OpenAICompatibleProviderConfig> = {
name: 'OpenAI Compatible',
@@ -19,6 +20,13 @@ export const openAICompatibleProvider: AIProviderStrategy<OpenAICompatibleProvid
type: m.modelType,
}))
},
+ async suggestModels(authConfig: OpenAICompatibleProviderAuthConfig, config: OpenAICompatibleProviderConfig): Promise<string[]> {
+ const modelIds = await fetchOpenAiModelIds({
+ url: `${config.baseUrl.replace(/\/$/, '')}/models`,
+ headers: { ...(config.defaultHeaders ?? {}), [config.apiKeyHeader]: authConfig.apiKey },
+ })
+ return modelIds.filter((modelId) => aiProviderUtils.isChatModelId({ modelId }))
+ },
}
function assertUsableBaseUrl({ baseUrl }: { baseUrl: string }): void {
diff --git a/packages/server/api/src/app/ai/providers/openai-compatible-vendor.ts b/packages/server/api/src/app/ai/providers/openai-compatible-vendor.ts
index 485091111d6..8d06bd1ccb5 100644
--- a/packages/server/api/src/app/ai/providers/openai-compatible-vendor.ts
+++ b/packages/server/api/src/app/ai/providers/openai-compatible-vendor.ts
@@ -4,6 +4,18 @@ import { safeHttp } from '@activepieces/server-utils'
import { AIProviderModel, AIProviderModelType, aiProviderUtils, BaseAIProviderAuthConfig, isNil, OpenAiCompatibleVendorConfig, tryCatch } from '@activepieces/shared'
import { AIProviderStrategy } from './ai-provider'
+export async function fetchOpenAiModelIds({ url, headers }: { url: string, headers: Record<string, string> }): Promise<string[]> {
+ const response = await safeHttp.axios.request<OpenAiCompatibleModelsResponse>({
+ method: 'GET',
+ url,
+ timeout: REQUEST_TIMEOUT_MS,
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
+ maxContentLength: MAX_MODELS_RESPONSE_BYTES,
+ headers,
+ })
+ return (response.data.data ?? []).map((model) => model.id)
+}
+
export function openAiCompatibleVendor({ name, provider }: {
name: string
provider: OpenAiCompatibleVendor
@@ -31,20 +43,18 @@ async function listVendorModels({ authConfig, provider, name }: {
return declaredModels
}
- const { data: response, error } = await tryCatch(() => safeHttp.axios.request<OpenAiCompatibleModelsResponse>({
- method: 'GET',
+ const { data: modelIds, error } = await tryCatch(() => fetchOpenAiModelIds({
url: vendorEndpoint({ provider, path: 'models' }),
- timeout: REQUEST_TIMEOUT_MS,
headers: vendorHeaders({ authConfig }),
}))
- if (!isNil(error) || isNil(response)) {
+ if (!isNil(error) || isNil(modelIds)) {
throw new Error(`[${name}] failed to list models: ${error instanceof Error ? error.message : String(error)}`)
}
- return (response.data.data ?? []).map((model) => ({
- id: model.id,
- name: model.id,
+ return modelIds.map((id) => ({
+ id,
+ name: id,
type: AIProviderModelType.TEXT,
}))
}
@@ -93,6 +103,8 @@ function vendorHeaders({ authConfig }: { authConfig: BaseAIProviderAuthConfig })
const REQUEST_TIMEOUT_MS = 15_000
+const MAX_MODELS_RESPONSE_BYTES = 5 * 1024 * 1024
+
const TEXT_OUTPUT_MODALITY = 'text'
const VENDORS_DECLARING_MODALITIES: OpenAiCompatibleVendor[] = [AIProviderName.XAI]
diff --git a/packages/server/api/test/unit/app/ai/providers/openai-compatible-suggestions.test.ts b/packages/server/api/test/unit/app/ai/providers/openai-compatible-suggestions.test.ts
new file mode 100644
index 00000000000..f22d72c70d5
--- /dev/null
+++ b/packages/server/api/test/unit/app/ai/providers/openai-compatible-suggestions.test.ts
@@ -0,0 +1,79 @@
+import { AIProviderModelType, isNil, OpenAICompatibleProviderConfig } from '@activepieces/shared'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { mockRequest } = vi.hoisted(() => ({ mockRequest: vi.fn() }))
+
+vi.mock('@activepieces/server-utils', () => ({
+ safeHttp: { axios: { request: mockRequest } },
+}))
+
+import { openAICompatibleProvider } from '../../../../../src/app/ai/providers/openai-compatible-gateway-provider'
+
+const config = (overrides: Partial<OpenAICompatibleProviderConfig> = {}): OpenAICompatibleProviderConfig => ({
+ apiKeyHeader: 'Authorization',
+ baseUrl: 'https://llm.example.com/v1/',
+ models: [{ modelId: 'typed-by-hand', modelName: 'typed-by-hand', modelType: AIProviderModelType.TEXT }],
+ ...overrides,
+})
+
+const respondWith = (ids: string[]): void => {
+ mockRequest.mockResolvedValue({ data: { data: ids.map((id) => ({ id })) } })
+}
+
+function suggest(overrides: Partial<OpenAICompatibleProviderConfig> = {}): Promise<string[]> {
+ const { suggestModels } = openAICompatibleProvider
+ if (isNil(suggestModels)) {
+ throw new Error('the OpenAI-compatible provider should suggest models')
+ }
+ return suggestModels({ apiKey: 'Bearer sk-test' }, config(overrides))
+}
+
+describe('openAICompatibleProvider.suggestModels', () => {
+ beforeEach(() => {
+ mockRequest.mockReset()
+ })
+
+ it('asks the server for its models with the same headers chat calls send', async () => {
+ respondWith(['llama-4'])
+
+ await suggest({ apiKeyHeader: 'x-api-key', defaultHeaders: { 'x-team': 'ops' } })
+
+ const request = mockRequest.mock.calls[0][0]
+ expect(request.url).toBe('https://llm.example.com/v1/models')
+ expect(request.headers).toEqual({ 'x-team': 'ops', 'x-api-key': 'Bearer sk-test' })
+ })
+
+ it('caps how long and how much the models request may read', async () => {
+ respondWith(['llama-4'])
+
+ await suggest()
+
+ const request = mockRequest.mock.calls[0][0]
+ expect(request.signal).toBeInstanceOf(AbortSignal)
+ expect(request.maxContentLength).toBe(5 * 1024 * 1024)
+ })
+
+ it('trims a long run of trailing slashes without stalling', async () => {
+ respondWith(['llama-4'])
+ const startedAt = performance.now()
+
+ await suggest({ baseUrl: `https://llm.example.com/v1${'/'.repeat(100_000)}x` })
+
+ expect(performance.now() - startedAt).toBeLessThan(1_000)
+ })
+
+ it('keeps chat models and drops embeddings, speech and moderation ids', async () => {
+ respondWith(['llama-4', 'text-embedding-3-small', 'whisper-1', 'omni-moderation-latest', 'qwen3-32b'])
+
+ await expect(suggest()).resolves.toEqual(['llama-4', 'qwen3-32b'])
+ })
+
+ it('does not change the models the key actually offers', async () => {
+ respondWith(['llama-4'])
+
+ await expect(openAICompatibleProvider.listModels({ apiKey: 'k' }, config())).resolves.toEqual([
+ { id: 'typed-by-hand', name: 'typed-by-hand', type: AIProviderModelType.TEXT },
+ ])
+ expect(mockRequest).not.toHaveBeenCalled()
+ })
+})
diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx
index 585e9f46100..a8fec7124dd 100644
--- a/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx
+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/config-detail.tsx
@@ -91,6 +91,11 @@ export function ConfigDetail({
queryFn: () => aiProviderApi.listModelsForConfig(config.id),
enabled: !manualModels,
});
+ const { data: suggestedModelIds = [] } = useQuery({
+ queryKey: [...aiProviderKeys.configModels(config.id), 'suggested'],
+ queryFn: () => aiProviderApi.listSuggestedModelsForConfig(config.id),
+ enabled: manualModels,
+ });
const selectableModels = [
...models,
...draft.modelIds
@@ -311,6 +316,7 @@ export function ConfigDetail({
{manualModels ? (
<ManualModelList
models={draft.models}
+ suggestedModelIds={suggestedModelIds}
onChange={(models) => setDraft({ ...draft, models })}
/>
) : (
diff --git a/packages/web/src/app/routes/platform/setup/ai/providers-tab/manual-model-list.tsx b/packages/web/src/app/routes/platform/setup/ai/providers-tab/manual-model-list.tsx
index a3d8444591d..d5e1f70a61c 100644
--- a/packages/web/src/app/routes/platform/setup/ai/providers-tab/manual-model-list.tsx
+++ b/packages/web/src/app/routes/platform/setup/ai/providers-tab/manual-model-list.tsx
@@ -1,7 +1,7 @@
import { AIProviderModelType, ProviderModelConfig } from '@activepieces/shared';
import { t } from 'i18next';
import { Plus, X } from 'lucide-react';
-import { useState } from 'react';
+import { useId, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -15,11 +15,17 @@ import {
export function ManualModelList({
models,
+ suggestedModelIds = [],
onChange,
}: {
models: ProviderModelConfig[];
+ suggestedModelIds?: string[];
onChange: (models: ProviderModelConfig[]) => void;
}) {
+ const suggestionListId = useId();
+ const unusedSuggestions = suggestedModelIds.filter(
+ (modelId) => !models.some((model) => model.modelId === modelId),
+ );
const [draftId, setDraftId] = useState('');
const [draftType, setDraftType] = useState<AIProviderModelType>(
AIProviderModelType.TEXT,
@@ -44,6 +50,7 @@ export function ManualModelList({
<div className="flex items-center gap-2 p-3">
<Input
className="max-w-xs"
+ list={suggestionListId}
value={draftId}
onChange={(event) => setDraftId(event.target.value)}
onKeyDown={(event) => {
@@ -54,6 +61,11 @@ export function ManualModelList({
}}
placeholder={t('e.g. openai/gpt-4o')}
/>
+ <datalist id={suggestionListId}>
+ {unusedSuggestions.map((modelId) => (
+ <option key={modelId} value={modelId} />
+ ))}
+ </datalist>
<Select
value={draftType}
onValueChange={(value) => setDraftType(modelTypeOf(value))}
diff --git a/packages/web/src/features/platform-admin/api/ai-provider-api.ts b/packages/web/src/features/platform-admin/api/ai-provider-api.ts
index 32a080893c2..4265530c715 100644
--- a/packages/web/src/features/platform-admin/api/ai-provider-api.ts
+++ b/packages/web/src/features/platform-admin/api/ai-provider-api.ts
@@ -35,6 +35,11 @@ export const aiProviderApi = {
`/v1/ai-providers/configs/${configId}/models`,
);
},
+ listSuggestedModelsForConfig(configId: string) {
+ return api.get<string[]>(
+ `/v1/ai-providers/configs/${configId}/suggested-models`,
+ );
+ },
listModelOptions({
projectId,
surface,
diff --git a/packages/web/test/app/routes/platform/setup/ai/manual-model-list.test.tsx b/packages/web/test/app/routes/platform/setup/ai/manual-model-list.test.tsx
index ab9e85d2389..1e856931aa9 100644
--- a/packages/web/test/app/routes/platform/setup/ai/manual-model-list.test.tsx
+++ b/packages/web/test/app/routes/platform/setup/ai/manual-model-list.test.tsx
@@ -34,8 +34,13 @@ vi.mock('@/components/ui/button', () => ({
}));
vi.mock('@/components/ui/input', () => ({
- Input: ({ value, onChange, placeholder }: any) => (
- <input value={value} onChange={onChange} placeholder={placeholder} />
+ Input: ({ value, onChange, placeholder, list }: any) => (
+ <input
+ value={value}
+ onChange={onChange}
+ placeholder={placeholder}
+ list={list}
+ />
),
}));
@@ -67,10 +72,19 @@ describe('ManualModelList', () => {
let root: Root;
let onChange: ReturnType<typeof vi.fn>;
- const render = (models: ProviderModelConfig[]) => {
+ const render = (
+ models: ProviderModelConfig[],
+ suggestedModelIds?: string[],
+ ) => {
onChange = vi.fn();
act(() => {
- root.render(<ManualModelList models={models} onChange={onChange} />);
+ root.render(
+ <ManualModelList
+ models={models}
+ suggestedModelIds={suggestedModelIds}
+ onChange={onChange}
+ />,
+ );
});
};
@@ -135,6 +149,27 @@ describe('ManualModelList', () => {
]);
});
+ it('suggests the models the server listed, minus the ones already added', () => {
+ render(
+ [
+ {
+ modelId: 'llama-4',
+ modelName: 'llama-4',
+ modelType: AIProviderModelType.TEXT,
+ },
+ ],
+ ['llama-4', 'qwen3-32b'],
+ );
+
+ const input = container.querySelector('input');
+ const suggestions = Array.from(
+ container.querySelectorAll(
+ `datalist[id="${input?.getAttribute('list')}"] option`,
+ ),
+ ).map((option) => option.getAttribute('value'));
+ expect(suggestions).toEqual(['qwen3-32b']);
+ });
+
it('flips the type of a model that is already saved, keeping its name', () => {
render([
{