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 相同,所以你可以並排比較兩份輸出。

為甚麼這個實驗值得做

延伸閱讀