Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
471 字
2 分钟
AI Agent

AI Agent#

一、概念#

1. 成熟的大模型要会自己使用工具#

大模型 + 各种工具(读写文件、运行终端命令…)

二. 构建(运行)模式#

1. ReAct#
加载失败

原理: 系统提示词 + 用户问题

① 系统提示词 + 用户问题 构建初始 messages

② 循环以下流程直至获取结果:

请求 xxx 模型 -> 检测 Thought -> 检测模型是否输出 Final Answer -> 检测 Action 并提取信息 -> 将信息添加到 messages 的用户问题

例:

# 工具列表
tools = [read_file, write_to_file, run_terminal_command]
# 返回 agent 对象(工具列表,模型,存放项目位置)
agent = ReActAgent(tools=tools, model="openai/gpt-4o", project_directory=project_dir)
task = input("请输入任务:")
res = agent.run(task)

ReActAgent 类

class ReActAgent:
def __init__(self, tools: List[Callable], model: str, project_directory: str):
self.tools = { func.__name__: func for func in tools }
self.model = model
self.project_directory = project_directory
self.client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=ReActAgent.get_api_key(),
)
def run(self, user_input: str):
# 系统提示词 + 用户问题
messages = [
{"role": "system", "content": self.render_system_prompt(react_system_prompt_template)},
{"role": "user", "content": f"<question>{user_input}</question>"}
]
while True:(重复执行,直到得到结果)
# 请求模型
content = self.call_model(messages)
# 检测 Thought
thought_match = re.search(r"<thought>(.*?)</thought>", content, re.DOTALL)
if thought_match:
thought = thought_match.group(1)
print(f"\n\n💭 Thought: {thought}")
# 检测模型是否输出 Final Answer,如果是,直接返回
if "<final_answer>" in content:
final_answer = re.search(r"<final_answer>(.*?)</final_answer>", content, re.DOTALL)
return final_answer.group(1)
# 检测 Action
action_match = re.search(r"<action>(.*?)</action>", content, re.DOTALL)
if not action_match:
raise RuntimeError("模型未输出 <action>")
action = action_match.group(1)
tool_name, args = self.parse_action(action)
print(f"\n\n🔧 Action: {tool_name}({', '.join(args)})")
# 提取信息
try:
observation = self.tools[tool_name](*args)
except Exception as e:
observation = f"工具执行错误:{str(e)}"
print(f"\n\n🔍 Observation:{observation}")
obs_msg = f"<observation>{observation}</observation>"
messages.append({"role": "user", "content": obs_msg})
2. Plan and Execute(先规划,再执行)#

原理: Plan 模型 + Re-Plan 模型 + 执行 Agent(例如 ReAct 运行模式的 Agent 即可,套娃)

① 系统提示词 + 用户问题 构建初始 messages

② 请求 Plan 模型,得到 执行计划

③ 循环以下流程直至获取结果:

执行计划 -> 请求执行 Agent -> 执行第 x 步,返回执行结果 -> 请求 Re-Plan 模型 -> 返回更新后执行计划

AI Agent
https://www.zangmiyu.com/posts/ai-agent/
作者
zangmiyu
发布于
2026-01-10
许可协议
CC 脏谜语

部分信息可能已经过时