手搓Agent

 1 def handle_rolled_agent(model, tools, question: str, max_steps: int = 5) -> AIMessage:
 2     tools_by_name = {t.name: t for t in tools}
 3     messages = [HumanMessage(question)]
 4 
 5     for _step in range(max_steps):
 6         ai_msg = model.invoke(messages)
 7         messages.append(ai_msg)
 8 
 9         if not ai_msg.tool_calls: # 无需工具调用,终止
10             return ai_msg
11 
12         for tc in ai_msg.tool_calls:
13             result = tools_by_name[tc["name"]].invoke(tc["args"]) # 执行工具调用
14             messages.append(ToolMessage( # 工具调用追加到messages
15                 content=str(result),
16                 tool_call_id=tc["id"],
17             ))
18 
19     raise RuntimeError(f"超过{max_steps}步未收敛")

Agent的本质就是一个有限次的循环,在循环中不断调用外部工具

posted @ 2026-11-27 21:17  yixiu868  阅读(3)  评论(0)    收藏  举报