diff --git a/AGENTS.md b/AGENTS.md index 4de581cb..536e9083 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,7 +73,8 @@ - `sources/`: each kind's `sync` function (dispatched by `sources::sync`) fetches its upstream providers (OpenRouter: `/v1/providers`; Cortecs, which has no provider list or names: the union of `providers` from `/v1/models?extended=true`, slug as name). `POST /api/v1/admin/upstream-providers/sync` and, in a background task, every model sync of a routing provider store the result in `upstream_gateways` / `upstream_providers`; `GET /api/v1/admin/upstream-providers` lists it, falling back to the endpoint options for kinds never synced. Restrictions the routing provider itself puts on our key (OpenRouter guardrail policies) are not read - To add a routing provider (e.g. Vercel): add its kind to `UPSTREAM_ROUTING`, map `ProviderRouting` in its Omniference adapter or vendor dialect, and add a `sync` function in `sources/` called from `sources::sync` - Cortecs (`CortecsDialect` in Omniference, Responses adapter): `only` becomes `allowed_providers`, `order` becomes `allowed_providers` with `provider_order: "custom"`, and Cortecs never falls back beyond that list, so web chat's "prefer" puts the model's other stored providers the user may use after the picked one (`picked_provider`); "lock" stays `only: [slug]`. Its catalog and every model's provider options come from one `/v1/models?extended=true` call in the model sync (`sync_cortecs_catalog`, `source_gateway = 'cortecs'`, `cortecs_options`, written in one transaction by `GatewayCatalogModel::replace_gateway_provider_options`); the provider-options refresh re-runs that sync. Cortecs reports EUR per 1M tokens (converted to USD with `exchange_rates`, left empty without a rate), latency in seconds (stored as ms) and uptime as a fraction (stored as percent); `ttft` and `cache_hit_rate` stay in `raw`. The admin Catalog tab stays OpenRouter-only -- Provider kinds without their own Omniference adapter pass `ProviderKind::catalog_slug()` as `catalog_provider_slug`, the vendor slug Omniference uses for models.dev prices and its vendor profile (`catalog/providers/.toml`); every `ProviderConfig` OxideChat builds must set it (`profile` and `resolved_profile` stay `None`: registration resolves the profile). `MISTRAL` uses the OpenAI-compatible Chat adapter (`/v1/chat/completions`), where Omniference's `MistralDialect` applies; `CORTECS` uses the OpenAI Responses adapter (`/v1/responses`) +- Native protocols (HEN-137): `providers.protocols` (`ChatProtocol`: `chat`, `responses`, `messages`) lists the chat protocols a provider serves besides its kind's own; `ai::provider_to_config` passes them to Omniference's `ProviderEndpoint::protocols`, whose router then forwards gateway requests in those protocols unchanged through that protocol's adapter instead of converting them (a request with provider routing is refused on a native route the vendor's dialect cannot route). The admin provider dialog edits them in a dropdown of checkboxes (`provider-protocols`; the kind's own protocol, `KIND_CHAT_PROTOCOL` in the generated `frontend/types/generated/protocols.ts`, written by `src/tests/bindings.rs` from Omniference with `CHAT_PROTOCOLS` and `UPSTREAM_PATHS`, is shown checked and locked, and a new preconfigured provider starts with its template's `defaultProtocols`, the other protocols that vendor serves), and `/api/v1/developer/models` returns each chat model's `routes` (`ChatRouteResponse`, from Omniference's `ChatRoute::all_for`, never recomputed in the frontend), shown on the Developer models page by `DeveloperModelRoutes` (accent arrow: passed through 1:1; muted icon: converted, with the protocol each route is sent as) and the Native endpoint filter +- Provider kinds without their own Omniference adapter pass `ProviderKind::catalog_slug()` as `catalog_provider_slug`, the vendor slug Omniference uses for models.dev prices and its vendor profile (`catalog/providers/.toml`); every `ProviderConfig` OxideChat builds must set it (`profile` and `resolved_profile` stay `None`: registration resolves the profile). `MISTRAL` and `CORTECS` use the OpenAI Responses adapter (`/v1/responses`; Mistral's is in public preview), where Omniference's `MistralDialect` and `CortecsDialect` apply; Mistral OCR goes through the same adapter to `/v1/ocr`, and new Mistral providers serve Chat natively too - `src/types/rag/` - Knowledge (RAG, HEN-22, built as stacked PRs; slices 1, 2a, 2b, 2c, 2d, 4 and 5b): `rag_config` (single row: reranker model, `top_n` and optional `min_score`, default managed connection, chunking defaults `chunk_size`/`chunk_overlap_percent`; knowledge uploads have no quotas of their own and count toward the shared file limits) and `rag_connections` (where vectors live), managed under `/api/v1/admin/rag` (`admin.rag.view` / `.edit`, page `/settings/tools/knowledge`, a sub page of Tools; `/settings/knowledge-setup` redirects there); knowledge is on while the Knowledge Search builtin tool row is enabled (`RagConfig::enabled`, `Tool::builtin_enabled`), there is no separate switch, and `/api/v1/base` returns that as `rag: {enabled}` - A connection has a `kind` (`pgvector`, `qdrant`) and a `mode` (`managed`: `OxideChat` writes, pgvector only; `read_only`: another pipeline fills it), both fixed at create. Its URL never holds a password, and a pgvector URL takes no query parameter but `sslmode` and no percent-encoded host (sqlx would read host, port, socket and key files from them past the host checks): the Postgres password or Qdrant API key is the encrypted `secret`, a new host needs it again (`RagConnection::redirects_secret`), and Qdrant keys go over https only. A managed pgvector connection without URL is the main database; `RAG_PGVECTOR_URL` replaces the address and password of the default managed connection; the first managed connection saved while no default is set becomes the default storage (`make_default_if_none`), and the add dialog (`SettingsKnowledgeConnectionsCard`) asks what to connect (OxideChat's own database, another PostgreSQL server, or an existing collection) and only then shows address and password - A managed connection's embedding model is checked with one test embedding billed to the saving admin (`probe_embedding`, `oxide_request_type = rag_setup`), which stores `vector_size`; a new model or size bumps `index_generation`. Reranker and embedding models are checked with `gateway::model_type`, and the admin model list takes `?type=embedding|reranking` for the pickers diff --git a/e2e/tests/admin.spec.ts b/e2e/tests/admin.spec.ts index ca98bd7a..d9459325 100644 --- a/e2e/tests/admin.spec.ts +++ b/e2e/tests/admin.spec.ts @@ -30,6 +30,7 @@ test.describe('admin settings', () => { await page.getByTestId('provider-card-MISTRAL').getByRole('button').first().click(); await expect(page.getByRole('dialog').getByTestId('provider-region')).toContainText(t('settings.providers.region_global')); await expect(page.getByRole('dialog').getByTestId('provider-reported-cost-source')).toHaveCount(0); + await expect(page.getByRole('dialog').getByTestId('provider-protocols')).toContainText(t('developer.protocol.chat')); await page.getByRole('dialog').getByTestId('provider-region').click(); await page.getByRole('option', {name: t('settings.providers.region_eu')}).click(); await page.getByRole('dialog').locator('#api-key').fill('e2e-mistral-key'); @@ -47,6 +48,9 @@ test.describe('admin settings', () => { await expect(dialog.getByTestId('provider-reported-cost-currency')).toContainText('EUR'); await expect(dialog.getByTestId('provider-reported-cost-source')).toHaveValue('usage.cost'); await expect(dialog.getByTestId('provider-reported-cost-scale')).toHaveValue('0.000001'); + for (const protocol of ['chat', 'responses', 'messages']) { + await expect(dialog.getByTestId('provider-protocols')).toContainText(t(`developer.protocol.${protocol}`)); + } }); test('the synced test model is listed on the models page', async ({page, t, seed}) => { diff --git a/e2e/tests/native-endpoints.spec.ts b/e2e/tests/native-endpoints.spec.ts new file mode 100644 index 00000000..3673ba08 --- /dev/null +++ b/e2e/tests/native-endpoints.spec.ts @@ -0,0 +1,86 @@ +import type {Page} from '@playwright/test'; +import {test, expect} from './support/fixtures'; +import {createKeyViaApi, uniqueName, waitForLog} from './support/gateway'; +import {LLM} from './support/constants'; +import {KIND_CHAT_PROTOCOL} from '../../frontend/types/generated/protocols'; + +const own = KIND_CHAT_PROTOCOL[LLM.kind]!; +const extra = own === 'messages' ? 'chat' : 'messages'; + +async function openProvider(page: Page, t: (key: string) => string, providerName: string) { + await page.goto('/settings/providers'); + await expect(page.getByText(t('settings.providers.configured'), {exact: true}).first()).toBeVisible(); + const card = page + .locator('div') + .filter({has: page.getByRole('heading', {name: providerName, exact: true})}) + .filter({has: page.locator('.lucide-settings-2')}) + .last(); + await card.getByRole('button').filter({has: page.locator('.lucide-settings-2')}).click(); + await expect(page.getByTestId('provider-protocols')).toBeVisible(); +} + +test.describe('native endpoints', () => { + test.afterEach(async ({api, seed}) => { + await api.put(`/api/v1/admin/providers/${seed.providerId}`, {protocols: []}); + }); + + test('a provider lists the protocols it serves natively from its dialog', async ({page, t, api, seed}) => { + const provider = await api.get(`/api/v1/admin/providers/${seed.providerId}`); + await openProvider(page, t, provider.name); + await expect(page.getByTestId('provider-protocols')).toContainText(t(`developer.protocol.${own}`)); + + await page.getByTestId('provider-protocols').click(); + await expect(page.getByTestId(`provider-protocol-${own}`)).toHaveAttribute('data-disabled', ''); + await expect(page.getByTestId(`provider-protocol-${extra}`)).toContainText(`${provider.base_url}/v1/`); + await page.getByTestId(`provider-protocol-${extra}`).click(); + await page.keyboard.press('Escape'); + await expect(page.getByTestId('provider-protocols')).toContainText(t(`developer.protocol.${extra}`)); + + await page.getByRole('dialog').getByRole('button', {name: t('common.save'), exact: true}).click(); + await expect(page.getByText(t('settings.providers.save_success')).first()).toBeVisible(); + expect((await api.get(`/api/v1/admin/providers/${seed.providerId}`)).protocols).toEqual([extra]); + }); + + test('developer models show which endpoints are passed through and which are converted', async ({page, t, api, seed}) => { + await createKeyViaApi(api, seed.teamId, uniqueName('routes-key')); + await api.put(`/api/v1/admin/providers/${seed.providerId}`, {protocols: [extra]}); + await page.goto('/developer/models'); + const row = page.getByTestId(`model-row-${seed.model.publicId}`); + await expect(row).toBeVisible(); + + const native = row.getByTestId('model-routes-native'); + await expect(native).toHaveAttribute('aria-label', new RegExp(t('developer.models.routes_native'))); + await expect(native).toHaveAttribute('aria-label', extra === 'messages' ? /\/anthropic\/v1\/messages/ : /\/openai\/v1\/chat\/completions/); + await expect(native).toHaveAttribute('tabindex', '0'); + await native.hover(); + await expect(page.getByText(t('developer.models.routes_native'), {exact: true}).first()).toBeVisible(); + await expect(row.getByTestId('model-routes-converted')).toHaveAttribute('aria-label', new RegExp(t(`developer.protocol.${own}`))); + + const third = ['chat', 'responses', 'messages'].find(protocol => protocol !== own && protocol !== extra)!; + await page.getByTestId('model-native-filter').click(); + await page.getByRole('option', {name: t('developer.models.native_filter').replace('{protocol}', t(`developer.protocol.${extra}`))}).click(); + await expect(row).toBeVisible(); + await page.getByTestId('model-native-filter').click(); + await page.getByRole('option', {name: t('developer.models.native_filter').replace('{protocol}', t(`developer.protocol.${third}`))}).click(); + await expect(row).toHaveCount(0); + }); + + test('an Anthropic Messages request reaches a router that speaks Messages natively', async ({page, api, seed}) => { + test.skip(LLM.isMock || LLM.kind !== 'OPENROUTER', 'needs a real router that serves Anthropic Messages'); + await api.put(`/api/v1/admin/providers/${seed.providerId}`, {protocols: ['messages']}); + const key = await createKeyViaApi(api, seed.teamId, uniqueName('native-messages')); + try { + const response = await page.request.post('/anthropic/v1/messages', { + headers: {'x-api-key': key.token, 'anthropic-version': '2023-06-01'}, + data: {model: seed.model.publicId, max_tokens: 20, messages: [{role: 'user', content: 'Say hi'}]}, + failOnStatusCode: false, + }); + expect(response.status(), await response.text()).toBe(200); + expect((await response.json()).type).toBe('message'); + const log = await waitForLog(api, key.id, response.headers()['x-request-id']); + expect(Number(log.input_tokens)).toBeGreaterThan(0); + } finally { + await api.post(`/api/v1/developer/keys/${key.id}/revoke`); + } + }); +}); diff --git a/frontend/components/developer/ModelRoutes.vue b/frontend/components/developer/ModelRoutes.vue new file mode 100644 index 00000000..8d195f3d --- /dev/null +++ b/frontend/components/developer/ModelRoutes.vue @@ -0,0 +1,55 @@ + + + diff --git a/frontend/pages/developer/models.vue b/frontend/pages/developer/models.vue index 89e712dd..ae37064e 100644 --- a/frontend/pages/developer/models.vue +++ b/frontend/pages/developer/models.vue @@ -32,6 +32,15 @@ {{ typeLabel(type) }} + + + + {{ store.getTranslation('developer.models.native_filter_all') }} + + {{ store.getTranslation('developer.models.native_filter', {protocol: store.getTranslation(`developer.protocol.${protocol}`)}) }} + + + @@ -77,6 +86,7 @@ + {{ store.getTranslation('developer.models.routes') }} {{ store.getTranslation('developer.models.features') }} @@ -101,6 +111,9 @@ + + +
@@ -132,6 +145,7 @@ import {ArrowDown, ArrowUp, Copy, Eye, FlaskConical, Image, Search, Sparkles, Wr import {useMainStore} from '@/stores'; import {useDeveloperStore} from '@/stores/developerStore'; import type {DeveloperModel} from '~/types/developer'; +import {CHAT_PROTOCOLS} from '~/types/generated/protocols'; type SortColumn = 'name' | 'type' | 'provider' | 'context' | 'input' | 'output'; @@ -158,6 +172,7 @@ const query = ref(''); const providerFilter = ref('all'); const teamFilter = ref('all'); const typeFilter = ref('all'); +const nativeFilter = ref('all'); const active = ref(new Set()); const sortBy = ref('name'); const sortDescending = ref(false); @@ -168,6 +183,8 @@ function typeLabel(type: string): string { return store.getTranslation(`developer.model_type.${type}`); } +const hasRoutes = computed(() => developer.models.some(model => model.routes.length > 0)); + const providers = computed(() => [...new Set(developer.models.map(model => model.provider))].sort((a, b) => a.localeCompare(b))); function knownPrice(value: string | null): number | null { @@ -191,6 +208,7 @@ const visible = computed(() => { .filter(model => !needle || `${model.display_name} ${model.id}`.toLowerCase().includes(needle)) .filter(model => typeFilter.value === 'all' || model.type === typeFilter.value) .filter(model => providerFilter.value === 'all' || model.provider === providerFilter.value) + .filter(model => nativeFilter.value === 'all' || model.routes.some(route => route.native && route.inbound === nativeFilter.value)) .filter(model => teamFilter.value === 'all' || model.team_ids.includes(teamFilter.value)) .filter(model => features.every(feature => feature.matches(model))) .sort((a, b) => { diff --git a/frontend/pages/settings/providers.vue b/frontend/pages/settings/providers.vue index d6e5b13e..22e35c45 100644 --- a/frontend/pages/settings/providers.vue +++ b/frontend/pages/settings/providers.vue @@ -191,6 +191,41 @@
+
+ {{ store.getTranslation('settings.providers.protocols') }} + + + + + {{ store.getTranslation(`developer.protocol.${protocol}`) }} + {{ store.getTranslation('settings.providers.protocols_none') }} + + + + + + + + + {{ store.getTranslation(`developer.protocol.${protocol}`) }} + · {{ store.getTranslation('settings.providers.protocols_own') }} + + {{ upstreamUrl(protocol) }} + + + + +

{{ store.getTranslation('settings.providers.protocols_hint') }}

+
+
{{ store.getTranslation('settings.providers.reported_cost') }} @@ -338,7 +373,7 @@