Skip to content

feat: add QueryRewrite prompt builder and response parser - #15669

Merged
yingfeng merged 1 commit into
infiniflow:mainfrom
xugangqiang:feat/go-kg-query-rewrite
Jun 5, 2026
Merged

yingfeng merged 1 commit into
infiniflow:mainfrom
xugangqiang:feat/go-kg-query-rewrite

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

QueryRewrite prompt builder and response parser. Zero external dependencies.

Functions

  • BuildQueryRewritePrompt: Renders minirag_query2kwd prompt with query and type pool
  • ParseQueryRewriteResponse: Parses LLM JSON response with fallback for markdown and extra text

Testing

=== RUN   TestBuildQueryRewritePrompt             --- PASS
=== RUN   TestParseQueryRewriteResponse_ValidJSON --- PASS
=== RUN   TestParseQueryRewriteResponse_MarkdownBlock --- PASS
=== RUN   TestParseQueryRewriteResponse_ExtraText --- PASS
=== RUN   TestParseQueryRewriteResponse_Invalid   --- PASS
=== RUN   TestParseQueryRewriteResponse_EmptyEntities --- PASS

- 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]>
@xugangqiang xugangqiang added the ci Continue Integration label Jun 4, 2026
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Query rewrite module

Layer / File(s) Summary
Data contract and prompt template
internal/common/kg_query_rewrite.go, internal/common/kg_query_rewrite_test.go
QueryRewriteResult struct with JSON tags for answer_type_keywords and entities_from_query. Large constant prompt template instructs the LLM to output the expected JSON schema with specified field names.
Prompt generation
internal/common/kg_query_rewrite.go, internal/common/kg_query_rewrite_test.go
BuildQueryRewritePrompt substitutes {query} and {TYPE_POOL} placeholders into the template using string replacement. Tests verify placeholders are replaced and content is present.
Response parsing with fallback strategies
internal/common/kg_query_rewrite.go, internal/common/kg_query_rewrite_test.go
ParseQueryRewriteResponse attempts direct JSON unmarshalling, then extraction from fenced markdown code blocks, then substring extraction of the first JSON object; uses tryParseJSON helper for unmarshalling. Tests cover valid JSON, markdown blocks, extra surrounding text, invalid input error handling, and empty entity arrays.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 A query rewritten by the LLM's mind,
Keywords and entities, so well defined,
Three parsing paths in case the response bends,
Robust and ready, the prompt module lends.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is missing the required 'What problem does this PR solve?' and 'Type of change' sections from the template, though it does provide functional details and test results. Add the required 'What problem does this PR solve?' and 'Type of change' sections from the description template to fully comply with repository standards.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: adding a QueryRewrite prompt builder and response parser, which matches the new functions and files added to the codebase.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

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

@xugangqiang
xugangqiang marked this pull request as ready for review June 4, 2026 13:56
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 4, 2026

@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 (2)
internal/common/kg_query_rewrite.go (2)

127-163: ⚡ Quick win

Consider 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 outer err, so the final return nil, err always 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 win

Correct the key count in the instruction.

The instruction states "The JSON should have three keys:" but then only lists two keys (answer_type_keywords and entities_from_query), which matches the actual QueryRewriteResult struct 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

📥 Commits

Reviewing files that changed from the base of the PR and between 98f2a2e and af0d3ee.

📒 Files selected for processing (2)
  • internal/common/kg_query_rewrite.go
  • internal/common/kg_query_rewrite_test.go

@codecov

codecov Bot commented Jun 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (98f2a2e) to head (af0d3ee).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yingfeng
yingfeng merged commit a237a89 into infiniflow:main Jun 5, 2026
1 check passed
yingfeng pushed a commit that referenced this pull request Jun 5, 2026
…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]>
@xugangqiang
xugangqiang deleted the feat/go-kg-query-rewrite branch August 7, 2026 12:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants