Repository navigation
feat: add QueryRewrite prompt builder and response parser - #15669
Conversation
- BuildQueryRewritePrompt: renders minirag_query2kwd prompt template - ParseQueryRewriteResponse: parses LLM response with JSON/fallback handling - Supports JSON, markdown code blocks, and extra text wrapping Co-Authored-By: Claude Opus 4.8 <[email protected]>
📝 WalkthroughWalkthroughThis PR introduces query rewriting support for knowledge graph integration. It adds a new module with a data contract for LLM output, a configurable prompt template, a function to build prompts by substituting placeholders, and robust response parsing that handles direct JSON, markdown-fenced blocks, and substring fallbacks. Comprehensive tests verify all code paths. ChangesQuery rewrite module
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
internal/common/kg_query_rewrite.go (2)
127-163: ⚡ Quick winConsider preserving the most recent parsing error.
The current implementation returns the error from the first parsing attempt (line 131) even when all three fallback strategies fail. The inner
result, err := tryParseJSON(...)declarations at lines 144 and 156 shadow the outererr, so the finalreturn nil, erralways returns the error from parsing the raw response.While this is intentional (per the comment on line 162), it can make debugging harder when a fallback strategy successfully extracts content but that content is still malformed JSON—the error message will reference the raw input rather than the extracted substring.
♻️ Proposed refactor to preserve the latest error
func ParseQueryRewriteResponse(response string) (*QueryRewriteResult, error) { // Try direct JSON parsing first result, err := tryParseJSON(response) if err == nil { return result, nil } + lastErr := err // Fallback: try to extract JSON from markdown code blocks cleaned := strings.TrimSpace(response) if idx := strings.Index(cleaned, "```"); idx >= 0 { rest := cleaned[idx+3:] if end := strings.Index(rest, "```"); end >= 0 { code := strings.TrimSpace(rest[:end]) code = strings.TrimPrefix(code, "json") code = strings.TrimSpace(code) - result, err := tryParseJSON(code) + result, err = tryParseJSON(code) if err == nil { return result, nil } + lastErr = err } } // Fallback: extract first JSON object start := strings.Index(cleaned, "{") end := strings.LastIndex(cleaned, "}") if start >= 0 && end > start { candidate := cleaned[start : end+1] - result, err := tryParseJSON(candidate) + result, err = tryParseJSON(candidate) if err == nil { return result, nil } + lastErr = err } - return nil, err // return the original error + return nil, lastErr }🤖 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 `@internal/common/kg_query_rewrite.go` around lines 127 - 163, ParseQueryRewriteResponse currently shadows the outer err in the fallback tryParseJSON calls so the final return always returns the first parse error; change the fallback calls in the markdown-block and JSON-object branches to assign to the existing err (not :=), introduce a lastErr variable initialized to the original err, set lastErr = err after each failed tryParseJSON, and return lastErr at the end so the most recent parsing error (from the extracted substring) is preserved; references: ParseQueryRewriteResponse, tryParseJSON, err, lastErr.
46-46: ⚡ Quick winCorrect the key count in the instruction.
The instruction states "The JSON should have three keys:" but then only lists two keys (
answer_type_keywordsandentities_from_query), which matches the actualQueryRewriteResultstruct definition. While the examples correctly demonstrate two keys, the inconsistency could potentially confuse the LLM.📝 Proposed fix
-- The JSON should have three keys: +- The JSON should have two keys:🤖 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 `@internal/common/kg_query_rewrite.go` at line 46, Update the mistaken instruction text that says "The JSON should have three keys:" to accurately state two keys to match the QueryRewriteResult struct; specifically mention that the JSON contains "answer_type_keywords" and "entities_from_query" to align the comment with the struct and examples in kg_query_rewrite.go (referencing QueryRewriteResult, answer_type_keywords, entities_from_query).
🤖 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 `@internal/common/kg_query_rewrite.go`:
- Around line 127-163: ParseQueryRewriteResponse currently shadows the outer err
in the fallback tryParseJSON calls so the final return always returns the first
parse error; change the fallback calls in the markdown-block and JSON-object
branches to assign to the existing err (not :=), introduce a lastErr variable
initialized to the original err, set lastErr = err after each failed
tryParseJSON, and return lastErr at the end so the most recent parsing error
(from the extracted substring) is preserved; references:
ParseQueryRewriteResponse, tryParseJSON, err, lastErr.
- Line 46: Update the mistaken instruction text that says "The JSON should have
three keys:" to accurately state two keys to match the QueryRewriteResult
struct; specifically mention that the JSON contains "answer_type_keywords" and
"entities_from_query" to align the comment with the struct and examples in
kg_query_rewrite.go (referencing QueryRewriteResult, answer_type_keywords,
entities_from_query).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: cf509159-51e2-4772-a87c-3134ea3149a1
📒 Files selected for processing (2)
internal/common/kg_query_rewrite.gointernal/common/kg_query_rewrite_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15669 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…ry_rewrite, community) (#15690) ## Summary `KGSearchRetrieval` composes entity search, type search, relation search, N-hop analysis, score fusion, LLM-based query\_rewrite, and community reports into a single synthetic chunk for KG-enhanced retrieval. ### Components | Component | Source | Status | |-----------|--------|--------| | Entity/relation/community search | Direct `DocEngine.Search` calls | ✅ | | N-hop analysis + score fusion | `common.AnalyzeNHopPaths` / `DoubleHitBoost` / `FuseRelationScores` | ✅ #15666 | | Query rewrite prompt + parser | `common.BuildQueryRewritePrompt` / `ParseQueryRewriteResponse` | ✅ #15669 | | Token budget | `common.BuildKGContent` + `NumTokensFromString` | ✅ #15666 | | LLM query rewrite integration | `queryRewrite` function with fallback | ✅ | ### Testing 11 tests (pure function + mock engine): ``` === RUN TestKgEntityFromChunk_Basic --- PASS === RUN TestKgEntityFromChunk_ScoreFallback --- PASS === RUN TestKgEntityFromChunk_MissingFields --- PASS === RUN TestKgRelationFromChunk_Basic --- PASS === RUN TestKgRelationFromChunk_MissingFrom --- PASS === RUN TestSearchKGTypeSamples_Success --- PASS === RUN TestSearchKGTypeSamples_Empty --- PASS === RUN TestKGSearchRetrieval_Basic --- PASS === RUN TestKGSearchRetrieval_NoEntities --- PASS === RUN TestQueryRewrite_Fallback --- PASS === RUN TestQueryRewrite_EmptyQuestion --- PASS ``` --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
QueryRewrite prompt builder and response parser. Zero external dependencies.
Functions
BuildQueryRewritePrompt: Rendersminirag_query2kwdprompt with query and type poolParseQueryRewriteResponse: Parses LLM JSON response with fallback for markdown and extra textTesting