08 Chroma 持久化 + FastAPI 封装
2026/8/14 17:06:30 网站建设 项目流程

Chroma 持久化 + FastAPI 封装

安装依赖

cdD:\yunyanshijie\skill_test\python_study .venv\Scripts\activate pipinstallchromadb langchain-chroma

Chroma 持久化

为什么要换?

InMemoryVectorStoreChroma
存储位置进程内存磁盘 chroma_db/
重启后索引丢失,需重新 Embedding直接加载,秒级启动
适用场景学习、调试接近真实部署

核心 API

fromlangchain_chromaimportChromadefbuild_vectorstore(chunks,embeddings,chroma_dir:Path):chroma_dir.mkdir(parents=True,exist_ok=True)ifany(chroma_dir.iterdir()):# 目录非空 → 已有索引,库已存在,直接加载print("从磁盘加载向量库...")returnChroma(persist_directory=str(chroma_dir),embedding_function=embeddings,collection_name="knowledge",)else:# 首次 → 建库(文档切分后)print("首次运行,正在建索引...")returnChroma.from_documents(documents=chunks,embedding=embeddings,persist_directory=str(chroma_dir),collection_name="knowledge",)

FastAPI 封装

架构

POST /chat

startup 一次

Client

FastAPI

agent_core

chroma_db

LangGraph

DeepSeek

重点:向量库和 Graph 在 服务启动时初始化一次,不是每个请求重建。

生命周期(lifespan)

FastAPI 推荐用 lifespan,在 startup 里完成初始化:

fromcontextlibimportasynccontextmanager graph=None@asynccontextmanagerasyncdeflifespan(app:FastAPI):globalgraph# 在函数里要赋值模块级变量时必须写,否则 Python 会当成函数局部变量graph=init_graph()# 内部调 build_vectorstore + build_graphyield# 关服务 → yield 之后的代码再跑(清理)# shutdown 清理app=FastAPI(lifespan=lifespan)

接口设计

classChatRequest(BaseModel):message:strthread_id:str="default"classChatResponse(BaseModel):reply:strsources:list[str]=[]# 这是 RAG 的 溯源(citation):不只给答案,还告诉用户「依据哪些文档」。
路由方法作用
/healthGET健康检查,返回 {“status”: “ok”, “chunks”: N}
/chatPOST发送消息,返回回答 + 引用来源

/chat 核心逻辑

@app.post("/chat",response_model=ChatResponse)defchat(req:ChatRequest):config={"configurable":{"thread_id":req.thread_id}}result=graph.invoke({"messages":[HumanMessage(content=req.message)],"context":""},config=config,)reply=result["messages"][-1].content sources=result.get("sources",[])# 见下方「溯源」returnChatResponse(reply=reply,sources=sources)

检索溯源

在 AgentState 里加一个字段:

classAgentState(TypedDict):messages:Annotated[list,add_messages]context:strsources:list[str]# 新增

retrieve 节点里:

sources=[str(doc.metadata.get("source","unknown"))fordocinresults]return{"context":context,"sources":sources}

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询