Skip to content

feat(settings): add OpenAI, Gemini, Azure OpenAI and OpenRouter keys for Chat - #1210

Merged
gkhngyk merged 13 commits into
ansvisor:mainfrom
cihan-gyk:feature/ai-provider-keys
Oct 22, 2026
Merged

gkhngyk merged 13 commits into
ansvisor:mainfrom
cihan-gyk:feature/ai-provider-keys

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

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:

Provider Default model Needs besides the key
Anthropic claude-sonnet-5 —
OpenAI gpt-5.5 —
Google Gemini gemini-3.5-flash —
Microsoft Azure OpenAI — endpoint + deployment
OpenRouter — model id

For the first three, the form takes an optional model in place of the default.

Database (migration 00188):

  • Table: organization_ai_keys holds one row per organization and provider.
    • The key is stored as the AES-256-GCM envelope from key-encryption.ts, with last4 for display.
    • settings (jsonb) holds the Azure endpoint and deployment, or a model.
    • active marks the provider Chat uses, at most one per organization (partial unique index).
  • Access: RLS is on with no policies, so only the service role can read or write it.
  • Switching: 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.
  • Existing keys: Anthropic keys in 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 env ANTHROPIC_API_KEY.
  • buildAgentModel({ provider, apiKey, settings }) builds the model:
    • Azure: createAzure({ baseURL: <endpoint>/openai })(deployment).
    • OpenRouter: createOpenAI({ baseURL: openrouter }).chat(model), because it has no Responses API.
  • Endpoint check: an Azure endpoint must be https on *.openai.azure.com, *.services.ai.azure.com or *.cognitiveservices.azure.com, the hosts @ai-sdk/azure treats as Azure. It is stored as its origin, so the server never calls an arbitrary host.
  • Missing key: a missing key returns missing_ai_key (was missing_anthropic_key). Nothing in the UI read that code.

API: /api/settings/ai-providers replaces /api/settings/anthropic-key.

  • GET: any member; returns configured plus each saved provider.
  • PUT: admin only. Saves a key with its settings; the first key saved becomes Chat's.
  • PATCH: admin only. Switches Chat's provider.
  • DELETE: admin only (?provider=). If Chat's key is removed, the most recently saved other key takes over.

The sidebar badge and Chat's key gate read configured from the new route.

UI:

  • Each provider gets its own row, with:
    • its logo;
    • "Used by Chat" or "Key saved";
    • the last 4 characters of the key, the model, and who saved it and when.
  • Admins see Add key / Replace, Use for Chat and Remove (with a confirmation). The form shows each provider's own fields and a link to where to get a key.
  • Members see an admin-only notice.
  • Rows lay out by their own width (container query).

New dependencies (approved): @ai-sdk/openai, @ai-sdk/google, @ai-sdk/azure, all v3 alongside ai@6. yarn.lock is updated, and yarn install --frozen-lockfile passes.

Related issue

Follows #1209.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Apply 00188 and run the web app in cloud mode (NEXT_PUBLIC_IS_CLOUD=true) with a real ANSVISOR_ENCRYPTION_KEY.
  2. Open /dashboard/settings/ai-providers as an admin. Add a key for one provider; it becomes "Used by Chat".
  3. Add a second key and click Use for Chat on it.
  4. For Azure, try an endpoint such as https://example.com. The form refuses it ("Enter your resource's endpoint…").
  5. Remove Chat's key. The other key takes over. Remove both, and Chat shows "Add an AI provider key".
  6. As a member, the rows show without buttons, with the admin-only notice.
  7. With real keys: send a Chat message on each provider. The tools must work, and token usage must be recorded.

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_provider on the dev DB in a rolled-back transaction.

Deploy order: 00188, then web.

  • Numbering: the number follows the open AI Traffic stack (00181–00187), so the numbers don't clash whichever merges first.
  • Version check: npm run version:check fails on main too: the compose images say 0.2.0. That predates this PR and is left as is.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run: yarn test (1,722 pass) and yarn build (with the CI placeholders), plus bash supabase/build-schema.sh (schema.sql included).

🤖 Generated with Claude Code

cihan-gyk and others added 3 commits October 19, 2026 20:05
…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
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk This is part 2 of AI Providers, after #1209. Three things only you can do or decide:

  1. Real keys. Could you send one Chat message per provider with real keys? I could only test with fake keys:
    • Chat must answer with tool calls.
    • agent_token_usage must record the turn.
    • Gemini: the AI SDK converts our tool schemas for Google. Please check that a tool call (e.g. list_brands) works.
    • Azure: this uses the v1 Responses API (<endpoint>/openai/v1/responses?api-version=v1). Older resources that only have deployment URLs would need useDeploymentBasedUrls; tell me if you see a 404 there.
  2. Default models. Are gpt-5.5 and gemini-3.5-flash the right defaults? Admins can name another model in the form either way.
  3. Old columns. Should the follow-up drop organizations.anthropic_api_key_* once 00188 is on prod? The keys there are copied, and nothing reads the columns after this PR.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 19, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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.recommendations with an empty items: {}, and render_chart.data rows as a bare {type: object}.
      • OpenAI's Responses API falls back from strict mode for our optional fields.
    • Please send one Chat message per provider that calls tools, render_chart included, and check that token usage is recorded.
  2. store on OpenAI and Azure.
    • streamText passes no providerOptions, so @ai-sdk/openai keeps store: true.
    • Saved assistant turns carry OpenAI item ids in providerMetadata, and they go back out as item_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 } }.
  3. 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.

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: true with 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.
  • Token usage: onFinish reads usage, which in ai v6 is the last step only. totalUsage covers 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 on provider-utils 4.0.27, and the new packages bring 4.0.61.
    • 4.0.27's addAdditionalPropertiesToJsonSchema sets additionalProperties: false on records too, so render_chart.data rows describe objects with no keys.
    • Moving ai, @ai-sdk/anthropic and @ai-sdk/react to their current v6 releases leaves one copy, here or in a follow-up chore.
  • 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.ts isn't regenerated.
    • schema.sql will need a rebuild when it lands after the AI Traffic stack.
  • Stale comments: a few still say "Anthropic key" or "Settings → Agent": config/plans.ts:172, sidebar.tsx:125 and :342, mobile-nav.tsx:104, key-encryption.ts:4 and :99.

cihan-gyk and others added 2 commits October 19, 2026 22:54
…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]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Thanks for the thorough pass. Fixed in a011b32, after merging main:

Before-merge items

  1. Step 7 (real keys). I can't run it: my local API has no provider keys, and per our split, key testing is yours. Could you send one Chat message per provider that calls tools (render_chart included) and check agent_token_usage?
    • render_audit: I captured the requests the way you did. recommendations now has a typed item schema; it had items: {}.
    • Records: categoryScores and the render_chart rows still go to Gemini as {type: object}. That is how @ai-sdk/google writes an empty-object schema on purpose (isEmptyObjectSchema), so I left them.
    • If Gemini refuses them, I'll restructure those two inputs in a follow-up, with the SDK dedupe below.
  2. store: false. AGENT_PROVIDER_OPTIONS = { openai: { store: false }, azure: { store: false } } goes to streamText. model.test.ts now checks that the OpenAI and Azure request bodies carry store: false.
  3. The old Anthropic copy. Saving or removing the anthropic key also nulls organizations.anthropic_api_key_*, with the error checked.
    • The stale window you mention (a key changed through the old route between 00188 and the web deploy) isn't covered by this. Since migrations go in at merge with the deploy, I left it. Say if you want a backfill step instead.

Non-blocking, also done

  • Locking:
    • remove_ai_provider_key(org, provider) locks the org's rows (for update), deletes, and promotes the most recently saved key in the same transaction. DELETE now makes one call.
    • set_active_ai_provider takes the same lock and has p_only_if_none, which PUT uses for a first key, so the "anything active?" read is gone.
    • Both are service-role only. I checked them on the dev DB in a rolled-back transaction.
  • Token usage: onFinish reads totalUsage.
  • Model ids: .. is refused, and so is / outside OpenRouter (tests added).
  • Repo conventions: 00188 ends with notify pgrst, 'reload schema';, and types/supabase.ts has the table and both functions.
  • Stale comments: fixed in plans.ts, sidebar.tsx (both), mobile-nav.tsx and key-encryption.ts (both).

Not done here

  • SDK dedupe (ai, @ai-sdk/anthropic, @ai-sdk/react to their current v6): a separate chore PR, since it bumps the packages Chat runs on today. I'll open it once step 7 tells us whether Gemini needs it.
  • schema.sql: it will need a rebuild when this lands after the AI Traffic stack.

Checks: web 1,725 tests pass, plus lint, typecheck and build. schema.sql is rebuilt.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fixes check out:

  • store: false, so a saved history goes out with encrypted reasoning instead of item_references;
  • the old Anthropic columns are cleared on PUT and DELETE;
  • remove_ai_provider_key and set_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. chat running gpt-5.x). The SDK reads the deployment name as the model id, so it doesn't ask for reasoning.encrypted_content, and with store: false the 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 to providerOptions.azure.forceReasoning would fix it.
  • Empty render_chart rows on OpenAI or Azure. [email protected]'s provider-utils 4.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.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@gkhngyk
gkhngyk merged commit b2ff68f into ansvisor:main Oct 22, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants