Skip to content

fix(categorizer): normalize LLM category output for consistent casing - #1097

Open
Saumya-b10 wants to merge 2 commits into
knoxiboy:mainfrom
Saumya-b10:fix/categorize-doubt-normalization
Open

fix(categorizer): normalize LLM category output for consistent casing#1097
Saumya-b10 wants to merge 2 commits into
knoxiboy:mainfrom
Saumya-b10:fix/categorize-doubt-normalization

Conversation

@Saumya-b10

@Saumya-b10 Saumya-b10 commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

User description

PR: Normalize LLM categorization output for consistent casing/punctuation

Problem

categorizeDoubt stores the raw string returned by the LLM directly as the doubt's category, relying entirely on the system prompt instruction ("Respond ONLY with the sub-topic name. No punctuation or explanation") for formatting consistency. LLMs don't reliably follow output-format instructions on every call — casing and trailing punctuation can vary between otherwise-identical requests, even at low temperature (0.1).

This means the same underlying topic can silently be stored as multiple distinct strings, e.g.:

"Recursion"
"recursion"
"Recursion."
" Recursion "

Since this category is used for grouping/analytics (e.g. teacher dashboards showing which sub-topics students struggle with most), these get treated as separate categories instead of one — fragmenting the data. There's no error or crash, so this goes unnoticed until someone inspects a report and the numbers look wrong.

Change

Added a normalizeCategory() helper that deterministically cleans the model's raw output before it's returned/stored:

typescript
function normalizeCategory(raw: string): string {
return raw
.trim()
.replace(/[.,;:!?"'`]+$/g, "") // strip trailing punctuation
.replace(/\s+/g, " ") // collapse internal whitespace
.split(" ")
.filter(Boolean)
.map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join(" ");
}

Applied in categorizeDoubt:

typescript
const raw = completion.choices[0]?.message?.content?.trim() || "";
return normalizeCategory(raw) || "General";

The existing "General" fallback behavior is preserved for empty/missing responses.
Closes #994


CodeAnt-AI Description

Normalize AI-generated doubt categories for consistent grouping

What Changed

  • Category labels now use consistent capitalization and spacing
  • Trailing punctuation is removed from AI-generated categories
  • Empty AI responses continue to fall back to General
  • Added coverage for lowercase, punctuation, whitespace, and empty responses

Impact

✅ Consistent category grouping
✅ Cleaner analytics labels
✅ Reliable fallback for empty responses

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • Bug Fixes
    • Improved AI category labeling by normalizing capitalization, spacing, and formatting.
    • Strips trailing punctuation/odd characters and removes surrounding quotes.
    • Preserves acronym casing (e.g., “SQL”, “API Design”) and handles empty/invalid model outputs by falling back to General.
  • Tests
    • Expanded test coverage for lowercase labels, irregular whitespace, multi-word categories, punctuation/ellipsis variants, quoted outputs, and empty responses.

@vercel

vercel Bot commented Jul 29, 2026

Copy link
Copy Markdown

@Saumya-b10 is attempting to deploy a commit to the Karan Mani Tripathi 's projects Team on Vercel.

A member of the Team first needs to authorize it.

@codeant-ai

codeant-ai Bot commented Jul 29, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR fbf4a2d Jul 29, 2026 · 16:06 16:08

@codeant-ai

codeant-ai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@github-actions github-actions Bot added gssoc'26 GSSoC program issue level:intermediate Intermediate level task type:bug Bug fix labels Jul 29, 2026
@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The categorizer now normalizes model-generated labels by trimming whitespace, removing punctuation, collapsing spacing, title-casing words, and preserving likely acronyms. Empty normalized results fall back to General, with tests covering these output cases.

Changes

Category normalization

Layer / File(s) Summary
Normalize categories and validate outputs
src/lib/ai/categorizer.ts, src/__tests__/lib/categorizer.test.ts
Adds normalizeCategory to standardize LLM labels, applies it in categorizeDoubt, and tests casing, punctuation removal, whitespace normalization, acronym preservation, quoting, and empty-response fallback.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: knoxiboy

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: normalizing LLM category output for consistent casing.
Linked Issues check ✅ Passed The PR implements normalization for casing, punctuation, whitespace, and empty responses as requested by issue #994.
Out of Scope Changes check ✅ Passed The added tests and acronym-preserving normalization are directly related to output normalization and not out of scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Fix failing CI checks
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codeant-ai codeant-ai Bot added the size:M This PR changes 30-99 lines, ignoring generated files label Jul 29, 2026
@github-actions
github-actions Bot requested a review from knoxiboy July 29, 2026 16:06
@github-actions

Copy link
Copy Markdown

@coderabbitai review
@codeantai review

@github-actions github-actions Bot added size/m and removed size:M This PR changes 30-99 lines, ignoring generated files labels Jul 29, 2026
Comment thread src/lib/ai/categorizer.ts Outdated
Comment thread src/lib/ai/categorizer.ts Outdated

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/lib/ai/categorizer.ts`:
- Line 11: Expand the trailing-punctuation normalization in the categorizer to
follow an explicit supported punctuation policy, including closing delimiters,
Unicode ellipsis, and punctuation separated by spaces such as “Recursion . .”.
Add representative tests covering these cases and confirm normalized values are
stored as the same category.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a224c918-52cc-43e4-895a-389beb33e2b2

📥 Commits

Reviewing files that changed from the base of the PR and between 1a16173 and fbf4a2d.

📒 Files selected for processing (2)
  • src/__tests__/lib/categorizer.test.ts
  • src/lib/ai/categorizer.ts

Comment thread src/lib/ai/categorizer.ts Outdated

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

🧹 Nitpick comments (1)
src/__tests__/lib/categorizer.test.ts (1)

89-92: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Cover missing model content as well as empty content.

The new fallback coverage only returns content: ''. Add a mock case with missing message.content (or an empty choices array) and assert that categorizeDoubt still returns General, matching the upstream fallback contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/__tests__/lib/categorizer.test.ts` around lines 89 - 92, Add a test case
in the categorizer tests covering an upstream response with missing
message.content or an empty choices array, and assert that categorizeDoubt
returns General. Keep the existing quoted-content test unchanged and reuse the
established mock setup for the fallback response.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/__tests__/lib/categorizer.test.ts`:
- Around line 89-92: Add a test case in the categorizer tests covering an
upstream response with missing message.content or an empty choices array, and
assert that categorizeDoubt returns General. Keep the existing quoted-content
test unchanged and reuse the established mock setup for the fallback response.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d91de6a-1cfb-499a-875a-0bfb2e3ddcb1

📥 Commits

Reviewing files that changed from the base of the PR and between fbf4a2d and d650457.

📒 Files selected for processing (2)
  • src/__tests__/lib/categorizer.test.ts
  • src/lib/ai/categorizer.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/ai/categorizer.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gssoc'26 GSSoC program issue level:intermediate Intermediate level task review-needed size/m type:bug Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Normalize categorization output for consistent DB values

1 participant