什么是大模型Agent?

大模型Agent是基于大规模语言模型(LLM)构建的智能实体,它融合了自主性、交互性、反应性和主动性等多元特质。与单纯的大模型不同,Agent不仅能够理解和生成文本,还能自主决策和执行任务,实现从"计划"、“组织”、"执行"到"学习"的完整闭环。

Agent可被视为"具备自主智能的实体",也被广泛称作智能体。当前的Agent主要分为三种类型:单体Agent、多Agent协作(Multi-Agent)以及与人交互的Agent。

大模型Agent的核心组件

一个完整的大模型Agent通常包含以下核心组件

  1. 感知模块:与外部世界交互的桥梁,负责接收和处理来自环境的各种输入。
  2. 决策模块:Agent的大脑,负责根据感知信息和既定目标制定行动计划。
  3. 执行模块:将决策模块制定的计划付诸实施。
  4. 记忆模块:存储和管理历史交互、上下文信息以及长期知识。
  5. 学习模块:赋予Agent持续学习和自我优化的能力。

大模型Agent的关键技术

构建大模型Agent涉及多项关键技术

  1. 模型微调:在预训练的大语言模型基础上针对特定任务进行微调。
  2. 指令微调:优化指令设计和训练策略,提升模型对指令的理解和执行能力。
  3. 工具调用:集成第三方服务和API,扩展Agent功能范围。
  4. 多智能体协作:实现多个Agent之间的协同工作和信息共享。

代码实现:基于LLM的数学计算Agent(示例:集成计算器工具)

以下是一个基于大模型的数学计算Agent实现代码,它能够理解数学问题并调用计算器工具进行计算:

1、设计调用计算器的prompt,设计如下:让llm判断是否需要调用agent(计算器),并以json格式输出计算器的输入。

 <|im_start|>system
 You are a math assistant with calculator access. Available tools:
 - calculator: evaluates math expressions. Input must be a valid expression like "3*(4+2)".
 Always follow these steps:
 1. Analyze if calculation is needed
 2. If yes, output JSON format: {"action": "calculator", "input": "<expression>"}
 3. If no, reply directly<|im_end|>
 <|im_start|>user
 Calculate (3.14 * 15^2) / 4<|im_end|>
 <|im_start|>assistant

2、编写代码

from transformers import AutoModelForCausalLM, AutoTokenizer
import json
import re

QWEN_QWEN_B_INSTRUCT = r"/home/ma-user/work/x00601234/model/Qwen2-7B-Instruct"


# 1. 定义计算器工具
def calculator(expression: str) -> str:
    """计算数学表达式(示例:'3 + 5 * 2')"""
    try:
        # 安全计算建议:实际生产环境应替换为ast.literal_eval或专用数学库
        result = eval(expression)
        return str(round(result, 4))  # 保留4位小数
    except Exception as e:
        return f"Calculation error: {e}"


# 2. 初始化模型
device = "cuda"
model = AutoModelForCausalLM.from_pretrained(
    QWEN_QWEN_B_INSTRUCT,
    torch_dtype="auto",
    device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(QWEN_QWEN_B_INSTRUCT)

# 3. Agent系统提示词(包含工具描述)
system_prompt = """You are a math assistant with calculator access. Available tools:
- calculator: evaluates math expressions. Input must be a valid expression like "3*(4+2)".

Always follow these steps:
1. Analyze if calculation is needed
2. If yes, output JSON format: {"action": "calculator", "input": "<expression>"}
3. If no, reply directly"""


def run_agent(query: str, max_retry=3) -> str:
    messages = [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": query}
    ]

    for _ in range(max_retry):
        text = tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            add_generation_prompt=True
        )
        inputs = tokenizer([text], return_tensors="pt").to(device)

        outputs = model.generate(
            inputs.input_ids,
            max_new_tokens=200,
            do_sample=True,
            temperature=0.7
        )
        response = tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True)

        # 解析工具调用
        if "{" in response and "}" in response:
            try:
                action = json.loads(re.search(r'\{.*\}', response).group(0))
                if action.get("action") == "calculator":
                    calc_result = calculator(action["input"])
                    messages.append({
                        "role": "system",
                        "content": f"Tool Result: {calc_result}"
                    })
                    continue
            except:
                pass

        # 无工具调用则返回最终答案
        return response.strip()


# 4. 使用示例
if __name__ == "__main__":
    math_question = "Calculate (3.14 * 15^2) / 4"
    print(f"Question: {math_question}")
    print("Answer:", run_agent(math_question))

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐