Repository navigation
feat(settings): add OpenAI, Gemini, Azure OpenAI and OpenRouter keys for Chat - #1210
Conversation
…ection its own address Settings › Agent holds the API key Chat runs on, so it's AI Providers now, with a description of what the key does and who pays for it. Each section has an address, /dashboard/settings/<section>: the Chat page's "Go to Settings" links to /dashboard/settings/ai-providers, and picking a section moves the address to it. /dashboard/settings?tab= still opens the section it names (the Daily Pulse e-mail and the integrations' OAuth return use it), and ?tab=agent opens AI Providers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…for Chat Settings › AI Providers now keeps one encrypted key per provider (Anthropic, OpenAI, Google Gemini, Microsoft Azure OpenAI, OpenRouter) in organization_ai_keys (migration 00188, service role only; existing Anthropic keys carry over as the one Chat uses) and lets admins pick the one Chat uses (set_active_ai_provider). Chat builds its model from that provider: claude-sonnet-5, gpt-5.5 and gemini-3.5-flash unless a model is named, an Azure deployment on the resource's own endpoint, or an OpenRouter model over Chat Completions. /api/settings/ai-providers replaces /api/settings/anthropic-key; adds @ai-sdk/openai, @ai-sdk/google and @ai-sdk/azure. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-keys # Conflicts: # web/messages/en.json # web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx # web/src/components/settings/agent-section.tsx
|
@gkhngyk This is part 2 of AI Providers, after #1209. Three things only you can do or decide:
|
gkhngyk
left a comment
There was a problem hiding this comment.
The security side holds up:
- The key stays on the server. GET never selects
key_encrypted. - The org comes from the profile, and the admin check runs on the server.
- The table and the switch function are service-role only.
- The Azure check parses the URL properly. It matches the suffix on the parsed hostname and stores only the origin.
x.openai.azure.com.evil.com,evil.com/.openai.azure.com,[email protected]and the encoded variants are all refused. - The migration copies the old envelopes as they are.
The five new test files pass (30 of 30).
Before merge:
- Step 7 with real keys.
- The unit tests stub
fetch, so no provider has yet accepted the 14 tool schemas or a multi-step tool loop. - Captured requests show two weak spots:
- Gemini gets
render_audit.recommendationswith an emptyitems: {}, andrender_chart.datarows as a bare{type: object}. - OpenAI's Responses API falls back from strict mode for our optional fields.
- Gemini gets
- Please send one Chat message per provider that calls tools,
render_chartincluded, and check that token usage is recorded.
- The unit tests stub
storeon OpenAI and Azure.streamTextpasses noproviderOptions, so@ai-sdk/openaikeepsstore: true.- Saved assistant turns carry OpenAI item ids in
providerMetadata, and they go back out asitem_references instead of text. - An existing thread then fails with "item not found" in three cases: the key is replaced by one from another OpenAI project, the stored items expire, or the org has zero data retention.
- The app keeps the full history, so pass
providerOptions: { openai: { store: false }, azure: { store: false } }.
- Removing the Anthropic key leaves the old copy.
- DELETE and PUT never touch
organizations.anthropic_api_key_*, so a removed key stays encrypted there. - A rollback to the old web would bring it back.
- A key changed through the old route between 00188 and the web deploy also leaves the new table stale (
on conflict do nothing). - For
anthropic, null the old columns on DELETE and PUT.
- DELETE and PUT never touch
Not blocking:
- Removing the active key is three calls: delete, then select the next key, then switch.
- The select's error isn't checked, so a failed read returns
ok: truewith no key active. - A "Use for Chat" click in between can be overridden.
- PUT's "is anything active?" read has the same gap.
- A
remove_ai_provider_key(org, provider)function that locks the org's rows (for update) and promotes in one transaction would fix all three. The lock also removes the duplicate-key 500 on two switches at once.
- The select's error isn't checked, so a failed read returns
- Token usage:
onFinishreadsusage, which in ai v6 is the last step only.totalUsagecovers a turn with tool calls. This predates the PR, but step 7 relies on it. - Two copies of the SDK in
yarn.lock:[email protected]and@ai-sdk/[email protected]stay onprovider-utils4.0.27, and the new packages bring 4.0.61.- 4.0.27's
addAdditionalPropertiesToJsonSchemasetsadditionalProperties: falseon records too, sorender_chart.datarows describe objects with no keys. - Moving
ai,@ai-sdk/anthropicand@ai-sdk/reactto their current v6 releases leaves one copy, here or in a follow-up chore.
- 4.0.27's
- Model ids: they accept
.., and the Gemini SDK puts the id in the URL path. Refuse.., or/outside OpenRouter. - Repo conventions:
- 00188 has no
notify pgrst, 'reload schema';at the end. types/supabase.tsisn't regenerated.schema.sqlwill need a rebuild when it lands after the AI Traffic stack.
- 00188 has no
- Stale comments: a few still say "Anthropic key" or "Settings → Agent":
config/plans.ts:172,sidebar.tsx:125and:342,mobile-nav.tsx:104,key-encryption.ts:4and:99.
…opic key copy Chat passes store: false to OpenAI and Azure, so saved turns go back as text rather than as references to stored response items, and bills every step (totalUsage). Saving or removing an Anthropic key clears its old copy on organizations. Switching and removing keys run in database functions that lock the organization's keys (remove_ai_provider_key promotes the next key in the same transaction; set_active_ai_provider takes p_only_if_none for a first key). Model ids refuse '..' and a '/' outside OpenRouter; render_audit's recommendations get a typed item schema; 00188 reloads PostgREST's schema; the Supabase types and stale comments are updated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk Thanks for the thorough pass. Fixed in a011b32, after merging main: Before-merge items
Non-blocking, also done
Not done here
Checks: web 1,725 tests pass, plus lint, typecheck and build. |
…-keys # Conflicts: # supabase/schema.sql
…-keys # Conflicts: # supabase/schema.sql
…-keys # Conflicts: # supabase/schema.sql
…-keys # Conflicts: # supabase/schema.sql
…-keys # Conflicts: # supabase/schema.sql
…-keys # Conflicts: # supabase/schema.sql
…-keys # Conflicts: # supabase/schema.sql
gkhngyk
left a comment
There was a problem hiding this comment.
The fixes check out:
store: false, so a saved history goes out with encrypted reasoning instead ofitem_references;- the old Anthropic columns are cleared on PUT and DELETE;
remove_ai_provider_keyandset_active_ai_provider(..., p_only_if_none), service-role only, with the org's rows locked;totalUsage;- the model id checks;
notify pgrst, the regenerated types and the stale comments.
It merges cleanly into main, and 00188 is still the next number.
Left before merge is step 7 with real keys, which I'll run. Two things to watch for there:
- An Azure deployment not named after its model (e.g.
chatrunning gpt-5.x). The SDK reads the deployment name as the model id, so it doesn't ask forreasoning.encrypted_content, and withstore: falsethe reasoning items are dropped between tool steps. If the second turn or a tool loop fails on such a deployment, an Azure "reasoning model" setting mapped toproviderOptions.azure.forceReasoningwould fix it. - Empty
render_chartrows on OpenAI or Azure.[email protected]'sprovider-utils4.0.27 closes record schemas (additionalProperties: false). If that shows up, the SDK bump shouldn't wait for the chore PR.
Deploy: I'll apply 00188 right before the merge. An Anthropic key changed through the old route between the two would otherwise leave the new table stale.
Later column drop: guard_organization_server_columns (00062) reads NEW.anthropic_api_key_*, so it needs updating in the same migration.
…-keys # Conflicts: # supabase/schema.sql
gkhngyk
left a comment
There was a problem hiding this comment.
Approving so step 7 can run on production with real keys.
00188 is applied on the hosted DB, and the five organizations' Anthropic keys carried over as the active provider. The last merge of main differs from a clean re-merge only in schema.sql's conflict resolution.
Tested on top of the current main: web and server tests, tsc, lint and Prettier pass, and schema.sql matches a rebuild. That includes the new SDK packages, installed from this branch's lockfile.
The real-key Chat check for each provider follows right after the deploy. The two things to watch from the last review (an Azure deployment not named after its model, and empty render_chart rows on OpenAI/Azure) are part of it.
Summary
Settings › AI Providers lets an organization add its own key for each of five providers, and choose which one Chat uses. This is part 2 of 2 for the AI Providers task; part 1 (#1209, the rename and its own address) is merged.
Providers:
claude-sonnet-5gpt-5.5gemini-3.5-flashFor the first three, the form takes an optional model in place of the default.
Database (migration 00188):
organization_ai_keysholds one row per organization and provider.key-encryption.ts, withlast4for display.settings(jsonb) holds the Azure endpoint and deployment, or a model.activemarks the provider Chat uses, at most one per organization (partial unique index).set_active_ai_provider(org, provider)switches the provider in one transaction: others off first, since the unique index is checked row by row. It is service role only.organizations.anthropic_api_key_*carry over as the provider Chat uses. The old columns are left in place, so a deploy in between doesn't lock Chat. Dropping them is a follow-up.Chat:
resolveAgentModelConfig(orgId)reads the active row; on self-host it still uses the envANTHROPIC_API_KEY.buildAgentModel({ provider, apiKey, settings })builds the model:createAzure({ baseURL: <endpoint>/openai })(deployment).createOpenAI({ baseURL: openrouter }).chat(model), because it has no Responses API.*.openai.azure.com,*.services.ai.azure.comor*.cognitiveservices.azure.com, the hosts@ai-sdk/azuretreats as Azure. It is stored as its origin, so the server never calls an arbitrary host.missing_ai_key(wasmissing_anthropic_key). Nothing in the UI read that code.API:
/api/settings/ai-providersreplaces/api/settings/anthropic-key.configuredplus each saved provider.?provider=). If Chat's key is removed, the most recently saved other key takes over.The sidebar badge and Chat's key gate read
configuredfrom the new route.UI:
New dependencies (approved):
@ai-sdk/openai,@ai-sdk/google,@ai-sdk/azure, all v3 alongsideai@6.yarn.lockis updated, andyarn install --frozen-lockfilepasses.Related issue
Follows #1209.
Type of change
feat— New featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
NEXT_PUBLIC_IS_CLOUD=true) with a realANSVISOR_ENCRYPTION_KEY./dashboard/settings/ai-providersas an admin. Add a key for one provider; it becomes "Used by Chat".https://example.com. The form refuses it ("Enter your resource's endpoint…").I checked steps 2–6 locally with fake keys, in light and dark themes, at 1440 and 1024 px. Step 7 needs real keys, so I haven't run it.
Tests:
providers.test.ts: settings parsing, the Azure host check, model ids.model.test.ts: each provider's model; the Azure and OpenRouter request URLs and headers, caught before they leave.key.test.ts: cloud and self-host key resolution.route.test.ts: roles, validation, first-key-active, switching, removing the active key.ai-providers-section.test.tsx: rows, switching, Azure endpoint check, removing, the member view.Also checked:
set_active_ai_provideron the dev DB in a rolled-back transaction.Deploy order: 00188, then web.
npm run version:checkfails on main too: the compose images say 0.2.0. That predates this PR and is left as is.Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)Also run:
yarn test(1,722 pass) andyarn build(with the CI placeholders), plusbash supabase/build-schema.sh(schema.sql included).🤖 Generated with Claude Code