欢迎光临
我们一直在努力

使用 Python 搭建智能体(Agent)完整指南

一、什么是智能体(Agent)

在 AI 领域,“智能体(Agent)”并不是一个抽象的概念,而是一个具备目标导向、自主决策能力,并能与环境交互的系统。

从工程角度,可以把智能体拆解为 4 个核心模块:

  • 感知(Perception)
    • 接收输入(用户问题、环境数据、API 返回)
  • 思考(Reasoning)
    • 使用大模型进行推理、规划
  • 行动(Action)
    • 调用工具(函数、API、数据库)
  • 记忆(Memory)
    • 短期上下文 + 长期知识
  • 👉 简单公式:

    Agent = LLM(大脑) + Tools(工具) + Memory(记忆) + Planning(规划)


    二、为什么用 Python 搭建 Agent

    Python 是目前构建 AI Agent 的首选语言,原因非常现实:

    1. 生态完整

    • AI:OpenAI / Transformers / PyTorch
    • Agent 框架:LangChain / LlamaIndex / AutoGen
    • 数据处理:Pandas / NumPy

    2. 调用模型方便

    from openai import OpenAI
    client = OpenAI()

    3. 易于扩展

    • Web:FastAPI
    • 数据库:SQLite / Redis / Vector DB

    三、Agent 的基本架构设计

    一个标准 Agent 系统结构如下:

    用户输入

    Prompt 构建

    LLM 推理(思考)

    是否调用工具?
    ↓ ↓
    否 是
    ↓ ↓
    直接回答 执行工具

    返回结果

    再次推理

    输出


    四、从零开始:手写一个最小 Agent

    1. 安装依赖

    pip install openai


    2. 基础 LLM 调用

    from openai import OpenAI

    client = OpenAI(api_key="your_api_key")

    def ask_llm(prompt):
    response = client.responses.create(
    model="gpt-5.3",
    input=prompt
    )
    return response.output[0].content[0].text


    3. 加入“工具能力”

    定义一个工具(例如计算器):

    def calculator(expression):
    try:
    return eval(expression)
    except:
    return "计算错误"


    4. 让模型决定是否调用工具(核心)

    def agent(user_input):
    prompt = f"""
    你是一个智能助手。

    如果问题需要计算,请输出:
    CALL_TOOL: calculator: 表达式

    否则直接回答。

    问题:{user_input}
    """

    result = ask_llm(prompt)

    if "CALL_TOOL" in result:
    tool_input = result.split(":")[-1].strip()
    tool_result = calculator(tool_input)

    final_prompt = f"""
    工具返回结果:{tool_result}
    请给出最终答案
    """
    return ask_llm(final_prompt)

    return result


    5. 测试

    print(agent("123 * 456 等于多少"))

    👉 这就是一个最基础的 Agent。


    五、进阶:使用函数调用(Function Calling)

    现代 Agent 不再用字符串解析,而是用结构化调用。

    示例:

    tools = [
    {
    "type": "function",
    "function": {
    "name": "calculator",
    "description": "计算数学表达式",
    "parameters": {
    "type": "object",
    "properties": {
    "expression": {
    "type": "string"
    }
    },
    "required": ["expression"]
    }
    }
    }
    ]

    调用:

    response = client.responses.create(
    model="gpt-5.3",
    tools=tools,
    input="帮我算 12 * 99"
    )


    六、加入记忆系统(Memory)

    1. 短期记忆(上下文)

    history = []

    def chat(user_input):
    history.append({"role": "user", "content": user_input})

    response = client.responses.create(
    model="gpt-5.3",
    input=history
    )

    answer = response.output[0].content[0].text
    history.append({"role": "assistant", "content": answer})

    return answer


    2. 长期记忆(向量数据库)

    可以使用:

    • FAISS
    • Chroma
    • Milvus

    示例(简化版):

    memory_db = []

    def save_memory(text):
    memory_db.append(text)

    def retrieve_memory(query):
    return memory_db[:3]


    七、加入规划能力(Planning)

    智能体的关键升级:从“回答问题” → “解决任务”

    示例:任务拆解

    def planner(task):
    prompt = f"""
    请把任务拆分成步骤:
    {task}
    """
    return ask_llm(prompt)


    示例输出:

    1. 搜索信息
    2. 整理数据
    3. 输出总结


    八、多工具 Agent(真实生产形态)

    tools = {
    "calculator": calculator,
    "search": lambda x: f"搜索结果: {x}"
    }

    调度逻辑:

    def execute_tool(name, arg):
    return tools[name](arg)


    九、使用框架(推荐)

    1. LangChain(最常用)

    pip install langchain

    示例:

    from langchain.agents import initialize_agent
    from langchain.tools import Tool

    tools = [
    Tool(
    name="Calculator",
    func=calculator,
    description="计算数学问题"
    )
    ]

    agent = initialize_agent(
    tools,
    llm,
    agent="zero-shot-react-description"
    )


    2. AutoGen(多智能体)

    适合复杂任务:

    from autogen import AssistantAgent

    👉 可以实现:

    • AI 自己写代码
    • AI 多角色协作

    十、完整 Agent 架构(工业级)

    一个成熟系统通常包含:

    1. 输入层

    • API / Web / Chat

    2. Agent 核心

    • LLM
    • Tool Router
    • Planner

    3. 工具层

    • 搜索
    • 数据库
    • 文件系统

    4. 存储层

    • 向量数据库
    • 日志

    十一、优化方向(关键)

    1. Prompt Engineering

    • Few-shot
    • Chain-of-Thought
    • ReAct

    2. RAG(检索增强)

    问题 → 检索 → 拼接上下文 → LLM


    3. 缓存(Context Caching)

    减少 token 消耗。


    4. 多 Agent 协作

    角色划分:

    • Planner
    • Executor
    • Reviewer

    十二、实际应用场景

    1. AI 客服

    • 自动回答 + 查询订单

    2. 数据分析助手

    • 自动写 SQL

    3. 自动化运维

    • 执行脚本

    4. AI 内容生产

    • 写文章、视频脚本

    十三、常见坑

    1. 幻觉问题

    👉 解决:RAG


    2. 工具调用错误

    👉 解决:函数调用 + schema


    3. 成本过高

    👉 解决:

    • 缓存
    • 限制上下文

    4. 延迟高

    👉 解决:

    • 流式输出
    • 并行调用

    十四、总结

    用 Python 搭建智能体,本质上是把 AI 从“聊天工具”升级为“执行系统”。

    核心路径:

    基础调用 → 工具调用 → 记忆 → 规划 → 多 Agent

    如果你要一句话总结:

    👉 Agent = 会思考 + 会用工具 + 会记住 + 会规划 的 AI 系统


    十五、下一步建议(重点)

    如果你要做更高级的系统,可以继续深入:

  • RAG 架构设计
  • Agent Workflow(工作流编排)
  • 多模态 Agent(图像/视频)
  • AI 自动化(AutoGPT / CrewAI)
  • 赞(0)
    未经允许不得转载:171主机测评 » 使用 Python 搭建智能体(Agent)完整指南
    分享到: 更多 (0)

    评论 抢沙发

    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址