学习中心/AI 应用实战/AI Agent 开发入门
中级

AI Agent 开发入门

理解 Agent 架构模式,学习 LangChain、CrewAI 等框架

Inkess40 min

学习笔记

AI Agent 开发入门

什么是 AI Agent

AI Agent 是能自主完成任务的 AI 系统。与简单的对话不同,Agent 可以:

  • 使用工具(调用 API、查询数据库、执行代码)
  • 制定计划(分解任务为多个步骤)
  • 反思与修正(检查结果,重试失败的步骤)

Agent 架构模式

1. ReAct(Reasoning + Acting)

最常见的 Agent 模式,循环执行:

Thought: 我需要查询天气
Action: call_weather_api("Beijing")
Observation: 北京今天晴,15°C
Thought: 我已经有了答案
Answer: 北京今天晴天,气温 15°C

2. Plan-and-Execute

先制定完整计划,再逐步执行:

Plan:
1. 查询用户的订单历史
2. 筛选最近 30 天的订单
3. 计算总金额
4. 返回结果

Execute:
Step 1: [执行] → 结果
Step 2: [执行] → 结果
...

3. Reflection

执行后反思,检查结果是否正确:

Action: 生成代码
Result: [代码]
Reflection: 这段代码有 bug,缺少错误处理
Action: 修复代码
Result: [修复后的代码]
Reflection: 现在看起来正确了

Tool Use 机制

Agent 的核心能力是使用工具。工具定义包含:

{
    "name": "get_weather",
    "description": "Get current weather for a city",
    "parameters": {
        "type": "object",
        "properties": {
            "city": {"type": "string", "description": "City name"}
        },
        "required": ["city"]
    }
}

Agent 根据任务选择工具,生成参数,你的代码执行工具并返回结果。

Agent 框架对比

框架 语言 特点 适合
LangChain Python/TS 生态最大 通用 Agent
LangGraph Python/TS 状态图编排 复杂工作流
CrewAI Python 多 Agent 协作 团队任务
Claude Agent SDK Python/TS 官方 SDK Claude 用户

简单 Agent 示例(Python)

import anthropic

client = anthropic.Anthropic()

tools = [
    {
        "name": "get_weather",
        "description": "Get weather for a city",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string"}
            },
            "required": ["city"]
        }
    }
]

def get_weather(city: str) -> str:
    # 实际应该调用天气 API
    return f"{city} 今天晴天,25°C"

def run_agent(user_message: str):
    messages = [{"role": "user", "content": user_message}]

    while True:
        response = client.messages.create(
            model="claude-sonnet-4-20250514",
            max_tokens=1024,
            tools=tools,
            messages=messages
        )

        if response.stop_reason == "end_turn":
            # Agent 完成任务
            return response.content[0].text

        if response.stop_reason == "tool_use":
            # Agent 要使用工具
            tool_use = next(
                block for block in response.content
                if block.type == "tool_use"
            )

            # 执行工具
            if tool_use.name == "get_weather":
                result = get_weather(tool_use.input["city"])

            # 返回结果给 Agent
            messages.append({"role": "assistant", "content": response.content})
            messages.append({
                "role": "user",
                "content": [{
                    "type": "tool_result",
                    "tool_use_id": tool_use.id,
                    "content": result
                }]
            })

# 使用
print(run_agent("北京今天天气怎么样?"))

延伸阅读