mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 04:29:27 +08:00
fix(rag): strip only list markers from generated queries
_generate_queries cleaned each LLM-returned line with
line.strip().lstrip("0123456789.-) "). str.lstrip takes a character SET, not a
prefix, so besides the intended "1. "/"2) " list markers it also ate any
leading digits of the query itself: "2024 budget forecast" -> "budget
forecast", "5G network rollout" -> "G network rollout". The KB was then
searched for a materially different query whenever a variant began with a
number (years, 5G, 3D, versions). Strip a real leading list marker with a
regex instead.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -4,10 +4,14 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Awaitable, Callable
|
||||
import re
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
SearchFunc = Callable[..., Awaitable[Dict[str, Any]]]
|
||||
|
||||
# A leading ordered ("1. ", "2) ") or unordered ("- ", "* ") list marker.
|
||||
_LIST_MARKER_RE = re.compile(r"^\s*(?:\d+[.)]|[-*+])\s+")
|
||||
|
||||
|
||||
class SmartRetriever:
|
||||
"""Generate query variants, retrieve passages, and aggregate them."""
|
||||
@@ -57,7 +61,7 @@ class SmartRetriever:
|
||||
)
|
||||
raw = await complete(prompt, system_prompt="You are a search query generator.")
|
||||
lines = [
|
||||
line.strip().lstrip("0123456789.-) ")
|
||||
_LIST_MARKER_RE.sub("", line.strip())
|
||||
for line in raw.strip().split("\n")
|
||||
if line.strip()
|
||||
]
|
||||
|
||||
@@ -348,3 +348,28 @@ async def test_delete_removes_kb_directory_when_pipeline_lacks_delete(tmp_path)
|
||||
|
||||
assert await service.delete(kb_name="demo") is True
|
||||
assert not kb_dir.exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_queries_strips_list_markers_not_leading_numbers(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
# The LLM returns a numbered list; only the list marker should be removed.
|
||||
# A query that itself begins with a number ("2024 ...", "5G ...") must keep
|
||||
# it — lstrip("0123456789.-) ") ate those because it is a char set, not a
|
||||
# prefix.
|
||||
import deeptutor.services.llm as llm_module
|
||||
|
||||
async def _fake_complete(_prompt: str, *, system_prompt: str | None = None) -> str:
|
||||
return "1. 2024 budget forecast\n2. 5G network rollout\n- climate policy"
|
||||
|
||||
monkeypatch.setattr(llm_module, "complete", _fake_complete, raising=True)
|
||||
|
||||
async def _unused_search(**_kwargs: object) -> dict:
|
||||
return {}
|
||||
|
||||
retriever = SmartRetriever(search=_unused_search)
|
||||
|
||||
queries = await retriever._generate_queries("some context", 3)
|
||||
|
||||
assert queries == ["2024 budget forecast", "5G network rollout", "climate policy"]
|
||||
|
||||
Reference in New Issue
Block a user