Skip to content

第 01 章 · 第一个 Deep Agent 与文件工具 ​

使用模型的章节需要自备支持工具调用的模型服务与 API Key(可为任意 OpenAI 兼容端点),运行会产生费用。

机制与设计选择 ​

Deep Agent 不只是“调模型”:它内置虚拟文件系统(ls/read_file/write_file/edit_file/delete/glob/grep)与一个默认 general-purpose 子智能体。默认 backend 是 StateBackend,文件保存在线程状态中,不会写到你的磁盘。给模型一个简单领域工具(查课程时长),并要求它把结果写文件,即可观察“工具 + 文件系统”闭环。

示例 ​

python
import os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from deepagents import create_deep_agent

@tool
def course_hours(course: str) -> str:
    """Return estimated study hours for a known course."""
    return {"langgraph": "12", "deepagents": "10"}.get(course.lower(), "unknown")

model = ChatOpenAI(
    model=os.environ["MODEL_ID"],
    api_key=os.environ["DEEPAGENT_API_KEY"],
    base_url=os.environ.get("DEEPAGENT_BASE_URL", "https://api.openai.com/v1"),
)

agent = create_deep_agent(
    model=model,
    tools=[course_hours],
    system_prompt="You are a course planning assistant. Record results with the write_file tool.",
)

config = {"configurable": {"thread_id": "ch01"}}
result = agent.invoke(
    {"messages": [{"role": "user", "content": "Use course_hours for deepagents, then write the answer to /plan.txt."}]},
    config=config,
)
print(result["messages"][-1].content)

import pathlib
assert not pathlib.Path("/plan.txt").exists()  # file lives in thread state, not on disk
print("ok: no /plan.txt on the host filesystem")

运行与验收 ​

额外安装 langchain-openai。配置 MODEL_ID、DEEPAGENT_API_KEY(可选 DEEPAGENT_BASE_URL 指向兼容端点)。验收:最终消息提到 10 小时,且 /plan.txt 没有出现在你的磁盘上,因为它属于 StateBackend。

容易踩的坑 ​

不要假定文件落在磁盘:默认是线程内的虚拟状态。需要跨线程持久化才换 StoreBackend;需要真实项目文件才用 FilesystemBackend。工具是模型可见的能力,不是安全边界——参数与权限仍在你的代码里校验。

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. 默认 backend 是什么?

2. write_file 需要额外安装吗?

3. 线程之间默认共享文件吗?

4. 工具可以替代授权检查吗?

动手实践 ​

  1. 用 ls 与 read_file 读回 /plan.txt 验证内容。
  2. 换一个未知课程名,验证 unknown 分支。
  3. 列出本章可用的文件工具并说明各自用途。

官方参考 ​

核验日期:2026-09-17,运行环境:Deep Agents 0.7.15。