Repository navigation
feat(server): add OpenRouter provider and make sentiment provider-agnostic - #708
Conversation
…ostic Sentiment analysis called `openai.responses.create()` directly with a hard-coded `gpt-5-mini`, and it runs on both tracking paths — the API worker and the Cloro result handler. That made OPENAI_API_KEY mandatory for every self-host install, including ones tracking Claude only or reading every engine through Cloro. It was the last hard dependency on an OpenAI account. Sentiment now routes through resolveModel() like every other analysis task, so SENTIMENT_MODEL accepts any configured provider. The default stays openai/gpt-5-mini, so existing deployments are unaffected. Also registers OpenRouter in the provider registry: one key for every upstream model, for analysis tasks only. Prompt tracking deliberately stays on the first-party SDKs — it depends on provider-hosted web search (OpenAI `web_search`, Anthropic `web_search_20250305`), which OpenRouter does not relay. OpenRouter is wired through `.chat()` rather than the provider's default call: @ai-sdk/openai defaults to OpenAI's Responses API, which OpenRouter does not implement, so every request would 404 on /responses. openai-tracker.js is left untouched; only the re-export in ai-tracker.js moves. Tests: 12 new cases covering default preservation, provider routing, nested OpenRouter model ids, the Chat Completions wiring, response truncation, and both degrade-to-neutral paths. Full suite: 186 passing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
There was a problem hiding this comment.
Welcome to Ansvisor, and thank you for your first PR! A maintainer will be by soon to review.
In the meantime, two things that make review faster:
- A short description of why the change matters, not just what it does — most of our PRs link a
Fixes #...to the issue that explains the why. - A quick local test note if there's anything worth eyeballing in the browser.
If you'd like to keep an eye on where Ansvisor goes next, a ⭐ on the repo helps others discover it (and Watch sends you a ping when related issues land). Either way — looking forward to your next one.
Verified against the live OpenRouter endpoint: `confidence: z.number().min(0).max(1)` emits `minimum`/`maximum` in the JSON Schema, and Anthropic rejects those in strict structured-output mode: output_config.format.schema: For 'number' type, properties maximum, minimum are not supported OpenRouter surfaces this as a 400 from every backing provider it tried — Anthropic, Azure and Bedrock — so `SENTIMENT_MODEL=openrouter/anthropic/claude-haiku-4.5` degraded to neutral on every call. Silent, because the function is designed never to throw. The range is now enforced in code, as the original OpenAI implementation did with `Math.max(0, Math.min(1, ...))`. Non-numeric or NaN falls back to 0.5. Live check with claude-haiku-4.5 through OpenRouter, three fixtures: positive 0.95, neutral 0.95, negative 0.92 — with coherent reasoning on each. Tests: 189 passing. Adds a guard asserting the emitted JSON Schema carries no minimum/maximum, plus clamping cases. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
Update: live-tested against OpenRouter now, which surfaced a real bug in the first commit. Fixed in The zod schema had OpenRouter returned it as a 400 from every backing provider it tried — Anthropic, Azure, Bedrock. So The range is now clamped in code, exactly as the original OpenAI implementation did with Live results with
Reasoning was coherent on each — the neutral case correctly identified the mention as a bare listing with no evaluative language. Worth noting for anyone else adding providers here: this only shows up at runtime. 189 tests passing, lint and format clean. |
gkhngyk
left a comment
There was a problem hiding this comment.
Excellent PR — accurate diagnosis, a faithful refactor, and the write-up made it reviewable in one pass. I verified the claims rather than taking them on trust, and ran the OpenRouter path against a live key since you flagged it as unexercised.
Live OpenRouter results
The wiring works, including structured outputs:
| Model | Result | Latency |
|---|---|---|
openrouter/anthropic/claude-haiku-4.5 |
3/3 correct, confidence 0.92–0.95 | ~2–3s |
openrouter/google/gemini-3-flash-preview |
3/3 correct, confidence 0.95–0.99 | ~1.5s |
openrouter/google/gemini-3.6-flash |
3/3 correct, confidence 0.98 | ~2s |
Positive, negative and neutral inputs each classified correctly on every model, so the strict: true JSON schema is relayed to the upstream providers intact — which also confirms your reasoning about leaving minimum/maximum off confidence.
The wiring detail you called out holds up: resolveModel('openrouter/anthropic/claude-haiku-4.5') gives provider openai.chat and model id anthropic/claude-haiku-4.5, so nested ids survive the first-slash split and requests go to Chat Completions rather than /responses.
The degrade path is real too, not just unit-tested: pointing SENTIMENT_MODEL at a nonexistent model returns a 400 from OpenRouter and the function resolves to { sentiment: 'neutral', confidence: 0, reason: 'Analysis failed' } with the error logged. A tracking result is never lost to a sentiment failure.
One correction, in the description rather than the code
The PR body suggests AUDIT_LLM_MODEL=openrouter/google/gemini-3-flash. That id doesn't exist on OpenRouter — it 400s with "is not a valid model ID". The working id is google/gemini-3-flash-preview (or google/gemini-3.6-flash). .env.example is fine, so nothing to change in the tree; worth fixing in the description so nobody copies it.
One request
analyzeSentimentAI in openai-tracker.js is now unreachable — ai-tracker.js re-exports the new one, and both call sites (tracking-worker.js and cloro-result-handler.js) go through that re-export. Could you delete the old implementation in this PR? Two implementations of the same function is an invitation for someone to fix a bug in the wrong one. runPrompt in that file stays, obviously.
What else I checked
- Both tracking paths pick up the new implementation through the one-line re-export change — nothing else needed touching.
- The refactor is behaviour-preserving: same default model, same 3000-character slice, same enum, same
[0,1]clamp, same neutral fallback. Structured output replacingJSON.parseof free text is a straight improvement. openai-tracker.jsis the only place using the OpenAI SDK directly andgetClient()is lazy, so your headline claim is right: after this, a Cloro-only or Anthropic-only install genuinely needs noOPENAI_API_KEY.- OpenRouter isn't registered without its key, so this is inert for every existing deployment.
servertests and lint locally: 189 passing, clean.
Approving. One thing we'll watch on our side after deploy: our production has no SENTIMENT_MODEL set, so it stays on openai/gpt-5-mini — same model, but now reached through generateObject instead of a raw Responses call, so we'll confirm the sentiment column keeps populating on the first nightly run.
Thanks also for #709 — that one is confirmed and being handled separately.
What & why
Sentiment analysis was the last hard dependency on an OpenAI account.
analyzeSentimentAIcalledopenai.responses.create()directly with a hard-codedgpt-5-mini, and it runs on both tracking paths — the API worker (tracking-worker.js) and the Cloro result handler. SoOPENAI_API_KEYwas mandatory for every self-hosted install, including one tracking Claude only, or reading every engine through Cloro. Without it, sentiment silently degraded to neutral on every mentioned brand — precisely the rows that matter.Sentiment now routes through
resolveModel()like every other analysis task, soSENTIMENT_MODELaccepts any configured provider. The default staysopenai/gpt-5-mini, so existing deployments are unaffected.While in there, this also registers OpenRouter in the provider registry — one key for every upstream model, for analysis tasks only.
Scope: analysis only, never tracking
Prompt tracking deliberately stays on the first-party SDKs. It depends on provider-hosted web search (
web_searchon OpenAI's Responses API,web_search_20250305on Anthropic's Messages API), which OpenRouter does not relay — routing tracking through it would silently change what is being measured and where citations come from. Only suggestions, audit signals and sentiment are affected.One wiring detail worth flagging
OpenRouter is registered through
.chat()rather than the provider's default call:@ai-sdk/openaidefaults to OpenAI's Responses API, which OpenRouter does not implement — every request would 404 on/responses. This is covered by a regression test, since a plaincreateOpenAI({ baseURL })looks correct and fails only at runtime.Nested model ids survive the prefix split:
openrouter/anthropic/claude-haiku-4.5resolves toanthropic/claude-haiku-4.5, becauseresolveModel()splits on the first slash only.Changes
server/src/lib/sentiment.jsgenerateObject+ zod schemaserver/src/lib/sentiment.test.jsserver/src/lib/ai-provider.js.chat()server/src/lib/ai-provider.test.jsserver/src/lib/ai-tracker.jssentiment.js(1 line)server/.env.exampleOPENROUTER_API_KEYandSENTIMENT_MODELopenai-tracker.jsis left untouched — the old implementation is still there, unused.How to test
Behaviour, with no config change: sentiment keeps resolving
openai/gpt-5-mini.Dropping the OpenAI requirement:
# server/.env — no OPENAI_API_KEY needed ANTHROPIC_API_KEY=sk-ant-... SENTIMENT_MODEL=anthropic/claude-haiku-4-5Via OpenRouter:
Then run tracking on a brand that gets mentioned and confirm the sentiment column is populated rather than neutral.
No UI changes, so no screenshots.
Note
Live OpenRouter calls have not been exercised yet — the wiring, resolution path and both degrade-to-neutral branches are unit-tested, but no request has hit the real endpoint. Worth a maintainer sanity check with a real key before merge. Models used for analysis must support structured outputs (Claude Haiku and Gemini Flash do).
Unrelated:
mainis currently broken for fresh installsWhile setting this up: migration
00048_gsc_suggestion_support.sqlrunsALTER TABLE public.prompt_suggestions, but no migration creates that table —grep -rn "prompt_suggestions" supabase/migrations/only ever findsALTER/comments.supabase startfails on a clean database with:schema.sqlinherits the same gap, being a concatenation of the migrations. Not touched here — happy to open a separate issue.