How to use LangChain in an AI agent (ReAct, version 7)?
Since version 1 we have written the Think → Act → Observe loop in plain Python. Version 7 keeps the same agent as version 6, but makes one change. We now use LangChain, a framework, to do the same job with less code.
The script
This is ReAct07.py. Three pieces replace the code we wrote in
the previous version without LangChain. First, the @tool
decorator turns an ordinary function into a tool the model can call:
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)
Second, create_agent() builds the whole loop:
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.""",
)
Third, perform_task shrinks to one call. There is no
for loop, no stop=["Action"], no
re.search, because LangChain thinks, calls the tool, observes
and repeats until the model answers:
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?")
The memory functions (load_memory, save_memory,
memory_text) and the memory reset at the bottom are identical
to version 6,
so they are omitted here. The full script also prints each step LangChain
ran, using the message types (AIMessage for Thought/Action,
ToolMessage for Observation).
One real run
--- 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.
Two things are worth noticing. First, the agent fired two searches in one turn — our hand-written loop forced one action per round, but function calling lets the model ask for several tools at once — here it searched for "Mark launched Muse" and "Mark Zuckerberg launches Muse app" in the same reply. Second, task 2 behaved exactly as in version 6: it read the memory, knew what "it" was, and answered with sources. Changing the engine did not change the behaviour — which is the point.
Running it on your own computer
Download the demo program
(Folder-AI-ReAct07.zip). The zip holds three files:
ReAct07.py (the full script), pyproject.toml and
README.md.
- Open the folder in Visual Studio Code.
-
Create a file named
.envin the folder with two lines:
Keys: DeepSeek console and Tavily (both have free starting credit).DEEPSEEK_API_KEY=your-deepseek-key TAVILY_API_KEY=your-tavily-key - In the Terminal, run:
uv sync uv run ReAct07.pyuv syncinstalls LangChain for you; the.envfile and the two tasks are the same as version 6, so you can compare the two printouts side by side.
Why this experiment matters
- A framework does the chores, not the thinking. The agent still thinks, acts and observes exactly as before — LangChain simply does the housekeeping we wrote by hand in previous versions.
- We tell LangChain exactly which tools the agent may use. In the previous versions, the model wrote the tool's name as text, and our code had to find it and run it. Now the model picks from the list of tools we gave LangChain — nothing to find, nothing to get wrong.
- Build it in Python first, without any framework, as in the previous versions; then use LangChain, as in this version. Having written the loop yourself, you can read exactly what LangChain is doing for you — and debug it when it does something unexpected.
Further reading
- LangChain documentation —
create_agent, tools and messages. - ReAct: Synergizing Reasoning and Acting in Language Models — the paper that named the pattern this series builds.
- Tavily documentation — search options, free tier and pricing.
- DeepSeek API documentation — models, keys and pricing.