feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1,233 @@
|
||||
"""
|
||||
文档问答 API
|
||||
============
|
||||
|
||||
【功能说明】基于指定目录下文档的多轮对话式问答接口。
|
||||
【实现思路】目录索引 + 对话问答 + 会话管理。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.schemas.project import ApiResponse
|
||||
from app.services.doc_qa_service import (
|
||||
chat,
|
||||
clear_conversation,
|
||||
delete_conversation,
|
||||
list_conversations,
|
||||
load_directory,
|
||||
vectorize,
|
||||
_conversations,
|
||||
)
|
||||
|
||||
logger = logging.getLogger("agent.doc_qa.api")
|
||||
|
||||
router = APIRouter(prefix="/api/docqa", tags=["文档问答"])
|
||||
|
||||
|
||||
@router.get("/browse", response_model=ApiResponse[dict], summary="浏览目录")
|
||||
def browse_directory(path: str = "") -> ApiResponse[dict]:
|
||||
"""
|
||||
列出指定目录下的子目录和文件(供前端目录选择器浏览)。
|
||||
|
||||
【请求参数】path:目录路径(留空返回 D:\\ 根目录)
|
||||
【返回】{path, parent, directories: [...], files: [...]}
|
||||
"""
|
||||
if not path:
|
||||
path = "D:\\"
|
||||
|
||||
target = Path(path)
|
||||
if not target.exists() or not target.is_dir():
|
||||
return ApiResponse(code=404, message=f"目录不存在:{path}", data=None)
|
||||
|
||||
try:
|
||||
dirs = []
|
||||
files = []
|
||||
for item in sorted(target.iterdir()):
|
||||
if item.name.startswith("."):
|
||||
continue
|
||||
if item.is_dir():
|
||||
dirs.append({"name": item.name, "path": str(item), "type": "dir"})
|
||||
else:
|
||||
size = item.stat().st_size
|
||||
files.append({
|
||||
"name": item.name,
|
||||
"path": str(item),
|
||||
"type": "file",
|
||||
"size": size,
|
||||
"ext": item.suffix.lower(),
|
||||
})
|
||||
|
||||
parent = str(target.parent) if target.parent != target else None
|
||||
|
||||
return ApiResponse(
|
||||
code=0,
|
||||
message=f"共 {len(dirs)} 个子目录,{len(files)} 个文件",
|
||||
data={
|
||||
"path": str(target),
|
||||
"parent": parent,
|
||||
"directories": dirs,
|
||||
"files": files,
|
||||
},
|
||||
)
|
||||
except PermissionError:
|
||||
return ApiResponse(code=403, message=f"无权限访问:{path}", data=None)
|
||||
except Exception as exc:
|
||||
return ApiResponse(code=500, message=f"浏览失败:{exc}", data=None)
|
||||
|
||||
|
||||
@router.post("/index", response_model=ApiResponse[dict], summary="加载文档")
|
||||
def create_index(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||
"""
|
||||
加载文档到内存(**不做向量化**,秒级完成)。
|
||||
|
||||
【请求体】
|
||||
{"directory": "D:\\xx"} — 加载目录下全部文档
|
||||
{"file_paths": ["D:\\xx\\a.md", ...]} — 加载指定文件(可多选)
|
||||
两者至少提供其一
|
||||
【返回】conversation_id
|
||||
"""
|
||||
directory = payload.get("directory", "")
|
||||
file_paths = payload.get("file_paths", [])
|
||||
|
||||
if not directory and not file_paths:
|
||||
return ApiResponse(code=422, message="directory 或 file_paths 必须提供其一", data=None)
|
||||
|
||||
result = load_directory(
|
||||
directory=Path(directory) if directory else None,
|
||||
file_paths=file_paths if file_paths else None,
|
||||
)
|
||||
if not result.get("success"):
|
||||
return ApiResponse(code=1, message=result.get("message", "解析失败"), data=result)
|
||||
return ApiResponse(
|
||||
code=0,
|
||||
message=f"文档加载完成:{result.get('file_count', 0)} 个文件(可直接提问)",
|
||||
data=result,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/vectorize", response_model=ApiResponse[dict], summary="手动向量化")
|
||||
def vectorize_endpoint(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||
"""
|
||||
手动触发向量化(**可选操作**,大文档/高频问答时用)。
|
||||
|
||||
【请求体】{"conversation_id": "conv_xxx"}
|
||||
"""
|
||||
conversation_id = payload.get("conversation_id", "")
|
||||
if not conversation_id:
|
||||
return ApiResponse(code=422, message="conversation_id 必填", data=None)
|
||||
|
||||
result = vectorize(conversation_id)
|
||||
if not result.get("success"):
|
||||
return ApiResponse(code=1, message=result.get("message", "向量化失败"), data=result)
|
||||
return ApiResponse(code=0, message=result.get("message", "向量化完成"), data=result)
|
||||
|
||||
|
||||
@router.post("/chat", response_model=ApiResponse[dict], summary="文档问答")
|
||||
def chat_endpoint(payload: dict[str, Any]) -> ApiResponse[dict]:
|
||||
"""
|
||||
基于文档内容回答用户问题(多轮对话)。无文档时走纯 LLM 问答。
|
||||
|
||||
【请求体】{
|
||||
"conversation_id": "conv_xxx",
|
||||
"question": "问题内容",
|
||||
"model_preference": "auto" 或具体模型 ID
|
||||
}
|
||||
"""
|
||||
conversation_id = payload.get("conversation_id", "")
|
||||
question = (payload.get("question") or "").strip()
|
||||
model_preference = payload.get("model_preference", "auto")
|
||||
|
||||
# 无对话时创建纯对话会话(不需要文档)
|
||||
if not conversation_id:
|
||||
conversation_id = f"conv_{uuid.uuid4().hex[:12]}"
|
||||
from app.services.doc_qa_service import _conversations, _save_persisted
|
||||
import time
|
||||
|
||||
_conversations[conversation_id] = {
|
||||
"directory": "",
|
||||
"documents": [],
|
||||
"vectorized": False,
|
||||
"collection_name": None,
|
||||
"history": [],
|
||||
"total_chars": 0,
|
||||
"title": question[:20] + ("…" if len(question) > 20 else ""),
|
||||
"created_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
}
|
||||
_save_persisted()
|
||||
|
||||
if not question:
|
||||
return ApiResponse(code=422, message="question 必填", data=None)
|
||||
|
||||
result = chat(conversation_id, question, model_preference=model_preference)
|
||||
if not result.get("success"):
|
||||
return ApiResponse(code=1, message=result.get("message", "问答失败"), data=result)
|
||||
result["conversation_id"] = conversation_id
|
||||
return ApiResponse(code=0, message="ok", data=result)
|
||||
|
||||
|
||||
@router.post("/clear", response_model=ApiResponse[bool], summary="清除会话历史")
|
||||
def clear_endpoint(payload: dict[str, Any]) -> ApiResponse[bool]:
|
||||
"""清除指定会话的对话历史。"""
|
||||
conversation_id = payload.get("conversation_id", "")
|
||||
if not conversation_id:
|
||||
return ApiResponse(code=422, message="conversation_id 必填", data=None)
|
||||
ok = clear_conversation(conversation_id)
|
||||
return ApiResponse(code=0, message="历史已清除", data=ok)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/conversations/{conversation_id}", response_model=ApiResponse[bool], summary="删除会话"
|
||||
)
|
||||
def delete_conversation_endpoint(conversation_id: str) -> ApiResponse[bool]:
|
||||
"""彻底删除指定会话。"""
|
||||
ok = delete_conversation(conversation_id)
|
||||
if not ok:
|
||||
return ApiResponse(code=404, message="会话不存在", data=False)
|
||||
return ApiResponse(code=0, message="会话已删除", data=True)
|
||||
|
||||
|
||||
@router.get("/conversations", response_model=ApiResponse[list[dict]], summary="会话列表")
|
||||
def conversations_endpoint() -> ApiResponse[list[dict]]:
|
||||
"""列出所有活跃的问答会话(含标题、时间、消息数)。"""
|
||||
items = list_conversations()
|
||||
return ApiResponse(code=0, message=f"共 {len(items)} 个会话", data=items)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/conversations/{conversation_id}",
|
||||
response_model=ApiResponse[dict],
|
||||
summary="会话详情(含历史消息)",
|
||||
)
|
||||
def conversation_detail(conversation_id: str) -> ApiResponse[dict]:
|
||||
"""
|
||||
获取指定会话的完整对话历史(含消息列表)。
|
||||
|
||||
【返回】{title, directory, history: [{role, content}]}
|
||||
"""
|
||||
conv = _conversations.get(conversation_id)
|
||||
if conv is None:
|
||||
return ApiResponse(code=404, message="会话不存在", data=None)
|
||||
|
||||
return ApiResponse(
|
||||
code=0,
|
||||
message="ok",
|
||||
data={
|
||||
"conversation_id": conversation_id,
|
||||
"title": conv.get("title", "未命名对话"),
|
||||
"directory": conv.get("directory", ""),
|
||||
"history": conv.get("history", []),
|
||||
"total_chars": conv.get("total_chars", 0),
|
||||
"file_count": len(conv.get("documents", [])),
|
||||
"vectorized": conv.get("vectorized", False),
|
||||
"created_at": conv.get("created_at", ""),
|
||||
},
|
||||
)
|
||||
Reference in New Issue
Block a user