本快速开始展示如何在几分钟内创建一个功能完整的 AI 代理。
正在使用 AI 编程助手?

安装依赖

安装以下包以跟随操作:
uv init
uv add langchain deepagents
uv sync

设置 API keys

任意支持的模型 provider 获取 API key(例如 Google Gemini 或 OpenAI)。 设置 API keys,例如:
export OPENAI_API_KEY="your-api-key"

构建基础代理

首先创建一个可以回答问题并调用工具的简单代理。此示例中的代理使用所选语言模型、作为工具的基础天气函数,以及用于引导其行为的简单 prompt:
from langchain.agents import create_agent

def get_weather(city: str) -> str:
    """Get weather for a given city."""
    return f"It's always sunny in {city}!"

agent = create_agent(
    model="openai:gpt-5.4",
    tools=[get_weather],
    system_prompt="You are a helpful assistant",
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]}
)
print(result["messages"][-1].content_blocks)
运行代码并提示代理告诉你 San Francisco 的天气时,代理会使用该输入和它可用的上下文。 代理会理解你在询问 San Francisco 这座城市的天气,因此会使用提供的城市名称调用天气工具。
可以通过更改模型名称并设置相应 API key 来使用任意支持的模型。使用 LangSmith 跟踪代理内部发生的事情。按照 tracing quickstart 完成设置。还建议设置 LangSmith Engine,它会监控 traces、检测问题并提出修复建议。

构建真实世界代理

在下面的示例中,你将构建一个可以回答文本文件相关问题的研究代理。 在此过程中,你将探索以下概念:
  1. 用于改善代理行为的详细 system prompts
  2. 创建工具以集成外部数据
  3. 用于一致响应的模型配置
  4. 用于聊天式交互的对话记忆
  5. 提供内置功能的 Deep Agents
  6. 测试你的代理
1

定义 system prompt

System prompt 定义代理的角色和行为。保持具体且可执行:
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

创建工具

Tools 让模型通过调用你定义的函数与外部系统交互。 Tools 可以依赖 runtime context,也可以与 agent memory 交互。此示例使用一个工具从给定 URL 加载文档:
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
工具应该有清晰文档:它们的名称、描述和参数名会成为模型 prompt 的一部分。 LangChain 的 @tool decorator 会添加 metadata,并通过 ToolRuntime 参数启用 runtime injection。 详情请参阅 tools guide
3

配置模型

使用适合用例的参数设置你的 language model。例如:
from langchain.chat_models import init_chat_model

model = init_chat_model(
    "openai:gpt-5.4",
    temperature=0.5,
    timeout=300,
    max_tokens=25000,
)
根据所选模型和 provider,初始化参数可能有所不同;详情请参阅各自的参考页面。
4

添加 memory

为代理添加 memory,以在交互之间维护状态。这让代理能够记住先前对话和上下文。
from langgraph.checkpoint.memory import InMemorySaver

checkpointer = InMemorySaver()
在生产环境中,请使用将消息历史保存到数据库的持久 checkpointer。 更多详情请参阅 Add and manage memory
5

创建并运行代理

现在用所有组件组装你的代理并运行它。创建代理有两个不同框架:LangChain agents 和 deep agents。 LangChain 和 deep agents 都为工具、memory 等提供细粒度控制。 二者主要区别是 deep agents 已内置一系列常用能力,例如规划、文件系统工具和 subagents。当你想用最少设置获得最大能力时使用 deep agents;当你需要细粒度控制时选择 LangChain agents。
由于代码会使用 The Great Gatsby 全文调用模型,因此会消耗大量 tokens。可以在下一步查看示例输出。
两者都试一下:
from langchain.agents import create_agent
from deepagents import create_deep_agent

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

deep_agent = create_deep_agent(
    model=model,
    tools=[fetch_text_from_url],
    system_prompt=SYSTEM_PROMPT,
    checkpointer=checkpointer,
)

content = f"""Project Gutenberg hosts a full plain-text copy of F. Scott Fitzgerald's The Great Gatsby.
URL: https://www.gutenberg.org/files/64317/64317-0.txt

Answer as much as you can:

1) How many lines in the complete Gutenberg file contain the substring `Gatsby` (count lines, not occurrences within a line, each line ends with a line break).
2) The 1-based line number of the first line in the file that contains `Daisy`.
3) A two-sentence neutral synopsis.

Do your best on (1) and (2). If at any point you realize you cannot **verify** an exact answer with
your available tools and reasoning, do not fabricate numbers: use `null` for that field and spell out
the limitation in `how_you_computed_counts`. If you encounter any errors please report what the error was and what the error message was."""

agent_result = agent.invoke(
    {"messages": [{"role": "user", "content": content}]},
    config={"configurable": {"thread_id": "great-gatsby-lc"}},
)
deep_agent_result = deep_agent.invoke(
    {"messages": [{"role": "user", "content": content}]},
    config={"configurable": {"thread_id": "great-gatsby-da"}},
)
print(agent_result["messages"][-1].content_blocks)
print("\n")
print(deep_agent_result["messages"][-1].content_blocks)
6

查看结果

结果会根据模型和执行情况而有所不同。
**1) Number of lines containing `Gatsby`:** `null`

**2) First line containing `Daisy`:** `null`

**3) Synopsis:**
The Great Gatsby follows the mysterious millionaire Jay Gatsby and his obsession with reuniting with his former lover, Daisy Buchanan, as narrated by his neighbor Nick Carraway. Set against the backdrop of the Roaring Twenties on Long Island, the novel explores themes of wealth, class, and the elusive nature of the American Dream.

**how_you_computed_counts:**
I successfully fetched the full text of the eBook using the `fetch_text_from_url` tool. However, because I do not have access to a code execution environment (like Python) or text-processing tools (like `grep`), I cannot deterministically split the text by line breaks, iterate through the thousands of lines, and verify the exact line numbers or match counts. LLMs cannot reliably perform exact line-counting or indexing over massive texts within their context window without external computational tools. As instructed, rather than fabricating or guessing a number, I have output `null` for the exact counts and positions.
如果查看两个标签页中的输出,会发现 LangChain agent 提供了答案,但这些答案是估计值。该代理缺少回答此问题所需的工具。你也可能遇到 prompt 过长的错误。另一方面,deep agent 可以:
  1. 使用内置 write_todos 工具规划方法,分解研究任务。
  2. 调用 fetch_text_from_url 工具加载文件以收集信息。
  3. 使用文件系统工具(grepread_file管理上下文
  4. 按需生成 subagents,将复杂子任务委派给专门的 subagents。
对于 LangChain agents,你必须实现更多能力才能获得类似服务水平,并且可以在过程中按需自定义。

跟踪代理调用

你使用 LangChain 构建的大多数有趣应用都会多次调用 LLM。随着这些应用变得更复杂,能够检查代理内部究竟发生了什么会变得很重要。最好的方式是使用 LangSmith 注册 LangSmith 账户,并设置这些环境变量以开始记录 traces:
export LANGSMITH_TRACING="true"
export LANGSMITH_API_KEY="..."
设置完成后,再次运行脚本,然后在 LangSmith 上检查代理调用期间发生的事情。
要进一步了解如何使用 LangSmith 跟踪代理,请参阅 LangSmith documentation还建议设置 LangSmith Engine,它会监控 traces、检测问题并提出修复建议。

下一步

现在你的代理可以:
  • 理解上下文并记住对话
  • 智能使用工具
  • 以一致格式提供结构化响应
  • 通过 context 处理用户特定信息
  • 跨交互维护对话状态
  • 规划、研究并综合信息(仅 deep agents)
继续阅读: