Add LLM token

This commit is contained in:
wangwei
2026-07-02 22:03:39 +08:00
parent e3afb8a07a
commit 52e67b0e7b
36 changed files with 2392 additions and 394 deletions
+20 -2
View File
@@ -9,6 +9,7 @@ from app.domain.conversation import AnswerGenerator, AnswerResult, ConversationS
from app.domain.retrieval import RetrievedChunk
from app.application.knowledge import KnowledgeRetrievalService
from app.application.agent.hyde_expander import HyDEExpander
# Keep orchestration logic centralized so use-case flow stays easy to trace.
@@ -26,6 +27,8 @@ class AgentConversationService:
self.retrieval_service = retrieval_service
self.answer_generator = answer_generator
self.conversation_store = conversation_store
# Shared HyDE expander — stateless, safe for reuse across requests.
self._hyde = HyDEExpander()
def ask(
self,
@@ -108,14 +111,26 @@ class AgentConversationService:
model: str | None = None,
top_k: int = 5,
prompt_template: str | None = None,
context_text: str | None = None,
context_filename: str | None = None,
) -> tuple[str, Generator[dict, None, None]]:
"""Stream chat for the Agent Conversation Service instance."""
"""Stream chat for the Agent Conversation Service instance.
When context_text is provided the user's document is passed directly to
the answer generator — RAG retrieval still runs on the user's question
(not the document text) to find relevant regulation passages.
"""
session = self.conversation_store.get_session(session_id) if session_id else None
if session is None:
session = self.conversation_store.create_session()
self.conversation_store.save_message(session.session_id, role="user", content=query)
history = [{"role": msg.role, "content": msg.content} for msg in session.messages[-10:]]
retrieved = self.retrieval_service.retrieve(query=query, top_k=top_k, filters=filters)
# HyDE: expand the query with a hypothetical answer to improve dense retrieval.
# For document-context queries, skip HyDE since the document itself guides retrieval.
retrieval_query = self._hyde.expand(query) if not context_text else query
# Retrieve using the enriched query — NOT the document text —
# so embedding quality is preserved for regulation chunk matching.
retrieved = self.retrieval_service.retrieve(query=retrieval_query, top_k=top_k, filters=filters)
def event_stream() -> Generator[dict, None, None]:
"""Handle event stream for the Agent Conversation Service instance."""
@@ -129,6 +144,8 @@ class AgentConversationService:
provider=provider,
model=model,
prompt_template=prompt_template,
context_text=context_text,
context_filename=context_filename,
):
if event.get("event") == "sources":
sources_payload = event.get("data", [])
@@ -189,3 +206,4 @@ class AgentSessionService:
raise ValueError("消息索引不存在")
# Preserve the existing API behavior until a persistent feedback store is introduced.
return AgentSessionFeedbackResult(session_id=session_id, message_index=message_index)