DeepMedAI / backend /app /agents /llm_agent.py
PBThuong's picture
Thiết lập lại thư viện y khoa sạch và cập nhật chroma_db
8eaa451
Raw
History Blame Contribute Delete
2.36 kB
"""
DeepMed-AI — agents/llm_agent.py
LLMAgent: trả lời trực tiếp từ Gemini 3 Flash (không qua RAG).
Dùng khi câu hỏi không liên quan y tế hoặc RAG không tìm được tài liệu.
"""
from app.core.logging_config import logger
from app.core.state import AgentState
from app.tools.llm_client import DEEPMED_SYSTEM_PROMPT, get_llm, get_llm_name
def LLMAgent(state: AgentState) -> AgentState:
"""Generate a response directly from Gemini 3 Flash (no retrieval)."""
llm = get_llm()
if not llm:
state["llm_success"] = False
state["llm_attempted"] = True
state["generation"] = "⚠️ Hệ thống AI tạm thời không khả dụng. Vui lòng thử lại sau."
return state
# Lịch sử hội thoại 5 lượt gần nhất
history_lines = []
for item in state.get("conversation_history", [])[-5:]:
role = "Người dùng" if item.get("role") == "user" else "DeepMed-AI"
history_lines.append(f"{role}: {item.get('content', '')}")
history_context = "\n".join(history_lines) if history_lines else "Không có lịch sử."
prompt = f"""{DEEPMED_SYSTEM_PROMPT}
---
## Lịch sử hội thoại:
{history_context}
## Câu hỏi hiện tại:
{state['question']}
---
**Lưu ý**: Không tìm được tài liệu phù hợp trong cơ sở dữ liệu nội bộ. Hãy trả lời dựa trên kiến thức y khoa \
tổng quát, rõ ràng bằng tiếng Việt. Nếu cần thông tin cụ thể hơn, gợi ý người dùng cung cấp \
thêm chi tiết."""
try:
response = llm.invoke(prompt)
answer = (
response.content.strip()
if hasattr(response, "content")
else str(response).strip()
)
if answer and len(answer) > 10:
state["generation"] = answer
state["llm_success"] = True
state["source"] = f"Kiến thức y khoa tổng quát ({get_llm_name()})"
logger.info("LLMAgent: Generated response successfully (%d chars)", len(answer))
else:
state["llm_success"] = False
logger.warning("LLMAgent: Response too short or empty")
except Exception as e:
logger.error("LLMAgent: Failed: %s", str(e))
state["llm_success"] = False
state["llm_attempted"] = True
return state