Skip to content

实战:文档问答 Agent

构建一个可以读取文档并回答问题的研究型 Agent。

本例基于官方 LangChain Quickstart 中的研究 Agent 示例。你将构建一个能够获取 URL 文档内容并回答问题的 Agent。

1. 定义系统提示词

系统提示词定义了 Agent 的角色和行为:

python
SYSTEM_PROMPT = """You are a literary data assistant.

## Capabilities

- `fetch_text_from_url`: loads document text from a URL into the conversation.
Do not guess line counts or positions—ground them in tool results from the saved file."""

2. 创建工具

工具让模型可以通过调用你定义的函数与外部系统交互:

python
import urllib.error
import urllib.request

from langchain.tools import tool


@tool
def fetch_text_from_url(url: str) -> str:
    """Fetch the document from a URL."""
    req = urllib.request.Request(
        url,
        headers={"User-Agent": "Mozilla/5.0 (compatible; quickstart-research/1.0)"},
    )
    try:
        with urllib.request.urlopen(req, timeout=120) as resp:
            raw = resp.read()
    except urllib.error.URLError as e:
        return f"Fetch failed: {e}"
    text = raw.decode("utf-8", errors="replace")
    return text

3. 配置模型

python
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "openai:gpt-4o",
    temperature=0.5,
    timeout=300,
    max_tokens=25000,
)

4. 添加记忆

python
from langgraph.checkpoint.memory import InMemorySaver

checkpointer = InMemorySaver()

5. 创建并运行 Agent

python
from langchain.agents import create_agent

agent = create_agent(
    model=model,
    tools=[fetch_text_from_url],
    system_prompt=SYSTEM_PROMPT,
    checkpointer=checkpointer,
)

from langchain_core.utils.uuid import uuid7

config = {"configurable": {"thread_id": str(uuid7())}}

result = agent.invoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "Fetch https://www.gutenberg.org/files/64317/64317-0.txt and tell me about it",
            }
        ]
    },
    config=config,
)

print(result["messages"][-1].content)

下一步

本站为非官方中文学习站点,不代表 LangChain 官方。部分内容参考官方文档并重新整理为中文学习笔记。