English 繁體中文 简体中文

如何在 AI 代理中使用 LangChain(ReAct,版本 7)?

林邦源博士 · AI 笔记 · 2026 年 11 月 9 日 · 约 4 分钟阅读

自从版本 1以来, 我们一直用纯 Python 写“思考 → 行动 → 观察”循环。 版本 7 保留版本 6 的代理,只改了一件事:我们现在改用 LangChain 这个框架, 用更少的代码做同一件事。

程序

这是 ReAct07.py。三段代码取代了上一版没用 LangChain 时 我们自己写的那部分。第一,@tool 装饰器把一个普通函数变成 模型可以调用的工具:

from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent

model = ChatOpenAI(
    model="deepseek-flash",
    api_key=os.environ.get('DEEPSEEK_API_KEY'),
    base_url="https://api.deepseek.com")

# The only tool (action) our agent can use — @tool makes it usable by LangChain
@tool
def search_tavily(query: str) -> str:
    """Search the web (Tavily) and return the top results (title, url, short content)."""
    results = tavily.search(query=query, max_results=3)["results"]
    if not results:
        return f"No web results found for '{query}'."
    return "\n".join(f"[{r['title']}] ({r['url']}) {r['content'][:400]}"
                     for r in results)

第二,create_agent() 建立整个循环:

agent = create_agent(
    model=model,
    tools=[search_tavily],
    system_prompt=f"""You are a helpful research assistant. Today is {today}.
Use the search_tavily tool when you need up-to-date facts.
If your memory already answers the task, you may answer without searching.""",
)

第三,perform_task 缩短成一次调用。没有 for 循环,没有 stop=["Action"],也没有 re.search, 因为 LangChain 会自己思考、调用工具、观察,然后重复,直到模型给出答案:

def perform_task(task):
    """Let the LangChain agent do one task, print each step, and return the answer."""
    print(f"\n########## TASK: {task} ##########")
    print("=== Memory loaded into the prompt ===")
    print(memory_text())

    prompt = f"""Task: {task}
Memory (what you learned before, with the date you learned it):
{memory_text()}"""
    result = agent.invoke({"messages": [{"role": "user", "content": prompt}]})

    answer = result["messages"][-1].content
    print("=== Final Answer ===")
    print(answer)
    save_memory(task, answer)   # long-term memory: keep it for next time
    return answer

perform_task("When did Mark launch Muse")
perform_task("Is it available in Hong Kong yet?")

记忆相关的函数(load_memory、save_memory、 memory_text)以及程序末尾的记忆重置,都与 版本 6 完全相同, 所以这里略去。完整程序也会打印 LangChain 运行的每一步,并用消息类型标示 (AIMessage 代表思考/行动,ToolMessage 代表观察)。

一次真实运行

--- Task 1: "When did Mark launch Muse" ---
=== Memory loaded into the prompt ===
(empty)
=== AIMessage - Thought ===
I don't have any prior memory about "Mark" or "Muse" to work from, and the question is ambiguous. Let me search for likely possibilities.
=== AIMessage - Action ===
search_tavily({'query': 'Mark launched Muse'})
=== AIMessage - Action ===
search_tavily({'query': 'Mark Zuckerberg launches Muse app'})
=== ToolMessage - Observation from Tavily web search ===
[Meta Debuts Muse, Its Long-Planned Personal AI Agent - Slashdot] ... launched ...
[The New York Times] ... Mark Zuckerberg ... September 8, 2026 ...
=== Final Answer ===
Muse launched on September 8, 2026. (Meta's personal AI agent, announced by Mark Zuckerberg; a related Muse Charm keychain device targets December 2026.)

--- Task 2: "Is it available in Hong Kong yet?" ---
=== Memory loaded into the prompt ===
- [2026-10-09] Q: When did Mark launch Muse A: ...the full September 8 answer...
=== AIMessage - Action ===
search_tavily({'query': 'Meta Muse personal AI agent Hong Kong availability launch'})
=== AIMessage - Action ===
search_tavily({'query': 'Muse Spark app supported countries Hong Kong rollout 2026'})
=== ToolMessage - Observation from Tavily web search ===
...US-only launch; "Singapore, Malaysia, Hong Kong, Taiwan — No official launch announced"; App Store listing appears only in the US storefront...
=== Final Answer ===
No — Meta's Muse is not available in Hong Kong yet. ... As of now, Muse is a US-exclusive launch. No timeline has been announced for Hong Kong or any other Asia-Pacific market.

摘录已缩短(…);完整运行会把两个任务全部打印出来。

有两点值得注意。第一,代理在同一轮发出两次搜索 —— 我们手写的循环每回合只允许一个行动,但函数调用让模型可以一次请求多个工具 —— 这里它在同一个回复中搜索了 “Mark launched Muse”和 “Mark Zuckerberg launches Muse app”。第二,任务 2 的表现 与版本 6 完全一样:它读取记忆,知道“它”指什么,并附上来源作答。换了引擎 并没有改变行为 —— 这正是重点所在。

在自己的电脑上运行

下载示范程序 (Folder-AI-ReAct07.zip)。zip 内有三个文件: ReAct07.py(完整程序)、pyproject.toml 和 README.md。

  1. 在 Visual Studio Code 打开这个文件夹。
  2. 在文件夹里创建一个名为 .env 的文件,内容有两行:
    DEEPSEEK_API_KEY=your-deepseek-key
    TAVILY_API_KEY=your-tavily-key
    密钥:DeepSeek 控制台和 Tavily (两者都有免费起始额度)。
  3. 在终端运行:
    uv sync
    uv run ReAct07.py
    uv sync 会替你安装 LangChain;.env 文件的内容 和两个任务都与版本 6 相同,所以你可以并排比较两份输出。

为什么这个实验值得做

延伸阅读