Skip to content

Ask AI Huge Response#1328

Merged
aadesh18 merged 9 commits intodevfrom
ask-ai-huge-responses-fix
Apr 13, 2026
Merged

Ask AI Huge Response#1328
aadesh18 merged 9 commits intodevfrom
ask-ai-huge-responses-fix

Conversation

@aadesh18
Copy link
Copy Markdown
Collaborator

@aadesh18 aadesh18 commented Apr 10, 2026

This PR fixes the bug where analytics tool returns a lot of rows, which results in huge token count. We do it by checking the number of characters in the tool call, and if it is more than 50000 characters, we send an error message rather than the rows and ask the ai to make more focused queries.

Summary by CodeRabbit

  • New Features

    • AI assistant shows friendlier, categorized error messages and captures unexpected errors for diagnosis.
    • UI now displays classifier-derived, user-friendly AI error text.
  • Bug Fixes & Improvements

    • Enforced a hard size budget for SQL query results and gracefully handles oversized responses.
    • Centralized safer database error messaging to avoid leaking internal details.
    • Strengthened AI guidance to prefer narrower queries, safer column selection, and pairing GROUP BY with ORDER BY + LIMIT.

Copilot AI review requested due to automatic review settings April 10, 2026 23:50
@vercel
Copy link
Copy Markdown

vercel Bot commented Apr 10, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
stack-auth-hosted-components Ready Ready Preview, Comment Apr 13, 2026 9:38pm
stack-backend Ready Ready Preview, Comment Apr 13, 2026 9:38pm
stack-dashboard Ready Ready Preview, Comment Apr 13, 2026 9:38pm
stack-demo Ready Ready Preview, Comment Apr 13, 2026 9:38pm
stack-docs Ready Ready Preview, Comment Apr 13, 2026 9:38pm
stack-preview-backend Ready Ready Preview, Comment Apr 13, 2026 9:38pm
stack-preview-dashboard Ready Ready Preview, Comment Apr 13, 2026 9:38pm

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 10, 2026

📝 Walkthrough

Walkthrough

Adds a 50,000-character result-size budget enforced in the SQL tool and prompts; centralizes ClickHouse error-safety logic into a helper; frontend maps AI/provider errors to friendlier messages and uses that helper in the Ask-AI UI.

Changes

Cohort / File(s) Summary
Backend prompts
apps/backend/src/lib/ai/prompts.ts
Expanded ClickHouse guidance: introduce hard tool-result size budget, instruct assistant to re-run narrower queries when { success: false } indicates "Result too large", stricter rules for selecting events/data, and require GROUP BY be paired with ORDER BY + LIMIT.
Backend SQL tool
apps/backend/src/lib/ai/tools/sql-query.ts
Added export const SQL_QUERY_RESULT_MAX_CHARS = 50_000; wrap execution in try/catch; serialize results and return { success: false, characters, rowCount, columnsReturned } when serialized size exceeds limit; use getSafeClickhouseErrorMessage for ClickHouse errors.
ClickHouse error helper
apps/backend/src/lib/clickhouse-errors.ts
New module exporting getSafeClickhouseErrorMessage(error, query) that validates error shape, classifies safe/unsafe codes, captures unexpected shapes/codes, and returns environment-aware safe messages.
Analytics route
apps/backend/src/app/api/.../analytics/query/route.ts
Remove local ClickHouse error whitelisting/blacklisting; import and use getSafeClickhouseErrorMessage(...) to derive user-facing messages while preserving existing error-control flow.
Frontend AI error utilities
apps/dashboard/src/components/commands/ai-chat-shared.tsx
Added getFriendlyAiErrorMessage(error) that extracts nested causes, classifies common AI/provider errors (context/token limits, rate limits/429/quota, timeouts/network, result-too-large), calls captureError for uncategorized cases, and returns friendly strings.
Ask-AI UI
apps/dashboard/src/components/commands/ask-ai.tsx
Use getFriendlyAiErrorMessage(aiError) for UI error text rendering instead of displaying raw aiError.message.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant AI_Assistant
    participant Backend
    participant ClickHouse
    participant ErrorLogger

    User->>Frontend: Submit question (may request analytics)
    Frontend->>AI_Assistant: Send prompt (includes SQL guidance & size budget)
    AI_Assistant->>Frontend: Emits tool call -> queryAnalytics(SQL)
    Frontend->>Backend: Invoke queryAnalytics with SQL
    Backend->>ClickHouse: Execute SQL
    ClickHouse-->>Backend: Return rows or error
    Backend->>Backend: Serialize rows -> check SQL_QUERY_RESULT_MAX_CHARS
    alt ≤ 50K chars
        Backend-->>Frontend: { success: true, rowCount, result }
        Frontend->>User: Display results
    else > 50K chars
        Backend-->>Frontend: { success: false, error: "Result too large", rowCount, characters, columnsReturned }
        Frontend->>AI_Assistant: Assistant detects `{ success: false }` -> issue narrower query (per prompt)
        Frontend->>ErrorLogger: captureError(if uncategorized)
        AI_Assistant->>Frontend: New, narrower tool call
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • N2D4

Poem

🐰 I hopped through queries, quick and spry,
Counting chars before they fly.
Fifty thousand keeps the heap light,
Narrow the rows, then run it right.
I log the strange and try, retry.

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is partially related to the changeset as it refers to handling huge responses from the Ask AI tool, which matches the core issue being fixed. However, it's vague and doesn't clearly convey that the fix involves implementing a character limit (50k) for analytics query results. Consider a more specific title like 'Implement character limit for analytics query results' or 'Add 50k character limit to prevent huge AI tool responses'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description check ✅ Passed The pull request description clearly explains the bug being fixed and the solution approach. It mentions the 50,000 character limit and the mechanism for handling oversized responses, aligning well with the actual changes made across multiple files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ask-ai-huge-responses-fix

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 and usage tips.

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented Apr 10, 2026

Greptile Summary

This PR adds a 50,000-character result-size guard to the queryAnalytics SQL tool and enriches the system prompt with query guidance to steer the AI toward aggregations over raw row fetches. The frontend improvements add Sentry error capture and a user-friendly error classifier for AI provider failures.

Confidence Score: 5/5

Safe to merge — all findings are P2 style suggestions that do not block correctness.

The size guard, prompt additions, and frontend error handling are all correct. The only finding is a P2 efficiency note about serialising large result sets before discarding them, which does not affect correctness or user-facing behaviour.

No files require special attention.

Important Files Changed

Filename Overview
apps/backend/src/lib/ai/tools/sql-query.ts Adds a 50,000-character post-fetch guard; data is fully transferred from ClickHouse before the check, resulting in avoidable bandwidth/memory overhead for oversized results.
apps/backend/src/lib/ai/prompts.ts Adds comprehensive TOOL RESULT BUDGET guidance and aggregation examples to the system prompt; tool name matches the registered "queryAnalytics" key.
apps/dashboard/src/components/commands/ask-ai.tsx Adds Sentry capture for raw AI errors and a friendly error classifier; clean and correct implementation.

Sequence Diagram

sequenceDiagram
    participant AI as AI Model
    participant Tool as queryAnalytics Tool
    participant CH as ClickHouse

    AI->>Tool: execute(query)
    Tool->>CH: query (max 10MB, 10k rows)
    CH-->>Tool: resultSet (JSONEachRow)
    Tool->>Tool: rows = await resultSet.json()
    Tool->>Tool: serialized = JSON.stringify(rows)
    alt serialized.length > 50,000 chars
        Tool-->>AI: { success: false, error, rowCount, characters, columnsReturned }
        AI->>AI: Re-query with aggregation / narrower WHERE / smaller LIMIT
        AI->>Tool: execute(refined_query)
    else within budget
        Tool-->>AI: { success: true, rowCount, result: rows }
    end
Loading
Prompt To Fix All With AI
This is a comment left during a code review.
Path: apps/backend/src/lib/ai/tools/sql-query.ts
Line: 40-41

Comment:
**Full result transferred before size check**

`JSON.stringify(rows)` materialises the entire result set in memory (up to the existing 10 MB ClickHouse cap) before the guard kicks in. Any result between ~50 KB and 10 MB is fully fetched and then discarded. Lowering `max_result_bytes` to something closer to the 50,000-character target (e.g. ~200 KB to give headroom for non-ASCII) would cut wasted bandwidth without changing the existing fallback logic.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "initial commit" | Re-trigger Greptile

Comment thread apps/backend/src/lib/ai/tools/sql-query.ts Outdated
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR reduces runaway token usage in the dashboard “Ask AI” analytics flow by enforcing a hard cap on the size of SQL tool results and by improving how AI/provider errors are reported to end users.

Changes:

  • Add a 50,000-character hard limit for queryAnalytics tool responses and return a structured success:false error when exceeded.
  • Update the AI system prompt with strict “tool result budget” guidance and re-query instructions.
  • Improve dashboard error UX by mapping raw AI errors to friendly messages and capturing raw errors via captureError.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
apps/dashboard/src/components/commands/ask-ai.tsx Adds friendly AI error messaging and captures raw errors for observability.
apps/backend/src/lib/ai/tools/sql-query.ts Enforces a maximum serialized result size and returns a guided error object instead of large row payloads.
apps/backend/src/lib/ai/prompts.ts Instructs the AI to prefer aggregation and to re-query when the tool returns a “result too large” response.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread apps/backend/src/lib/ai/tools/sql-query.ts Outdated
Comment thread apps/dashboard/src/components/commands/ask-ai.tsx Outdated
Comment thread apps/backend/src/lib/ai/prompts.ts
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/backend/src/lib/ai/prompts.ts`:
- Line 120: Update the quantile example in apps/backend/src/lib/ai/prompts.ts to
use a schema-valid numeric value instead of the nonexistent "amount" column:
either replace "amount" with a real numeric column from the table (e.g.,
"duration_ms" or "price") or explicitly extract a numeric value from JSON (e.g.,
use JSONExtractFloat(properties, 'amount') or
toFloat64(JSONExtractRaw(properties, 'amount')) ) so the example query (the
Quantiles line) produces valid ClickHouse SQL; modify the example string where
"Quantiles: SELECT quantile(0.5)(amount), quantile(0.95)(amount) FROM events"
appears accordingly.

In `@apps/dashboard/src/components/commands/ask-ai.tsx`:
- Around line 485-497: Update getFriendlyAiErrorMessage to explicitly detect
backend "Result too large" errors by checking the combined blob (error.message +
cause message) for patterns like /result too large|limit \d+/i and return a
clear user-facing message such as asking the user to narrow the query or request
fewer rows; modify the function (getFriendlyAiErrorMessage and its blob
variable) to add this new conditional branch before the generic fallback so
those backend errors no longer fall through to "Something went wrong."
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 683f7767-1fd4-4794-879e-1f4188654fb4

📥 Commits

Reviewing files that changed from the base of the PR and between 0a48aa5 and 39a9a7d.

📒 Files selected for processing (3)
  • apps/backend/src/lib/ai/prompts.ts
  • apps/backend/src/lib/ai/tools/sql-query.ts
  • apps/dashboard/src/components/commands/ask-ai.tsx

Comment thread apps/backend/src/lib/ai/prompts.ts Outdated
Comment thread apps/dashboard/src/components/commands/ask-ai.tsx Outdated
@aadesh18 aadesh18 changed the title initial commit Ask AI Huge Response Apr 11, 2026
Comment thread apps/backend/src/lib/ai/prompts.ts Outdated
Comment thread apps/backend/src/lib/ai/tools/sql-query.ts Outdated
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
apps/backend/src/lib/clickhouse-errors.ts (1)

39-40: Cache getNodeEnvironment() once per call.

Line 39 calls getNodeEnvironment() twice in the same branch; storing once improves clarity and avoids repeated lookup.

Suggested refactor
-  if (getNodeEnvironment() === "development" || getNodeEnvironment() === "test") {
+  const nodeEnv = getNodeEnvironment();
+  if (nodeEnv === "development" || nodeEnv === "test") {
     return `${DEFAULT_CLICKHOUSE_ERROR_MESSAGE}${!isKnown ? "\n\nThis error is not known and you should probably add it to the safe or unsafe codes in clickhouse-errors.ts." : ""}\n\nAs you are in development mode, you can see the full error: ${errorCode} ${message}`;
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/backend/src/lib/clickhouse-errors.ts` around lines 39 - 40, The code
calls getNodeEnvironment() twice when building the development/test error
string; refactor by calling getNodeEnvironment() once into a local const (e.g.,
const env = getNodeEnvironment()) at the start of the function in
clickhouse-errors.ts and use that variable in the if condition and the returned
template instead of repeated calls, ensuring getNodeEnvironment() is only
invoked once per call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/backend/src/lib/clickhouse-errors.ts`:
- Around line 39-40: The code calls getNodeEnvironment() twice when building the
development/test error string; refactor by calling getNodeEnvironment() once
into a local const (e.g., const env = getNodeEnvironment()) at the start of the
function in clickhouse-errors.ts and use that variable in the if condition and
the returned template instead of repeated calls, ensuring getNodeEnvironment()
is only invoked once per call.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 552d2c5d-5a3f-471d-9e14-acb9939e94d8

📥 Commits

Reviewing files that changed from the base of the PR and between 70f3daa and 4d030b4.

📒 Files selected for processing (3)
  • apps/backend/src/app/api/latest/internal/analytics/query/route.ts
  • apps/backend/src/lib/ai/tools/sql-query.ts
  • apps/backend/src/lib/clickhouse-errors.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/backend/src/lib/ai/tools/sql-query.ts

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

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 the current code and only fix it if needed.

Inline comments:
In `@apps/dashboard/src/components/commands/ai-chat-shared.tsx`:
- Around line 541-542: The cast on causeMessage bypasses the type system; change
the extraction to runtime-safe narrowing: ensure the thrown value is an Error
(e.g., check error instanceof Error) then inspect error.cause with defensive
checks (if cause instanceof Error -> use cause.message, else if typeof cause ===
"string" -> use cause, else if cause and typeof cause === "object" and "message"
in cause and typeof (cause as any).message === "string" -> use that), and
fallback to an empty string; then build blob from error.message plus that
computed causeMessage (update the code that defines causeMessage and blob
accordingly).
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: ca0b94d1-416b-4d7c-a14a-db308c1e1b40

📥 Commits

Reviewing files that changed from the base of the PR and between 4d030b4 and 40e15fc.

📒 Files selected for processing (2)
  • apps/dashboard/src/components/commands/ai-chat-shared.tsx
  • apps/dashboard/src/components/commands/ask-ai.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/dashboard/src/components/commands/ask-ai.tsx

Comment thread apps/dashboard/src/components/commands/ai-chat-shared.tsx
@aadesh18 aadesh18 enabled auto-merge (squash) April 13, 2026 22:11
@aadesh18 aadesh18 merged commit 5573927 into dev Apr 13, 2026
32 checks passed
@aadesh18 aadesh18 deleted the ask-ai-huge-responses-fix branch April 13, 2026 22:12
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.

3 participants