Skip to content

feat(server): add OpenRouter provider and make sentiment provider-agnostic - #708

Merged
gkhngyk merged 2 commits into
ansvisor:mainfrom
mikam44700:feat/openrouter-and-provider-agnostic-sentiment
Aug 12, 2026
Merged

gkhngyk merged 2 commits into
ansvisor:mainfrom
mikam44700:feat/openrouter-and-provider-agnostic-sentiment

Conversation

@mikam44700

Copy link
Copy Markdown
Contributor

What & why

Sentiment analysis was the last hard dependency on an OpenAI account.

analyzeSentimentAI called openai.responses.create() directly with a hard-coded gpt-5-mini, and it runs on both tracking paths — the API worker (tracking-worker.js) and the Cloro result handler. So OPENAI_API_KEY was 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, so SENTIMENT_MODEL accepts any configured provider. The default stays openai/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_search on OpenAI's Responses API, web_search_20250305 on 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:

providers.openrouter = (modelId, options) => openrouter.chat(modelId, options);

@ai-sdk/openai defaults 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 plain createOpenAI({ baseURL }) looks correct and fails only at runtime.

Nested model ids survive the prefix split: openrouter/anthropic/claude-haiku-4.5 resolves to anthropic/claude-haiku-4.5, because resolveModel() splits on the first slash only.

Changes

File Change
server/src/lib/sentiment.js New. Provider-agnostic sentiment via generateObject + zod schema
server/src/lib/sentiment.test.js New. 7 cases
server/src/lib/ai-provider.js OpenRouter registered, via .chat()
server/src/lib/ai-provider.test.js New. 5 cases
server/src/lib/ai-tracker.js Re-export moved to sentiment.js (1 line)
server/.env.example Documents OPENROUTER_API_KEY and SENTIMENT_MODEL

openai-tracker.js is left untouched — the old implementation is still there, unused.

How to test

cd server && npm test          # 186 passing (12 new)
npm run lint                   # clean
npm run format:check           # clean
npm run version:check          # all at v0.2.0

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-5

Via OpenRouter:

OPENROUTER_API_KEY=sk-or-v1-...
SENTIMENT_MODEL=openrouter/anthropic/claude-haiku-4.5
AUDIT_LLM_MODEL=openrouter/google/gemini-3-flash

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: main is currently broken for fresh installs

While setting this up: migration 00048_gsc_suggestion_support.sql runs ALTER TABLE public.prompt_suggestions, but no migration creates that table — grep -rn "prompt_suggestions" supabase/migrations/ only ever finds ALTER/comments. supabase start fails on a clean database with:

ERROR: relation "public.prompt_suggestions" does not exist (SQLSTATE 42P01)

schema.sql inherits the same gap, being a concatenation of the migrations. Not touched here — happy to open a separate issue.

…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]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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]>
@mikam44700

Copy link
Copy Markdown
Contributor Author

Update: live-tested against OpenRouter now, which surfaced a real bug in the first commit. Fixed in 53b9da4.

The zod schema had confidence: z.number().min(0).max(1). That emits minimum/maximum in the JSON Schema, and Anthropic rejects both in strict structured-output mode:

output_config.format.schema: For 'number' type, properties maximum, minimum are not supported

OpenRouter returned it as a 400 from every backing provider it tried — Anthropic, Azure, Bedrock. So SENTIMENT_MODEL=openrouter/anthropic/claude-haiku-4.5 degraded to neutral on every call, silently, since the function is designed never to throw.

The range is now clamped in code, exactly as the original OpenAI implementation did with Math.max(0, Math.min(1, ...)). A test asserts the emitted JSON Schema carries no minimum/maximum, so this cannot regress.

Live results with claude-haiku-4.5 through OpenRouter:

Fixture Verdict Confidence
"LE cabinet de référence… noté 4,9/5" positive 0.95
"Plusieurs cabinets existent, dont X, Y et Z" neutral 0.95
"cher et les délais de réponse sont très longs" negative 0.92

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. createOpenAI({ baseURL }) plus a min/max schema looks perfectly correct and passes unit tests.

189 tests passing, lint and format clean.

@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.

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 replacing JSON.parse of free text is a straight improvement.
  • openai-tracker.js is the only place using the OpenAI SDK directly and getClient() is lazy, so your headline claim is right: after this, a Cloro-only or Anthropic-only install genuinely needs no OPENAI_API_KEY.
  • OpenRouter isn't registered without its key, so this is inert for every existing deployment.
  • server tests 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.

@gkhngyk
gkhngyk merged commit 800d474 into ansvisor:main Aug 12, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants