← 返回文章列表

Agent开发入门第一课

带你从0用python且只用160行写出一个Agent

Agent开发入门第一课

Agent是什么?

  • 我们平时所接触的AI大模型基本上都是属于LLM(Large Language Model)。简单来说这个AI本身只会说话,并不能独立执行文件的增删改查等一系列操作。但是给LLM套上harness(运行时控制层)就可以,harness你可以理解为LLM的身体,那么所谓的Agent则是运行在harness之上的具体用户逻辑。它定义的是目标---"做什么?"
  • 那么本文就以最简单的CodingAgent进行讲解。

Agent开发入门(你必须要知道的概念)

1:Loop(循环)

  • LLM本身并没有记忆,但是你会想说,我的豆包、Deepseek是吧,它都有记忆啊。好,那么我告诉你其实每一次你在和它们对话,这些软件都会把你和AI之前说了什么都重复一遍发回去,那么LLM基于你们的聊天上下文再输出最新的回答并且进入到上下文之中。那么你还会发现一个问题,这种网页对话的AI,你和他的交流过程中会出现的状况通常是

用户:一问 AI:一答

那么其实这里就可以引申出来一个区别了,Agent是可以独立自主地去完成一些事情。那你可能用过ClaudeCode、Codex、hermes、DeepSeekHarness、WorkBuddy等harness,你会发现他们会去调用一些工具。那么其实本质可以这么去看待它:

QQ20261104-170731.png 上图就是Agent循环的图例,那么其实最简单地理解它,你只要代入AI视角就可以了。当你对AI提出了要求,AI有两个选择:

  1. 回答你的问题
  2. 调用工具 当AI认为不用调用工具之后,那就是回答你的问题了。当AI认为当前的情况还不足以回答你的问题,它就得去调用工具。 那么当你理解了循环之后你再去手写Agent就会有一条思路了。

2.上下文与记忆

  • AI的输入长度是有限度的,不是无限的。所以当上文所述"循环"中的内容挤满了该模型所能接受的上下文的长度,就需要对这个上下文进行压缩,那么这个时候需要考虑的就是上下文的压缩策略了。本项目Agent不包含上下文压缩,所以可以先做了解,在完成本项目之后再自行深入研究。
  • 记忆最简单的解决方案是外接一个RAG知识库,需要用到向量模型。本项目未设计,故本文不作叙述。

3.工具

  • Agent完成在涉及到它"训练数据"之外的任务的时候通常会需要调用工具来辅助完成任务,工具需要给请求体加一个schema(一种结构化框架),你可以简单理解为告诉模型,你当前有什么工具,它们能干什么。schema的结构大致如下:
python
  [
    {
      "type": "function",
      "function": {
        "name": "read_file",
        "description": "读取本地文本文件的内容。当用户要求查看、分析、总结某个文件时调用。",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,Windows 用反斜杠,例如 C:\\Users\\Administrator\\note.txt。单次最多返回前 200 行。" }
          },
          "required": ["file_path"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "write_file",
        "description": "覆盖写入整个文件。当用户要求写某个文件时调用",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,例如 C:\\Users\\Administrator\\note.txt。" },
            "text": { "type": "string", "description": "传需要写入的文本" },
          },
          "required": ["file_path","text"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "run_command",
        "description": "执行shell命令。当需要运行验证程序、安装依赖、查找目录等需要执行命令时调用",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "command": { "type": "string", "description": "传入要执行的Shell指令。执行30秒后属超时。" },
          },
          "required": ["command"]
        }
      }
    }
  ]

上面一共是三个工具,分别为读文件、写文件、命令行调用工具。大家可以读一下必填的字段,我都打上了注释的喵。

开始手搓Agent~

  • 下述代码都以Python为例。
  • 不是唯一写法,只要结果对了那就是对的。这是客观题,不是主观题。

1.只会聊天的壳

代码我放在下面了,大家可以对照着注释来读。

  • 首先:sendMessage方法在做什么?它本质上就是接收你和你的Agent的上下文,然后发送到API提供商端点,并且取回Agent回复的一个方法,而其中的loopTextList则是一个列表,里面存着字典,字典里面囊括了一条消息的发送者,内容。
role 谁在说话 这条消息里装什么 在我的代码里哪里写入
system 开发者写给模型的设定 人设与总指令:"你是一个AI助手,乐于帮助用户解决问题" main() 初始化 loopTextList 的第一句,全程只写一次
user 人类用户 用户敲进来的任务,如"创建hello.py并运行它" 接收到人类用户的信息后
assistant 模型 两种身份:① 最终回答(content 有字)② 工具调用意图(tool_calls 有内容,content 通常为空) 模型给出回答的时候
tool 代码(工具运行后的结果) 工具的执行结果。content 必须是字符串,且必须带 tool_call_id toolCalls() 组装,模型每发一次调用,就回一条

并且结合前文,Main函数也就是可以顺带一下就读懂的。

python
import os
import sys
import requests

def sendMessage(loopTextList):
  resp = requests.post(
    "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions",  # 请求端点
    headers={
        "Authorization": "Bearer 替换成你的API_KEY",  # 认证头,前缀固定 Bearer
        "Content-Type": "application/json",  # 请求体格式
    },
    json={  # 请求体
        "model": "glm-5.3-flash",  # 模型名
        "messages": loopTextList,  # 对话消息
    },
  )

  data = resp.json()  # 解析 JSON 响应
  return(data["choices"][0]["message"]["content"])  # 返回结果文本

def main():
  exit = False
  print("蛋老师的简易Agent")
  print('输入"exit"退出')
  loopTextList = [{"role":"system", "content": "你是一个代码助手,很乐于帮助用户解决问题。"}]
  while exit != True:
    print("请输入文本:",end = "")
    message = input()
    if message == "exit":
      exit = True
      break
    loopTextList.append({"role":"user", "content": message})
    result = sendMessage(loopTextList)
    loopTextList.append({"role": "assistant", "content": result})
    print(result)

if __name__ == "__main__":
    main()

2.给模型写工具说明书

  • 到这一步就是在导入schema 给模型 sendMessage 发送的参数里面就多了一个tools字段,就是这个schema字段。
python
import os
import sys
import requests

TOOLS = [
    {
      "type": "function",
      "function": {
        "name": "read_file",
        "description": "读取本地文本文件的内容。当用户要求查看、分析、总结某个文件时调用。",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,Windows 用反斜杠,例如 C:\\Users\\Administrator\\note.txt。单次最多返回前 200 行。" }
          },
          "required": ["file_path"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "write_file",
        "description": "写入本地文本文件内容。当用户要求写某个文件时调用",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,Windows 用反斜杠,例如 C:\\Users\\Administrator\\note.txt。单次最多返回前 200 行。" },
            "text": { "type": "string", "description": "传需要增加或者修改的文本" },
            "line": { "type": "string", "description": "传需要增加或者修改的文本的行号" }
          },
          "required": ["file_path","text","line"]
        }
      }
    }
 ]

def sendMessage( messages):
  resp = requests.post(
    "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions",  # 请求端点
    headers={
        "Authorization": "Bearer 替换成你的API_KEY",  # 认证头,前缀固定 Bearer
        "Content-Type": "application/json",  # 请求体格式
    },
    json={  # 请求体
        "model": "glm-5.3-flash",  # 模型名
        "messages":  messages,  # 对话消息
        "tools": TOOLS,
    },
  )

  data = resp.json()  # 解析 JSON 响应
  return(data["choices"][0]["message"]["content"])  # 返回结果文本

def main():
  exit = False
  print("蛋老师的简易Agent")
  print('输入"exit"退出')
  loopTextList = [{"role":"system", "content": "你是一个AI助手,很乐于帮助用户解决问题。"}]
  while exit != True:
    print("请输入文本:",end = "")
    message = input()
    if message == "exit":
      exit = True
      break
    loopTextList.append({"role":"user", "content": message})
    result = sendMessage(loopTextList)
    loopTextList.append({"role": "assistant", "content": result})
    print(result)

if __name__ == "__main__":
  main()

3.工具本体与错误协议

  • 定义了工具的方法,并且进行了实现。在语言上注意要用try进行包裹,否则报错会出问题,并且最好把报错之后的内容一起发回给模型。(报错 ==> 模型的路径名输错了,模型的工具名输错了)
python
import os
import sys
import requests

TOOLS = [
    {
      "type": "function",
      "function": {
        "name": "read_file",
        "description": "读取本地文本文件的内容。当用户要求查看、分析、总结某个文件时调用。",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,Windows 用反斜杠,例如 C:\\Users\\Administrator\\note.txt。单次最多返回前 200 行。" }
          },
          "required": ["file_path"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "write_file",
        "description": "覆盖写入整个文件。当用户要求写某个文件时调用",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,例如 C:\\Users\\Administrator\\note.txt。" },
            "text": { "type": "string", "description": "传需要写入的文本" },
          },
          "required": ["file_path","text"]
        }
      }
    }
  ]

def read_file(file_path):
  try:
    with open(file_path, "r", encoding="utf-8") as f:
      text = f.read()
  except Exception as e:
    return {"error": f"读取失败: {type(e).__name__}: {e}" }
  lines = text.splitlines()
  lst = lines[:200]
  return "\n".join(lst)

def write_file(file_path, text):
  try:
    with open(file_path, "w", encoding="utf-8") as f:
      f.write(text)
  except Exception as e:
    return {"error": f"文件写入失败: {type(e).__name__}: {e}" }
  return f"文件写入成功,已写入{len(text)}个字符"

def sendMessage( messages):

  resp = requests.post(
    "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions",  # 请求端点
    headers={
        "Authorization": "Bearer 替换成你的API_KEY",  # 认证头,前缀固定 Bearer
        "Content-Type": "application/json",  # 请求体格式
    },
    json={  # 请求体
        "model": "glm-5.3-flash",  # 模型名
        "messages":  messages,  # 对话消息
        "tools": TOOLS,
    },
  )

  data = resp.json()  # 解析 JSON 响应
  return (data)  # 返回结果

def toolCalls():
  ...


def main():
  exit = False
  print("蛋老师的简易Agent")
  print('输入"exit"退出')
  loopTextList = [{"role":"system", "content": "你是一个AI助手,很乐于帮助用户解决问题。"}] # 系统提示词
  while exit != True:
    print("请输入文本:",end = "")
    message = input()
    if message == "exit":
      exit = True
      break
    loopTextList.append({
      "role":"user",
      "content": message
      }) # 用户输入
    data = sendMessage(loopTextList)

    choice = data["choices"][0]
    msg = choice["message"]
    finish = choice.get("finish_reason")

    if msg.get("tool_calls"):
      ...
    # loopTextList.append({"role": "assistant", "content": result})


if __name__ == "__main__":
  main()

4.toolCalls 派发器的组装:

  • 可以看到多了一个toolCalls的方法,这就是派发器。从模型返回的结果,取出需要使用的工具列表,并且遍历这个列表把模型发出来的工具调用都调用一遍,并且每个工具调用时都要绑定模型给出的id,确保工具调用的结果和模型它问的那个问题是对应的。
  • 并且这里对几个工具的输出做了调整,加上了json.dumps()方法,把json转为字符串。
python
import os
import sys
import requests
import json

TOOLS = [
    {
      "type": "function",
      "function": {
        "name": "read_file",
        "description": "读取本地文本文件的内容。当用户要求查看、分析、总结某个文件时调用。",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,Windows 用反斜杠,例如 C:\\Users\\Administrator\\note.txt。单次最多返回前 200 行。" }
          },
          "required": ["file_path"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "write_file",
        "description": "覆盖写入整个文件。当用户要求写某个文件时调用",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,例如 C:\\Users\\Administrator\\note.txt。" },
            "text": { "type": "string", "description": "传需要写入的文本" },
          },
          "required": ["file_path","text"]
        }
      }
    }
  ]

def read_file(file_path):
  try:
    with open(file_path, "r", encoding="utf-8") as f:
      text = f.read()
  except Exception as e:
    return json.dumps({"error": f"读取失败: {type(e).__name__}: {e}" })
  lines = text.splitlines()
  lst = lines[:200]
  return "\n".join(lst)

def write_file(file_path, text):
  try:
    with open(file_path, "w", encoding="utf-8") as f:
      f.write(text)
  except Exception as e:
    return json.dumps({"error": f"文件写入失败: {type(e).__name__}: {e}" })
  return f"文件写入成功,已写入{len(text)}个字符"

def sendMessage( messages):

  resp = requests.post(
    "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions",  # 请求端点
    headers={
        "Authorization": "Bearer 替换成你的API_KEY",  # 认证头,前缀固定 Bearer
        "Content-Type": "application/json",  # 请求体格式
    },
    json={  # 请求体
        "model": "glm-5.3-flash",  # 模型名
        "messages":  messages,  # 对话消息
        "tools": TOOLS,
    },
  )

  data = resp.json()  # 解析 JSON 响应
  return (data)  # 返回结果

def toolCalls(tool_calls):
  tool_messages = []
  for index in range(len(tool_calls)):
    call = tool_calls[index]
    arg = json.loads(call["function"]["arguments"])
    if(call["function"]["name"] == "read_file"):
      tool_messages.append({"role": "tool", "tool_call_id": call["id"], "content": read_file(arg["file_path"])})
    elif(call["function"]["name"] == "write_file"):
      tool_messages.append({"role": "tool", "tool_call_id": call["id"], "content": write_file(arg["file_path"],arg["text"])})
    else:
      tool_messages.append({"role": "tool", "tool_call_id": call["id"], "content": "工具名称调用错误"})
 return tool_messages

def main():
  exit = False
  print("蛋老师的简易Agent")
  print('输入"exit"退出')
  loopTextList = [{"role":"system", "content": "你是一个AI助手,很乐于帮助用户解决问题。"}] # 系统提示词
  while exit != True:
    print("请输入文本:",end = "")
    message = input()
    if message == "exit":
      exit = True
      break
    loopTextList.append({
      "role":"user",
      "content": message
      }) # 用户输入
    data = sendMessage(loopTextList)

    choice = data["choices"][0]
    msg = choice["message"]

    if msg.get("tool_calls"):
      loopTextList.append({
        "role": "assistant",
        "content": msg.get("content"),
        "tool_calls": msg["tool_calls"],
      })
      toolMessages = toolCalls(msg[toolCalls])
      loopTextList += toolMessages
    else:
      reply = msg.get("content") or ""
      print(reply)
      loopTextList.append({
        "role": "assistant",
        "content": reply
      })


if __name__ == "__main__":
  main()

5.isInLoop状态机+最后一个命令行工具的拼装(最终完整版,前面的代码多少在这版会有变化):

  • isInLoop:这个布尔变量确保了模型在自己的循环中。(也就是模型在不决定做出答复的时候可以一直自行调用工具了)
  • run_command:让agent拥有了执行命令的能力
python
import os
import sys
import requests
import json
import subprocess

TOOLS = [
    {
      "type": "function",
      "function": {
        "name": "read_file",
        "description": "读取本地文本文件的内容。当用户要求查看、分析、总结某个文件时调用。",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,Windows 用反斜杠,例如 C:\\Users\\Administrator\\note.txt。单次最多返回前 200 行。" }
          },
          "required": ["file_path"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "write_file",
        "description": "覆盖写入整个文件。当用户要求写某个文件时调用",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "file_path": { "type": "string", "description": "只能传绝对路径,例如 C:\\Users\\Administrator\\note.txt。" },
            "text": { "type": "string", "description": "传需要写入的文本" },
          },
          "required": ["file_path","text"]
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "run_command",
        "description": "执行shell命令。当需要运行验证程序、安装依赖、查找目录等需要执行命令时调用",
        "parameters": {   # 入参的 schema,描述这个函数吃什么
          "type": "object",
          "properties": {   # 逐个参数的定义,每一条 = 一个参数
            "command": { "type": "string", "description": "传入要执行的Shell指令。执行30秒后属超时。" },
          },
          "required": ["command"]
        }
      }
    }
  ]

def read_file(file_path):
  try:
    with open(file_path, "r", encoding="utf-8") as f:
      text = f.read()
  except Exception as e:
    return json.dumps({"error": f"读取失败: {type(e).__name__}: {e}" })
  lines = text.splitlines()
  lst = lines[:200]
  return "\n".join(lst)

def write_file(file_path, text):
  try:
    with open(file_path, "w", encoding="utf-8") as f:
      f.write(text)
  except Exception as e:
    return json.dumps({"error": f"文件写入失败: {type(e).__name__}: {e}" })
  return f"文件写入成功,已写入{len(text)}个字符"

def run_command(command):
    try:
        out = subprocess.run(command, shell=True, capture_output=True, timeout=30, text=True)
    except Exception as e:
        return json.dumps({"error": f"命令执行失败: {type(e).__name__}: {e}" })
    if out.returncode != 0:
        return f"命令执行失败:{out.stderr}"
    else:
        return out.stdout

def sendMessage( messages):

  resp = requests.post(
    "https://open.bigmodel.cn/api/coding/paas/v4/chat/completions",  # 请求端点
    headers={
        "Authorization": "Bearer 替换成你的API_KEY",  # 认证头,前缀固定 Bearer
        "Content-Type": "application/json",  # 请求体格式
    },
    json={  # 请求体
        "model": "glm-5.3-flash",  # 模型名
        "messages":  messages,  # 对话消息
        "tools": TOOLS,
    },
  )

  data = resp.json()  # 解析 JSON 响应
  return (data)  # 返回结果

def toolCalls(tool_calls):
  tool_messages = []
  for index in range(len(tool_calls)):
    call = tool_calls[index]
    arg = json.loads(call["function"]["arguments"])
    if(call["function"]["name"] == "read_file"):
      tool_messages.append({"role": "tool", "tool_call_id": call["id"], "content": read_file(arg["file_path"])})
    elif(call["function"]["name"] == "write_file"):
      tool_messages.append({"role": "tool", "tool_call_id": call["id"], "content": write_file(arg["file_path"],arg["text"])})
    elif(call["function"]["name"] == "run_command"):
      tool_messages.append({"role": "tool", "tool_call_id": call["id"], "content": run_command(arg["command"])})
    else:
      tool_messages.append({"role": "tool", "tool_call_id": call["id"], "content": "工具名称调用错误"})
  return tool_messages


def main():
  isInLoop = False
  exit = False
  print("蛋老师的简易Agent")
  print('输入"exit"退出')
  loopTextList = [{"role":"system", "content": "你是一个AI助手,很乐于帮助用户解决问题。"}] # 系统提示词
  while exit != True:
    if isInLoop == False:
      print("请输入文本:",end = "")
      message = input()
      if message == "exit":
        exit = True
        break
      loopTextList.append({
      "role":"user",
      "content": message
      }) # 用户输入


    data = sendMessage(loopTextList)

    choice = data["choices"][0]
    msg = choice["message"]

    # 模型调工具
    if msg.get("tool_calls"):
      loopTextList.append({
        "role": "assistant",
        "content": msg.get("content"),
        "tool_calls": msg["tool_calls"],
      })
      toolMessages = toolCalls(msg["tool_calls"])
      loopTextList += toolMessages
      isInLoop = True

    # 模型给出回复
    else:
      reply = msg.get("content") or ""
      print(reply)
      loopTextList.append({
        "role": "assistant",
        "content": reply
      })
      isInLoop = False


if __name__ == "__main__":
  main()

结语:

希望本篇文章能让你对Agent有更深入的了解喵那今天就到这啦,拜拜

评论 0

评论加载中

继续阅读

一个提升你对提示词工程能力的方法~工程手记一个提升你对提示词工程能力的方法~SubAgent协作开发的个人思路工程手记SubAgent协作开发的个人思路工程手记REST-API设计思想