"""Independent offline lab for LangChain Ch 06: First LangChain Agent (create_agent)."""
import ast
import asyncio
import json
import operator
import platform
from typing import Any
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.utils.function_calling import convert_to_openai_tool
from langgraph.errors import GraphRecursionError
OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.UAdd: operator.pos,
ast.USub: operator.neg,
}
def safe_calculate(expression: str):
"""Evaluate limited arithmetic expressions via AST whitelist (no eval)."""
if len(expression) > 100:
raise ValueError("表达式过长")
tree = ast.parse(expression, mode="eval")
def evaluate(node):
if isinstance(node, ast.Constant):
if type(node.value) in (int, float):
if abs(node.value) > 1_000_000_000:
raise ValueError("数字过大")
return node.value
if isinstance(node, ast.BinOp):
op_type = type(node.op)
if op_type not in OPERATORS:
raise ValueError("不支持的运算符")
left = evaluate(node.left)
right = evaluate(node.right)
if op_type is ast.Div and right == 0:
raise ValueError("除数不能为零")
res = OPERATORS[op_type](left, right)
if abs(res) > 1_000_000_000:
raise ValueError("计算结果过大")
return res
if isinstance(node, ast.UnaryOp):
op_type = type(node.op)
if op_type not in (ast.UAdd, ast.USub):
raise ValueError("不支持的运算符")
return OPERATORS[op_type](evaluate(node.operand))
raise ValueError("不支持的表达式")
return evaluate(tree.body)
@tool
def get_weather(city: str) -> str:
"""查询指定城市的模拟天气数据。
Args:
city: 城市名称,例如杭州、北京、上海。
"""
weather_data = {
"杭州": "晴,25°C,湿度60%",
"北京": "多云,18°C,湿度45%",
"上海": "小雨,22°C,湿度80%",
}
return weather_data.get(city, f"没有找到{city}的模拟天气数据")
@tool
def calculate(expression: str) -> str:
"""计算简单数学表达式,支持加减乘除和括号。
Args:
expression: 例如 "3 * 7 + 2" 或 "(25 - 18)"。
"""
try:
result = safe_calculate(expression)
return f"计算结果:{expression} = {result}"
except (ValueError, SyntaxError, ZeroDivisionError, OverflowError) as error:
return f"计算失败:{error}"
class DeterministicAgentModel(BaseChatModel):
"""Offline chat model driving create_agent through real ToolMessage loops."""
handler: Any = None
@property
def _llm_type(self) -> str:
return "deterministic-agent-offline"
def _generate(self, messages, stop=None, run_manager=None, **kwargs):
msg = self.handler(messages, kwargs)
return ChatResult(generations=[ChatGeneration(message=msg)])
def bind_tools(self, tools, *, tool_choice=None, **kwargs):
formatted = [convert_to_openai_tool(t) for t in tools]
return self.bind(tools=formatted, tool_choice=tool_choice, **kwargs)
def main():
cases = []
# 1. @tool metadata and AST safe calculator boundary checks
w_hz = get_weather.invoke({"city": "杭州"})
w_unknown = get_weather.invoke({"city": "拉萨"})
calc_1 = calculate.invoke({"expression": "3 * 7 + 2"})
calc_2 = calculate.invoke({"expression": "(3 + 2) * 7"})
calc_neg = calculate.invoke({"expression": "-5 + (12 / 3)"})
calc_inject = calculate.invoke({"expression": "__import__('os').system('echo hi')"})
calc_div0 = calculate.invoke({"expression": "10 / 0"})
calc_pow = calculate.invoke({"expression": "2 ** 10"})
calc_long = calculate.invoke({"expression": "1+" * 60 + "1"})
c1_ok = (
get_weather.name == "get_weather"
and "city" in get_weather.args
and w_hz == "晴,25°C,湿度60%"
and "没有找到拉萨" in w_unknown
and calc_1 == "计算结果:3 * 7 + 2 = 23"
and calc_2 == "计算结果:(3 + 2) * 7 = 35"
and calc_neg == "计算结果:-5 + (12 / 3) = -1.0"
and calc_inject.startswith("计算失败:")
and "除数不能为零" in calc_div0
and "不支持的运算符" in calc_pow
and "表达式过长" in calc_long
)
cases.append(
dict(
name="tool_decorator_and_safe_ast_calculator",
inputs=dict(cities=["杭州", "拉萨"], valid_exprs=["3 * 7 + 2", "(3 + 2) * 7"], blocked_exprs=["__import__", "10 / 0", "2 ** 10"]),
prerequisites="使用 @tool 定义 get_weather 与基于 ast 白名单的 calculate 安全计算器。",
action="核对合法城市与未知城市回退、合法四则运算结果,以及拒绝函数调用注入、除零、幂运算和超长表达式。",
expected=dict(
hz_weather="晴,25°C,湿度60%",
calc_23="计算结果:3 * 7 + 2 = 23",
calc_35="计算结果:(3 + 2) * 7 = 35",
injection_blocked=True,
div_zero_blocked=True,
pow_blocked=True,
overlength_blocked=True,
),
actual=dict(
hz_weather=w_hz,
calc_23=calc_1,
calc_35=calc_2,
injection_blocked=calc_inject.startswith("计算失败:"),
div_zero_blocked=("除数不能为零" in calc_div0),
pow_blocked=("不支持的运算符" in calc_pow),
overlength_blocked=("表达式过长" in calc_long),
),
measurements=dict(
weather_args=list(get_weather.args.keys()),
calc_args=list(calculate.args.keys()),
neg_expr_result=calc_neg,
),
passed=c1_ok,
)
)
# 2. Single-tool create_agent invoke() and 4-message trace inspection
def single_tool_handler(messages, kwargs):
tool_msgs = [m for m in messages if m.type == "tool"]
if not tool_msgs:
return AIMessage(
content="",
tool_calls=[
{
"name": "get_weather",
"args": {"city": "杭州"},
"id": "call_weather_hz",
"type": "tool_call",
}
],
)
return AIMessage(content=f"根据模拟数据,杭州天气为:{tool_msgs[-1].content}。")
single_agent = create_agent(
model=DeterministicAgentModel(handler=single_tool_handler),
tools=[get_weather, calculate],
system_prompt="你是中文 AI 助手,天气数据均为模拟数据。",
)
single_res = single_agent.invoke({"messages": [{"role": "user", "content": "杭州的模拟天气怎么样?"}]})
msgs = single_res["messages"]
msg_types = [m.type for m in msgs]
ai_call_msg = msgs[1]
tool_res_msg = msgs[2]
final_msg = msgs[3]
c2_ok = (
msg_types == ["human", "ai", "tool", "ai"]
and ai_call_msg.content == ""
and len(ai_call_msg.tool_calls) == 1
and ai_call_msg.tool_calls[0]["name"] == "get_weather"
and tool_res_msg.tool_call_id == "call_weather_hz"
and tool_res_msg.name == "get_weather"
and tool_res_msg.content == "晴,25°C,湿度60%"
and final_msg.tool_calls == []
and "25°C" in final_msg.content
)
cases.append(
dict(
name="single_tool_agent_invoke_history",
inputs=dict(question="杭州的模拟天气怎么样?"),
prerequisites="使用 create_agent(model, tools=[get_weather, calculate], system_prompt=...) 执行单工具天气查询。",
action="检查完整消息历史为 [human, ai(tool_calls), tool(tool_call_id), ai(final)],且请求工具的 AIMessage.content 为空串。",
expected=dict(
message_types=["human", "ai", "tool", "ai"],
tool_call_ai_content_empty=True,
tool_call_id_matched=True,
tool_output="晴,25°C,湿度60%",
),
actual=dict(
message_types=msg_types,
tool_call_ai_content_empty=(ai_call_msg.content == ""),
tool_call_id_matched=(tool_res_msg.tool_call_id == ai_call_msg.tool_calls[0]["id"]),
tool_output=tool_res_msg.content,
),
measurements=dict(
final_answer=final_msg.content,
),
passed=c2_ok,
)
)
# 3. Multi-tool loop (two weather calls + calculate) & empty-tools agent direct reply
def multi_tool_handler(messages, kwargs):
tool_msgs = [m for m in messages if m.type == "tool"]
if len(tool_msgs) == 0:
return AIMessage(
content="",
tool_calls=[
{"name": "get_weather", "args": {"city": "杭州"}, "id": "call_hz", "type": "tool_call"},
{"name": "get_weather", "args": {"city": "北京"}, "id": "call_bj", "type": "tool_call"},
],
)
if len(tool_msgs) == 2:
return AIMessage(
content="",
tool_calls=[
{"name": "calculate", "args": {"expression": "25 - 18"}, "id": "call_diff", "type": "tool_call"}
],
)
return AIMessage(content="根据模拟数据,杭州 25°C、北京 18°C,两地气温相差 7°C。")
multi_agent = create_agent(
model=DeterministicAgentModel(handler=multi_tool_handler),
tools=[get_weather, calculate],
system_prompt="先查模拟天气,再调用 calculate 计算温差。",
)
multi_res = multi_agent.invoke(
{"messages": [{"role": "user", "content": "查询杭州和北京模拟天气并计算温差。"}]},
config={"recursion_limit": 15},
)
multi_types = [m.type for m in multi_res["messages"]]
calc_tool_msg = [m for m in multi_res["messages"] if m.type == "tool" and m.name == "calculate"][0]
# Empty tools list agent
direct_agent = create_agent(
model=DeterministicAgentModel(handler=lambda msgs, kw: AIMessage(content="无工具模式直接回复。")),
tools=[],
)
direct_res = direct_agent.invoke({"messages": [{"role": "user", "content": "你好"}]})
c3_ok = (
multi_types == ["human", "ai", "tool", "tool", "ai", "tool", "ai"]
and calc_tool_msg.content == "计算结果:25 - 18 = 7"
and "7°C" in multi_res["messages"][-1].content
and [m.type for m in direct_res["messages"]] == ["human", "ai"]
)
cases.append(
dict(
name="multi_tool_agent_execution_loop",
inputs=dict(cities=["杭州", "北京"], expression="25 - 18"),
prerequisites="在同一轮触发双城市 get_weather 调用,随后在下一轮调用 calculate('25 - 18');并对照 tools=[] 空工具列表行为。",
action="核对多工具调用消息链共 7 条消息、calculate 返回 7,以及空工具列表时不进入工具循环直接返回。",
expected=dict(
multi_msg_count=7,
calc_result="计算结果:25 - 18 = 7",
empty_tools_types=["human", "ai"],
),
actual=dict(
multi_msg_count=len(multi_types),
calc_result=calc_tool_msg.content,
empty_tools_types=[m.type for m in direct_res["messages"]],
),
measurements=dict(
multi_message_types=multi_types,
multi_final_answer=multi_res["messages"][-1].content,
),
passed=c3_ok,
)
)
# 4. Async ainvoke() and stream(stream_mode="updates") node trace
async def run_async():
return await single_agent.ainvoke({"messages": [{"role": "user", "content": "杭州的模拟天气怎么样?"}]})
async_res = asyncio.run(run_async())
stream_nodes = []
for update in single_agent.stream(
{"messages": [{"role": "user", "content": "杭州的模拟天气怎么样?"}]},
stream_mode="updates",
):
stream_nodes.extend(list(update.keys()))
c4_ok = (
"25°C" in async_res["messages"][-1].content
and stream_nodes == ["model", "tools", "model"]
)
cases.append(
dict(
name="async_ainvoke_and_stream_updates",
inputs=dict(stream_mode="updates"),
prerequisites="在同一 Agent 上分别执行 asyncio.run(agent.ainvoke(...)) 与 agent.stream(..., stream_mode='updates')。",
action="核对异步调用得到相同结果,且 updates 流依次产出 model -> tools -> model 三个节点更新。",
expected=dict(
async_has_25c=True,
stream_node_sequence=["model", "tools", "model"],
),
actual=dict(
async_has_25c=("25°C" in async_res["messages"][-1].content),
stream_node_sequence=stream_nodes,
),
measurements=dict(
async_final_answer=async_res["messages"][-1].content,
),
passed=c4_ok,
)
)
# 5. recursion_limit protection against infinite tool loops
def infinite_tool_handler(messages, kwargs):
call_no = sum(1 for m in messages if m.type == "tool") + 1
return AIMessage(
content="",
tool_calls=[
{"name": "get_weather", "args": {"city": "杭州"}, "id": f"call_loop_{call_no}", "type": "tool_call"}
],
)
loop_agent = create_agent(
model=DeterministicAgentModel(handler=infinite_tool_handler),
tools=[get_weather],
)
hit_recursion_error = False
error_type_name = ""
try:
loop_agent.invoke(
{"messages": [{"role": "user", "content": "一直查天气"}]},
config={"recursion_limit": 4},
)
except GraphRecursionError as exc:
hit_recursion_error = True
error_type_name = type(exc).__name__
c5_ok = hit_recursion_error and error_type_name == "GraphRecursionError"
cases.append(
dict(
name="recursion_limit_guard",
inputs=dict(recursion_limit=4),
prerequisites="构造持续请求工具调用的离线模型并配置 config={'recursion_limit': 4}。",
action="确认 LangGraph 在步数超限时抛出 GraphRecursionError 强制终止循环。",
expected=dict(raised_recursion_error=True, error_type="GraphRecursionError"),
actual=dict(raised_recursion_error=hit_recursion_error, error_type=error_type_name),
measurements=dict(limit_used=4),
passed=c5_ok,
)
)
print(
json.dumps(
dict(
version=platform.python_version(),
system=platform.system(),
cases=cases,
),
ensure_ascii=False,
)
)
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
入口文件:projects/langchain-first-agent-lab/explore-first-agent.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-first-agent.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a518.zip