feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1,440 @@
|
||||
"""
|
||||
文档问答服务
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
基于指定目录下的文档提供多轮对话式问答。
|
||||
支持两种模式:
|
||||
1. 文本模式(默认):解析文档到内存,直接用原文回答(无需向量化,快);
|
||||
2. 向量模式(可选):手动触发向量化,用向量检索回答(大文档/高频问答时用)。
|
||||
|
||||
【技术选型理由】
|
||||
1. 文本模式优先:小文档量直接塞 LLM 上下文即可,省向量化时间;
|
||||
2. 向量化可选:用户按需触发,不强制;
|
||||
3. 复用已有 document_loader / vector_store 组件。
|
||||
|
||||
【实现思路】
|
||||
- load_directory():只解析文档存内存(快);
|
||||
- chat():文本模式直接用原文;有向量索引时用检索增强;
|
||||
- vectorize():手动触发向量化(按钮)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("agent.doc_qa")
|
||||
|
||||
# 会话存储
|
||||
_conversations: dict[str, dict[str, Any]] = {}
|
||||
|
||||
# 持久化文件(对话历史跨重启保留)
|
||||
_PERSIST_FILE = Path(r"D:\Agent\agent\data\docqa_conversations.json")
|
||||
|
||||
|
||||
def _load_persisted() -> None:
|
||||
"""启动时从文件恢复对话历史。"""
|
||||
if not _PERSIST_FILE.exists():
|
||||
return
|
||||
try:
|
||||
data = json.loads(_PERSIST_FILE.read_text(encoding="utf-8"))
|
||||
for cid, conv in data.items():
|
||||
# 只恢复元数据和历史,documents 可能太大
|
||||
_conversations[cid] = {
|
||||
"directory": conv.get("directory", ""),
|
||||
"documents": conv.get("documents", []),
|
||||
"vectorized": conv.get("vectorized", False),
|
||||
"collection_name": conv.get("collection_name"),
|
||||
"history": conv.get("history", []),
|
||||
"total_chars": conv.get("total_chars", 0),
|
||||
"total_chunks": conv.get("total_chunks", 0),
|
||||
"title": conv.get("title", "未命名对话"),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
}
|
||||
logger.info("已恢复 %d 个对话历史", len(_conversations))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("恢复对话历史失败:%s", exc)
|
||||
|
||||
|
||||
def _save_persisted() -> None:
|
||||
"""持久化对话历史到文件。"""
|
||||
try:
|
||||
_PERSIST_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
# 只存必要字段,documents 可能很大
|
||||
data = {}
|
||||
for cid, conv in _conversations.items():
|
||||
data[cid] = {
|
||||
"directory": conv.get("directory", ""),
|
||||
"documents": conv.get("documents", [])[:50], # 最多存 50 个文档元数据
|
||||
"vectorized": conv.get("vectorized", False),
|
||||
"collection_name": conv.get("collection_name"),
|
||||
"history": conv.get("history", [])[-20:], # 最多存最近 20 轮
|
||||
"total_chars": conv.get("total_chars", 0),
|
||||
"total_chunks": conv.get("total_chunks", 0),
|
||||
"title": conv.get("title", "未命名对话"),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
}
|
||||
_PERSIST_FILE.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("保存对话历史失败:%s", exc)
|
||||
|
||||
|
||||
# 启动时恢复
|
||||
_load_persisted()
|
||||
|
||||
|
||||
def load_directory(
|
||||
directory: Path | None = None,
|
||||
conversation_id: str | None = None,
|
||||
file_paths: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
解析文档并存入内存(**不做向量化**,快)。
|
||||
|
||||
【参数】
|
||||
directory:目录路径(加载目录下全部文档)
|
||||
file_paths:文件路径列表(加载指定文件,与 directory 二选一)
|
||||
【返回】{conversation_id, total_chars, file_count, vectorized: False}
|
||||
"""
|
||||
from app.knowledge.document_loader import load_directory as _load, load_file
|
||||
|
||||
if conversation_id is None:
|
||||
conversation_id = f"conv_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
docs = []
|
||||
warnings = []
|
||||
target_label = ""
|
||||
|
||||
try:
|
||||
if file_paths:
|
||||
# 加载指定文件
|
||||
target_label = f"{len(file_paths)} 个文件"
|
||||
for fp in file_paths:
|
||||
try:
|
||||
docs.extend(load_file(Path(fp)))
|
||||
except Exception as exc: # noqa: BLE001
|
||||
warnings.append(f"解析失败:{Path(fp).name},{exc}")
|
||||
elif directory:
|
||||
# 加载目录下全部文档
|
||||
directory = Path(directory)
|
||||
if not directory.exists():
|
||||
return {"success": False, "message": f"目录不存在:{directory}"}
|
||||
target_label = str(directory)
|
||||
docs, warnings = _load(directory)
|
||||
else:
|
||||
return {"success": False, "message": "directory 或 file_paths 必须提供其一"}
|
||||
|
||||
if not docs:
|
||||
return {
|
||||
"success": False,
|
||||
"message": f"无可用文档(跳过 {len(warnings)} 个文件)",
|
||||
"conversation_id": conversation_id,
|
||||
}
|
||||
|
||||
# 存入内存(不做向量化)
|
||||
documents = [
|
||||
{
|
||||
"filename": d.metadata.get("filename", "未知"),
|
||||
"text": d.page_content,
|
||||
"chars": len(d.page_content),
|
||||
}
|
||||
for d in docs
|
||||
]
|
||||
total_chars = sum(d["chars"] for d in documents)
|
||||
|
||||
_conversations[conversation_id] = {
|
||||
"directory": target_label,
|
||||
"documents": documents,
|
||||
"vectorized": False,
|
||||
"collection_name": None,
|
||||
"history": [],
|
||||
"total_chars": total_chars,
|
||||
"title": Path(target_label).name if target_label else "新对话",
|
||||
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
}
|
||||
_save_persisted()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"conversation_id": conversation_id,
|
||||
"directory": target_label,
|
||||
"file_count": len(documents),
|
||||
"total_chars": total_chars,
|
||||
"vectorized": False,
|
||||
"files": documents,
|
||||
"warnings": warnings,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("文档解析失败")
|
||||
return {"success": False, "message": f"解析失败:{exc}", "conversation_id": conversation_id}
|
||||
|
||||
|
||||
def vectorize(conversation_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
手动触发向量化(按钮)。
|
||||
|
||||
【返回】{success, total_chunks, collection_name}
|
||||
"""
|
||||
from app.knowledge.embeddings import get_embedding_provider
|
||||
from app.knowledge.text_splitter import split_documents
|
||||
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||
from app.knowledge.document_loader import LoadedDocument
|
||||
|
||||
conv = _conversations.get(conversation_id)
|
||||
if conv is None:
|
||||
return {"success": False, "message": "会话不存在,请先加载目录"}
|
||||
|
||||
if conv.get("vectorized"):
|
||||
return {"success": True, "message": "已向量化,无需重复操作", "total_chunks": conv.get("total_chunks", 0)}
|
||||
|
||||
try:
|
||||
from app.config.settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
provider = get_embedding_provider(
|
||||
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||
)
|
||||
collection_name = f"docqa_{conversation_id}"
|
||||
vs = KnowledgeVectorStore(
|
||||
persist_dir=settings.chroma_dir,
|
||||
collection_name=collection_name,
|
||||
embedding_provider=provider,
|
||||
)
|
||||
|
||||
# 内存文档 → LoadedDocument → 切分 → 入库
|
||||
docs = [
|
||||
LoadedDocument(page_content=d["text"], metadata={"filename": d["filename"], "source": ""})
|
||||
for d in conv["documents"]
|
||||
]
|
||||
chunks = split_documents(docs)
|
||||
|
||||
import uuid as uuid_mod
|
||||
|
||||
ids = [f"chunk_{uuid_mod.uuid4().hex[:12]}" for _ in chunks]
|
||||
vs.add_documents(
|
||||
[c.page_content for c in chunks],
|
||||
[c.metadata for c in chunks],
|
||||
ids,
|
||||
)
|
||||
|
||||
conv["vectorized"] = True
|
||||
conv["collection_name"] = collection_name
|
||||
conv["total_chunks"] = len(chunks)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"向量化完成:{len(chunks)} 个文本块",
|
||||
"total_chunks": len(chunks),
|
||||
"collection_name": collection_name,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("向量化失败")
|
||||
return {"success": False, "message": f"向量化失败:{exc}"}
|
||||
|
||||
|
||||
def chat(
|
||||
conversation_id: str,
|
||||
question: str,
|
||||
model_preference: str = "auto",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
多轮对话问答。
|
||||
|
||||
【模式】
|
||||
无文档:纯 LLM 对话(无 RAG,直接回答);
|
||||
有文档未向量化:文档原文直接进 LLM 上下文;
|
||||
有文档已向量化:向量检索 top-k 相关片段 + LLM 回答。
|
||||
"""
|
||||
from app.models.model_router import get_model_for_task
|
||||
|
||||
conv = _conversations.get(conversation_id)
|
||||
if conv is None:
|
||||
return {"success": False, "message": "会话不存在,请先创建对话或加载文档"}
|
||||
|
||||
try:
|
||||
docs = conv.get("documents", [])
|
||||
|
||||
if not docs:
|
||||
# ========== 无文档模式:纯 LLM 对话 ==========
|
||||
context = "(本次对话无关联文档,请直接回答用户问题)"
|
||||
sources = []
|
||||
mode = "chat"
|
||||
elif conv.get("vectorized") and conv.get("collection_name"):
|
||||
# ========== 向量模式:检索 top-5 相关片段 ==========
|
||||
from app.knowledge.embeddings import get_embedding_provider
|
||||
from app.knowledge.vector_store import KnowledgeVectorStore
|
||||
from app.config.settings import load_settings
|
||||
|
||||
settings = load_settings()
|
||||
provider = get_embedding_provider(
|
||||
provider="", cache_dir=str(settings.data_root / "embedding_cache")
|
||||
)
|
||||
vs = KnowledgeVectorStore(
|
||||
persist_dir=settings.chroma_dir,
|
||||
collection_name=conv["collection_name"],
|
||||
embedding_provider=provider,
|
||||
)
|
||||
hits = vs.search(question, top_k=5)
|
||||
context = "\n\n".join(
|
||||
f"【片段 {i + 1}】来源:{h.get('metadata', {}).get('filename', '未知')}\n{h.get('text', '')}"
|
||||
for i, h in enumerate(hits)
|
||||
)
|
||||
sources = [
|
||||
{
|
||||
"filename": h.get("metadata", {}).get("filename", ""),
|
||||
"score": h.get("score"),
|
||||
"excerpt": h.get("text", "")[:150],
|
||||
}
|
||||
for h in hits[:3]
|
||||
]
|
||||
mode = "vector"
|
||||
else:
|
||||
# ========== 文本模式:文档原文进上下文 ==========
|
||||
MAX_CONTEXT_CHARS = 500_000
|
||||
total_chars = sum(d["chars"] for d in docs)
|
||||
context_parts = []
|
||||
if total_chars <= MAX_CONTEXT_CHARS:
|
||||
for doc in docs:
|
||||
context_parts.append(f"【文档:{doc['filename']}】\n{doc['text']}")
|
||||
else:
|
||||
MIN_CHARS_PER_DOC = 2000
|
||||
for doc in docs:
|
||||
quota = max(MIN_CHARS_PER_DOC, int(MAX_CONTEXT_CHARS * doc["chars"] / total_chars))
|
||||
text = doc["text"][:quota]
|
||||
context_parts.append(f"【文档:{doc['filename']}(共{doc['chars']}字符)】\n{text}")
|
||||
if doc["chars"] > quota:
|
||||
context_parts.append(f"…({doc['filename']} 内容过长已截断)")
|
||||
context = "\n\n".join(context_parts)
|
||||
sources = [
|
||||
{"filename": d["filename"], "score": None, "excerpt": d["text"][:150]}
|
||||
for d in docs[:3]
|
||||
]
|
||||
mode = "text"
|
||||
|
||||
# 多轮对话历史(超过 20 轮自动压缩摘要)
|
||||
history = conv.get("history", [])
|
||||
history_text = ""
|
||||
if history:
|
||||
if len(history) > 20:
|
||||
# 上下文压缩:保留最近 8 轮 + 对前 12 轮做摘要
|
||||
recent = history[-8:]
|
||||
older = history[:-8]
|
||||
try:
|
||||
# 简单截断(避免每次调模型摘要),取前 200 字符每条
|
||||
summary = "\n".join(
|
||||
f"{m['role']}: {m['content'][:100]}" for m in older[:12]
|
||||
)
|
||||
history_text = f"【更早对话摘要】\n{summary}\n\n【近期对话】\n"
|
||||
except Exception: # noqa: BLE001
|
||||
summary = ""
|
||||
history_text = ""
|
||||
history_text += "\n".join(
|
||||
f"{msg['role']}: {msg['content'][:200]}" for msg in recent
|
||||
)
|
||||
else:
|
||||
recent = history[-6:]
|
||||
history_text = "\n".join(
|
||||
f"{msg['role']}: {msg['content'][:200]}" for msg in recent
|
||||
)
|
||||
|
||||
if docs:
|
||||
prompt = f"""你是一个基于文档的问答助手。请严格根据以下文档内容回答用户问题。
|
||||
|
||||
【文档内容】
|
||||
{context}
|
||||
|
||||
【对话历史】
|
||||
{history_text or '(无历史)'}
|
||||
|
||||
【用户问题】
|
||||
{question}
|
||||
|
||||
【回答要求】
|
||||
1. 严格基于上述文档内容回答,禁止编造
|
||||
2. 如果文档中没有相关内容,直接回答「根据已有文档,未找到相关答案」
|
||||
3. 引用文档原文时用引号标注
|
||||
4. 用中文回答,完整有条理"""
|
||||
else:
|
||||
prompt = f"""你是一个专业的问答助手。请回答用户的问题。
|
||||
|
||||
【对话历史】
|
||||
{history_text or '(无历史)'}
|
||||
|
||||
【用户问题】
|
||||
{question}
|
||||
|
||||
请用中文回答,完整有条理。"""
|
||||
|
||||
model = get_model_for_task(model_preference, "strong")
|
||||
model_name = getattr(model, "model_name", None) or getattr(model, "model", "未知模型")
|
||||
resp = model.invoke(prompt)
|
||||
answer = resp.content if hasattr(resp, "content") else str(resp)
|
||||
|
||||
history.append({"role": "user", "content": question})
|
||||
history.append({"role": "assistant", "content": answer})
|
||||
conv["history"] = history
|
||||
conv["updated_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# 首次提问时用问题做标题
|
||||
if len(history) == 2 and conv.get("title") == conv.get("directory", "").split("\\")[-1]:
|
||||
conv["title"] = question[:20] + ("…" if len(question) > 20 else "")
|
||||
|
||||
_save_persisted()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"answer": answer,
|
||||
"model": model_name,
|
||||
"sources": sources,
|
||||
"history_count": len(history),
|
||||
"mode": mode,
|
||||
}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.exception("问答失败")
|
||||
return {"success": False, "message": f"问答失败:{exc}"}
|
||||
|
||||
|
||||
def clear_conversation(conversation_id: str) -> bool:
|
||||
"""清除会话历史。"""
|
||||
if conversation_id in _conversations:
|
||||
_conversations[conversation_id]["history"] = []
|
||||
_save_persisted()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def delete_conversation(conversation_id: str) -> bool:
|
||||
"""删除会话(彻底移除)。"""
|
||||
if conversation_id in _conversations:
|
||||
del _conversations[conversation_id]
|
||||
_save_persisted()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def list_conversations() -> list[dict[str, Any]]:
|
||||
"""列出所有活跃会话(含标题、时间、消息数)。"""
|
||||
items = []
|
||||
for cid, conv in _conversations.items():
|
||||
items.append({
|
||||
"conversation_id": cid,
|
||||
"title": conv.get("title", "未命名对话"),
|
||||
"directory": conv.get("directory", ""),
|
||||
"total_chars": conv.get("total_chars", 0),
|
||||
"file_count": len(conv.get("documents", [])),
|
||||
"history_count": len(conv.get("history", [])),
|
||||
"vectorized": conv.get("vectorized", False),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
"updated_at": conv.get("updated_at", ""),
|
||||
})
|
||||
# 按更新时间倒序
|
||||
items.sort(key=lambda x: x.get("updated_at", ""), reverse=True)
|
||||
return items
|
||||
Reference in New Issue
Block a user