1. Retrieval

1.1. Resources

1.2. Workflow

retrieve_context 用 @tool(response_format="content_and_artifact")。同一次返回里,content 和 artifact 是同一个 ToolMessage 的两面。

左边的 ToolMessage.content 进模型上下文,是拼好的文档字符串,供推理和最终回答。右边的 ToolMessage.artifact 留在应用侧,这里是原始 Document 列表。run_llm 从 artifact 取出这些文档,放进返回值的 context。

1.3. INCLUDES

  • OpenAIEmbeddings(已注释)
  • init_chat_model("gpt-5.2")(已注释)
  • ZhipuAIEmbeddings
  • ChatZhipuAI(glm-4-plus)
  • PineconeVectorStore langchain-docs-zhipu
  • retrieve_context:content + artifact
  • create_agent 调用检索工具
  • 从最后一条 AI 消息取 answer,从 ToolMessage.artifact 取 context

1.4. 改用智谱

backend/core.py 的嵌入和聊天模型都改成智谱,和 ingestion.py、create_index.py 用同一套索引。课程代码是 OpenAI text-embedding-3-small(1536 维)、索引 langchain-docs,以及 init_chat_model("gpt-5.2", model_provider="openai")。当前入库的是 langchain-docs-zhipu(embedding-3,1024 维)。ZhipuAIEmbeddings 和 ChatZhipuAI 默认读 ZHIPUAI_API_KEY,这里把 .env 里的 ZHIPU_API_KEY 传给 api_key。

# from langchain.chat_models import init_chat_model
from langchain_community.chat_models.zhipuai import ChatZhipuAI
from langchain_community.embeddings import ZhipuAIEmbeddings
# from langchain_openai import OpenAIEmbeddings

# embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
embeddings = ZhipuAIEmbeddings(
    model="embedding-3",
    dimensions=1024,
    api_key=os.environ["ZHIPU_API_KEY"],
)
# vectorstore = PineconeVectorStore(
#     index_name="langchain-docs", embedding=embeddings
# )
vectorstore = PineconeVectorStore(
    index_name="langchain-docs-zhipu", embedding=embeddings
)
# model = init_chat_model("gpt-5.2", model_provider="openai")
model = ChatZhipuAI(
    model="glm-4-plus",
    api_key=os.environ["ZHIPU_API_KEY"],
)

1.5. 检索工具

retrieve_context 用向量库的 retriever 取最相近的 4 条。拼进 content 的是来源和正文;第二个返回值原样作为 artifact。

@tool(response_format="content_and_artifact")
def retrieve_context(query: str):
    """Retrieve relevant documentation to help answer user queries about LangChain."""
    retrieved_docs = vectorstore.as_retriever().invoke(query, k=4)
    serialized = "\n\n".join(
        (f"Source: {doc.metadata.get('source', 'Unknown')}\n\nContent: {doc.page_content}")
        for doc in retrieved_docs
    )
    return serialized, retrieved_docs

1.6. 回答问题

run_llm 用 create_agent 把 glm-4-plus 和 retrieve_context 接在一起。系统提示要求先检索,再回答,并写出来源。用户问题放进 messages 后调用 agent。最后一条消息的 content 是回答。遍历消息时,只从带 artifact 的 ToolMessage 里收集 Document。

agent = create_agent(model, tools=[retrieve_context], system_prompt=system_prompt)
messages = [{"role": "user", "content": query}]
response = agent.invoke({"messages": messages})
answer = response["messages"][-1].content

context_docs = []
for message in response["messages"]:
    if isinstance(message, ToolMessage) and hasattr(message, "artifact"):
        if isinstance(message.artifact, list):
            context_docs.extend(message.artifact)

return {
    "answer": answer,
    "context": context_docs
}

文件直接运行时问的是 what are deep agents?:

if __name__ == '__main__':
    result = run_llm(query="what are deep agents?")
    print(result)

1.7. 测试 Output

在编辑器里 Run backend/core.py。导入 ChatZhipuAI 时先打出 langchain-community 的 DeprecationWarning,随后打印 run_llm 的字典。进程退出码 0,用时 11.627 秒。

/Users/admin/Code/documentation-helper/backend/core.py:9: DeprecationWarning: `langchain-community` is being sunset and is no longer actively maintained. See https://github.com/langchain-ai/langchain-community/issues/674 for details and migration guidance toward standalone integration packages.
  from langchain_community.chat_models.zhipuai import ChatZhipuAI

answer 根据检索到的文档说明 Deep Agents,并在末尾给出来源:

{'answer': '\nBased on the LangChain documentation, **Deep Agents** is an advanced agent harness designed for complex, multi-step work. ...
Source: [Deep Agents Overview - LangChain Documentation](https://docs.langchain.com/oss/python/deepagents/overview.md)', ...}

context 里是 4 个 Document,对应 artifact 里的原始检索结果。两条来自 overview 的不同 chunk,另外两条分别是 models 和 customization:

f9749fe5-d349-4ce7-b09d-d20779faa1e2
{'source': 'https://docs.langchain.com/oss/python/deepagents/overview.md'}

5f4dfb0f-8fe9-45b6-9161-ca0c301f39be
{'source': 'https://docs.langchain.com/oss/python/deepagents/overview.md'}

3f8e6fd5-afbb-45c6-952b-1442eb72be13
{'source': 'https://docs.langchain.com/oss/python/deepagents/models.md'}

618e7932-6637-4266-87b5-bba707e06fe6
{'source': 'https://docs.langchain.com/oss/python/deepagents/customization.md'}

第一条 page_content 的开头:

> ## Documentation Index > Fetch the complete documentation index at: https://docs.langchain.com/llms.txt > Use this file to discover all available pages before exploring further. # Deep Agents overview
[Done] exited with code=0 in 11.627 seconds

.env 里开了 LANGSMITH_TRACING。同一次调用在 LangSmith 里是一条 LangGraph trace:先走 glm-4-plus,再调用 retrieve_context(里面是 VectorStoreRetriever),最后再走一次 glm-4-plus 写出回答。Trace 总时长 8.43 秒。

ccq/2-retrieval-qa-finish

26.12.02

results matching ""

    No results matching ""