【收藏必备】Python构建AI Agent完整指南:从零开始到实战应用,新手友好

【收藏必备】Python构建AI Agent完整指南:从零开始到实战应用,新手友好

本文详细介绍了如何使用Python从零开始构建一个AI Agent。首先解释了Agent的概念和类型,然后指导读者设置开发环境、定义Model类、创建工具和工具箱,以及实现Agent类。文章提供了完整的代码示例,包括计算器和字符串反转器作为工具,最后展示了如何初始化和运行这个Agent,使其能够根据用户输入选择适当的工具并执行任务。这是一个结构化的指南,为构建能够自动执行任务和做出明智决策的智能交互Agent奠定了基础。

1、什么是Agent?

Agent是指一种能够感知环境、做出决策并采取行动以实现特定目标的自主实体。AI Agent的复杂程度各不相同,既有仅对刺激做出反应的简单反应式智能体,也有能够随时间推移不断学习和适应的高级智能体。常见的智能体类型包括:

  • Reactive Agents: 直接响应环境变化,不具备内部记忆。
  • Model-Based Agents: 利用内部世界模型进行决策的智能体。
  • Goal-Based Agents: 以实现特定目标为基础规划行动。
  • Utility-Based Agents: 基于效用函数评估潜在行动,以实现结果的最大化。

示例包括聊天机器人、推荐系统和自动驾驶汽车,它们各自利用不同类型的Agent,以高效且智能的方式执行任务。

智能体的核心组成部分如下:

  • Models: 智能体的大脑,负责处理输入信息并做出反应。
  • Tools: 智能体可根据用户请求执行的预定义功能。
  • Toolbox: 智能体可使用的工具集合。
  • System Prompt: 指导智能体处理用户输入并选择正确工具的指令集。

2、实 现‍

现在,让我们卷起袖子开始实现吧!

  • 前提条件

本教程的完整代码可在 AI Agents GitHub 代码库中找到。

Github: https://github.com/vsingh9076/AI-Agents/tree/main/build-agent-from-scratch

运行代码前,请确保您的系统满足以下前提条件:

  • Python 环境设置

运行AI Agent需要安装 Python虚拟环境。请按照以下步骤设置虚拟环境:

python -m venv ai_agents_env source ai_agents_env/bin/activate # On Windows: ai_agents_env\Scripts\activate 

安装所需的依赖项,导航至本仓库代码页面,按照requirements.txt安装所需依赖,指令如下:

pip install -r requirements.txt 
  • 在本地设置 Ollama

Ollama 用于高效运行和管理本地大语言模型。请按照以下步骤进行安装和配置:大家可以访问 Ollama 官方网站,下载适用于你操作系统的安装程序。

Ollama官网:https://ollama.com/

按照官网说明进行安装后,大家运行以下命令检查 Ollama 是否已正确安装:

ollama --version 

拉取模型,某些Agent的实现可能需要特定的模型。您可以使用以下命令拉取模型:

ollama pull mistral # Replace 'mistral' with the model needed 

3、定义Model类

本文实现的具体流程如下:

除了 Python,我们还需要安装一些必要的库。在本教程中,我们将使用 requests、json 和 termcolor。此外,我们还将使用 dotenv 来管理环境变量。

pip install requests termcolor python-dotenv 

我们首先需要一个处理用户输入的模型。我们将创建一个 OllamaModel 类,该类与本地 API 交互以生成响应。

下面是一个简单的代码实现:

from termcolor import colored import os from dotenv import load_dotenv load_dotenv() ### Models import requests import json import operator 
class OllamaModel: def __init__(self, model, system_prompt, temperature=0, stop=None): """ Initializes the OllamaModel with the given parameters. Parameters: model (str): The name of the model to use. system_prompt (str): The system prompt to use. temperature (float): The temperature setting for the model. stop (str): The stop token for the model. """ self.model_endpoint = "http://localhost:11434/api/generate" self.temperature = temperature self.model = model self.system_prompt = system_prompt self.headers = {"Content-Type": "application/json"} self.stop = stop def generate_text(self, prompt): """ Generates a response from the Ollama model based on the provided prompt. Parameters: prompt (str): The user query to generate a response for. Returns: dict: The response from the model as a dictionary. """ payload = { "model": self.model, "format": "json", "prompt": prompt, "system": self.system_prompt, "stream": False, "temperature": self.temperature, "stop": self.stop } try: request_response = requests.post( self.model_endpoint, headers=self.headers, data=json.dumps(payload) ) print("REQUEST RESPONSE", request_response) request_response_json = request_response.json() response = request_response_json['response'] response_dict = json.loads(response) print(f"\n\nResponse from Ollama model: {response_dict}") return response_dict except requests.RequestException as e: response = {"error": f"Error in invoking model! {str(e)}"} return response 

该类使用参数model、system_prompt、temperature和stop token进行初始化。其中generate_text 函数向模型 API 发送请求并返回响应。

4、创建Agent所需工具

下一步是创建智能体Agent可以使用的工具。这些工具是执行特定任务的简单 Python 函数。下面是一个基本计算器和一个字符串反转器的示例:

def basic_calculator(input_str): """ Perform a numeric operation on two numbers based on the input string or dictionary. Parameters: input_str (str or dict): Either a JSON string representing a dictionary with keys 'num1', 'num2', and 'operation', or a dictionary directly. Example: '{"num1": 5, "num2": 3, "operation": "add"}' or {"num1": 67869, "num2": 9030393, "operation": "divide"} Returns: str: The formatted result of the operation. Raises: Exception: If an error occurs during the operation (e.g., division by zero). ValueError: If an unsupported operation is requested or input is invalid. """ try: # Handle both dictionary and string inputs if isinstance(input_str, dict): input_dict = input_str else: # Clean and parse the input string input_str_clean = input_str.replace("'", "\"") input_str_clean = input_str_clean.strip().strip("\"") input_dict = json.loads(input_str_clean) # Validate required fields if not all(key in input_dict for key in ['num1', 'num2', 'operation']): return "Error: Input must contain 'num1', 'num2', and 'operation'" num1 = float(input_dict['num1']) # Convert to float to handle decimal numbers num2 = float(input_dict['num2']) operation = input_dict['operation'].lower() # Make case-insensitive except (json.JSONDecodeError, KeyError) as e: return "Invalid input format. Please provide valid numbers and operation." except ValueError as e: return "Error: Please provide valid numerical values." # Define the supported operations with error handling operations = { 'add': operator.add, 'plus': operator.add, # Alternative word for add 'subtract': operator.sub, 'minus': operator.sub, # Alternative word for subtract 'multiply': operator.mul, 'times': operator.mul, # Alternative word for multiply 'divide': operator.truediv, 'floor_divide': operator.floordiv, 'modulus': operator.mod, 'power': operator.pow, 'lt': operator.lt, 'le': operator.le, 'eq': operator.eq, 'ne': operator.ne, 'ge': operator.ge, 'gt': operator.gt } # Check if the operation is supported if operation not in operations: return f"Unsupported operation: '{operation}'. Supported operations are: {', '.join(operations.keys())}" try: # Special handling for division by zero if (operation in ['divide', 'floor_divide', 'modulus']) and num2 == 0: return "Error: Division by zero is not allowed" # Perform the operation result = operations[operation](num1, num2) # Format result based on type if isinstance(result, bool): result_str = "True" if result else "False" elif isinstance(result, float): # Handle floating point precision result_str = f"{result:.6f}".rstrip('0').rstrip('.') else: result_str = str(result) return f"The answer is: {result_str}" except Exception as e: return f"Error during calculation: {str(e)}" def reverse_string(input_string): """ Reverse the given string. Parameters: input_string (str): The string to be reversed. Returns: str: The reversed string. """ # Check if input is a string if not isinstance(input_string, str): return "Error: Input must be a string" # Reverse the string using slicing reversed_string = input_string[::-1] # Format the output result = f"The reversed string is: {reversed_string}" return result 

这些函数旨在根据所提供的输入执行特定任务。basic_calculator 处理算术运算,而 reverse_string 则反转给定的字符串。

5、创建工具箱

工具箱ToolBox类存储了智能体可以使用的所有工具,并提供了每种工具的说明:

class ToolBox: def __init__(self): self.tools_dict = {} def store(self, functions_list): """ Stores the literal name and docstring of each function in the list. Parameters: functions_list (list): List of function objects to store. Returns: dict: Dictionary with function names as keys and their docstrings as values. """ for func in functions_list: self.tools_dict[func.__name__] = func.__doc__ return self.tools_dict def tools(self): """ Returns the dictionary created in store as a text string. Returns: str: Dictionary of stored functions and their docstrings as a text string. """ for name, doc in self.tools_dict.items(): tools_str += f"{name}: \"{doc}\"\n" return tools_str.strip() 

这个类将帮助智能体了解哪些工具可用以及每种工具的具体用途。

6、创建Agent类

Agent需要思考、决定使用哪种工具并执行它。下面是Agent类的代码实现:

系统提示词如下:

agent_system_prompt_template = """ You are an intelligent AI assistant with access to specific tools. Your responses must ALWAYS be in this JSON format: {{ "tool_choice": "name_of_the_tool", "tool_input": "inputs_to_the_tool" }} TOOLS AND WHEN TO USE THEM: 1. basic_calculator: Use for ANY mathematical calculations - Input format: {{"num1": number, "num2": number, "operation": "add/subtract/multiply/divide"}} - Supported operations: add/plus, subtract/minus, multiply/times, divide - Example inputs and outputs: Input: "Calculate 15 plus 7" Output: {{"tool_choice": "basic_calculator", "tool_input": {{"num1": 15, "num2": 7, "operation": "add"}}}} Input: "What is 100 divided by 5?" Output: {{"tool_choice": "basic_calculator", "tool_input": {{"num1": 100, "num2": 5, "operation": "divide"}}}} 2. reverse_string: Use for ANY request involving reversing text - Input format: Just the text to be reversed as a string - ALWAYS use this tool when user mentions "reverse", "backwards", or asks to reverse text - Example inputs and outputs: Input: "Reverse of 'Howwwww'?" Output: {{"tool_choice": "reverse_string", "tool_input": "Howwwww"}} Input: "What is the reverse of Python?" Output: {{"tool_choice": "reverse_string", "tool_input": "Python"}} 3. no tool: Use for general conversation and questions - Example inputs and outputs: Input: "Who are you?" Output: {{"tool_choice": "no tool", "tool_input": "I am an AI assistant that can help you with calculations, reverse text, and answer questions. I can perform mathematical operations and reverse strings. How can I help you today?"}} Input: "How are you?" Output: {{"tool_choice": "no tool", "tool_input": "I'm functioning well, thank you for asking! I'm here to help you with calculations, text reversal, or answer any questions you might have."}} STRICT RULES: 1. For questions about identity, capabilities, or feelings: - ALWAYS use "no tool" - Provide a complete, friendly response - Mention your capabilities 2. For ANY text reversal request: - ALWAYS use "reverse_string" - Extract ONLY the text to be reversed - Remove quotes, "reverse of", and other extra text 3. For ANY math operations: - ALWAYS use "basic_calculator" - Extract the numbers and operation - Convert text numbers to digits Here is a list of your tools along with their descriptions: {tool_descriptions} Remember: Your response must ALWAYS be valid JSON with "tool_choice" and "tool_input" fields. """ 

Agent类的代码实现如下:

class Agent: def __init__(self, tools, model_service, model_name, stop=None): """ Initializes the agent with a list of tools and a model. Parameters: tools (list): List of tool functions. model_service (class): The model service class with a generate_text method. model_name (str): The name of the model to use. """ self.tools = tools self.model_service = model_service self.model_name = model_name self.stop = stop def prepare_tools(self): """ Stores the tools in the toolbox and returns their descriptions. Returns: str: Descriptions of the tools stored in the toolbox. """ toolbox = ToolBox() toolbox.store(self.tools) tool_descriptions = toolbox.tools() return tool_descriptions def think(self, prompt): """ Runs the generate_text method on the model using the system prompt template and tool descriptions. Parameters: prompt (str): The user query to generate a response for. Returns: dict: The response from the model as a dictionary. """ tool_descriptions = self.prepare_tools() agent_system_prompt = agent_system_prompt_template.format(tool_descriptions=tool_descriptions) # Create an instance of the model service with the system prompt if self.model_service == OllamaModel: model_instance = self.model_service( model=self.model_name, system_prompt=agent_system_prompt, temperature=0, stop=self.stop ) else: model_instance = self.model_service( model=self.model_name, system_prompt=agent_system_prompt, temperature=0 ) # Generate and return the response dictionary agent_response_dict = model_instance.generate_text(prompt) return agent_response_dict def work(self, prompt): """ Parses the dictionary returned from think and executes the appropriate tool. Parameters: prompt (str): The user query to generate a response for. Returns: The response from executing the appropriate tool or the tool_input if no matching tool is found. """ agent_response_dict = self.think(prompt) tool_choice = agent_response_dict.get("tool_choice") tool_input = agent_response_dict.get("tool_input") for tool in self.tools: if tool.__name__ == tool_choice: response = tool(tool_input) print(colored(response, 'cyan')) return print(colored(tool_input, 'cyan')) return 

该类有三个主要方法:

  • prepare_tools: 存储并返回工具说明。
  • think: 根据用户提示决定使用哪种工具。
  • work: 执行所选工具并返回结果。

7、运行Agent

最后,让我们将所有内容整合在一起,运行我们的Agent智能体。在脚本的main入口函数内,初始化Agent并开始接受用户输入:

# Example usage if __name__ == "__main__": """ Instructions for using this agent: Example queries you can try: 1. Calculator operations: - "Calculate 15 plus 7" - "What is 100 divided by 5?" - "Multiply 23 and 4" 2. String reversal: - "Reverse the word 'hello world'" - "Can you reverse 'Python Programming'?" 3. General questions (will get direct responses): - "Who are you?" - "What can you help me with?" Ollama Commands (run these in terminal): - Check available models: 'ollama list' - Check running models: 'ps aux | grep ollama' - List model tags: 'curl http://localhost:11434/api/tags' - Pull a new model: 'ollama pull mistral' - Run model server: 'ollama serve' """ tools = [basic_calculator, reverse_string] # Uncomment below to run with OpenAI # model_service = OpenAIModel # model_name = 'gpt-3.5-turbo' # stop = None # Using Ollama with llama2 model model_service = OllamaModel model_name = "llama2" # Can be changed to other models like 'mistral', 'codellama', etc. stop = "<|eot_id|>" agent = Agent(tools=tools, model_service=model_service, model_name=model_name, stop=stop) print("\nWelcome to the AI Agent! Type 'exit' to quit.") print("You can ask me to:") print("1. Perform calculations (e.g., 'Calculate 15 plus 7')") print("2. Reverse strings (e.g., 'Reverse hello world')") print("3. Answer general questions\n") while True: prompt = input("Ask me anything: ") if prompt.lower() == "exit": break agent.work(prompt) 

结论

在这篇文章中,我们一步一步地探索了对Agent是什么的理解。我们建立了虚拟环境,定义了模型,创建了基本工具,并构建了一个结构化工具箱来支持我们的代理功能。最后,我们通过运行Agent,将一切整合在一起。

这种结构化方法为构建能够自动执行任务和做出明智决策的智能交互Agent奠定了坚实的基础。随着AI Agent的不断发展,其应用范围将扩展到各个行业,从而推动效率和创新。

那么,如何系统的去学习大模型LLM?

作为一名从业五年的资深大模型算法工程师,我经常会收到一些评论和私信,我是小白,学习大模型该从哪里入手呢?我自学没有方向怎么办?这个地方我不会啊。如果你也有类似的经历,一定要继续看下去!这些问题啊,也不是三言两语啊就能讲明白的。

所以我综合了大模型的所有知识点,给大家带来一套全网最全最细的大模型零基础教程。在做这套教程之前呢,我就曾放空大脑,以一个大模型小白的角度去重新解析它,采用基础知识和实战项目相结合的教学方式,历时3个月,终于完成了这样的课程,让你真正体会到什么是每一秒都在疯狂输出知识点。

由于篇幅有限,⚡️ 朋友们如果有需要全套 《2025全新制作的大模型全套资料》,扫码获取~

为什么要学习大模型?

我国在A大模型领域面临人才短缺,数量与质量均落后于发达国家。2023年,人才缺口已超百万,凸显培养不足。随着AI技术飞速发展,预计到2025年,这一缺口将急剧扩大至400万,严重制约我国AI产业的创新步伐。加强人才培养,优化教育体系,国际合作并进是破解困局、推动AI发展的关键。

在这里插入图片描述
在这里插入图片描述

👉大模型学习指南+路线汇总👈

我们这套大模型资料呢,会从基础篇、进阶篇和项目实战篇等三大方面来讲解。

在这里插入图片描述


在这里插入图片描述

👉①.基础篇👈

基础篇里面包括了Python快速入门、AI开发环境搭建及提示词工程,带你学习大模型核心原理、prompt使用技巧、Transformer架构和预训练、SFT、RLHF等一些基础概念,用最易懂的方式带你入门大模型。

在这里插入图片描述

👉②.进阶篇👈

接下来是进阶篇,你将掌握RAG、Agent、Langchain、大模型微调和私有化部署,学习如何构建外挂知识库并和自己的企业相结合,学习如何使用langchain框架提高开发效率和代码质量、学习如何选择合适的基座模型并进行数据集的收集预处理以及具体的模型微调等等。

在这里插入图片描述

👉③.实战篇👈

实战篇会手把手带着大家练习企业级的落地项目(已脱敏),比如RAG医疗问答系统、Agent智能电商客服系统、数字人项目实战、教育行业智能助教等等,从而帮助大家更好的应对大模型时代的挑战。

在这里插入图片描述

👉④.福利篇👈

最后呢,会给大家一个小福利,课程视频中的所有素材,有搭建AI开发环境资料包,还有学习计划表,几十上百G素材、电子书和课件等等,只要你能想到的素材,我这里几乎都有。我已经全部上传到ZEEKLOG,朋友们如果需要可以微信扫描下方ZEEKLOG官方认证二维码免费领取【保证100%免费

相信我,这套大模型系统教程将会是全网最齐全 最易懂的小白专用课!!

Read more

【论文阅读】Gaussian Grouping: Segment and Edit Anything in 3D Scenes

【论文阅读】Gaussian Grouping: Segment and Edit Anything in 3D Scenes

摘要 高斯投影(Gaussian Splatting)实现了高质量、实时的三维场景新视点合成。不过,它仅专注于外观和几何建模,缺乏对细粒度的物体级场景理解。为了解决这一问题,我们提出了 Gaussian Grouping,将高斯点扩展为联合重建和分割开放世界三维场景中的任意内容。我们为每个高斯添加了一个紧凑的身份编码(Identity Encoding),使得这些高斯点能够根据其在三维场景中的物体实例或“物体/背景”的成员关系进行分组。并不依赖昂贵的三维标签,我们在可微渲染过程中通过利用 Segment Anything Model (SAM) 的二维掩码预测,以及引入的三维空间一致性正则化,对身份编码进行监督。与隐式的 NeRF 表示相比,我们表明离散且分组的三维高斯点能够在三维中以高视觉质量、细粒度和高效性来重建、分割和编辑任意内容。 引言 本文旨在构建一个 expressive 的三维场景表示,不仅对外观和几何进行建模,还捕捉场景中每个实例和物体的身份信息。我们的方法以最近的三维高斯投影(Gaussian Splatting)为基础,将其从纯粹的三维重建扩展到细粒度的场景

By Ne0inhk
【花雕学编程】Arduino BLDC 之自适应阻抗控制的外骨骼机器人

【花雕学编程】Arduino BLDC 之自适应阻抗控制的外骨骼机器人

基于 Arduino 的无刷直流电机(BLDC)实现自适应阻抗控制的外骨骼机器人,代表了康复工程与智能控制领域的前沿方向。该系统旨在让机器人的运动特性(如刚度、阻尼)不再是固定的,而是能根据人体意图和环境交互力实时调整,从而实现如“肌肉”般柔顺、自然的协同运动。 1、 主要特点 类肌肉的柔顺驱动特性 这是阻抗控制的核心优势,旨在模拟生物系统的运动特性。 力-位置耦合关系: 传统的刚性位置控制容易导致人机交互中的“动力对抗”。自适应阻抗控制将外骨骼关节建模为一个虚拟的弹簧-阻尼系统。这使得外骨骼在受到外部推力时能产生顺应性位移,而非硬性抵抗,极大提升了穿戴舒适度与安全性。 无感交互: 通过 BLDC 配合 FOC(磁场定向控制),可以实现高精度的力矩控制,精确复现阻抗模型所需的输出力,让人感觉像是在自然行走,而非被机器“拖着走”。 基于生理信号的自适应机制 “自适应”是该系统的进阶特征,它解决了固定参数无法适应复杂人体需求的问题。 意图识别: 系统通过传感器(如表面肌电 sEMG 传感器、IMU 惯性测量单元或足底压力传感器)实时采集穿戴者的运动意图和生理状态。

By Ne0inhk
FPGA:高速接口JESD204B以及FPGA实现

FPGA:高速接口JESD204B以及FPGA实现

本文将先介绍JESD204B高速接口的基本概念和特性,然后详细说明如何基于Xilinx Kintex-7系列FPGA实现JESD204B高速接口。 一、JESD204B高速接口介绍 JESD204B是由JEDEC(固态技术协会)制定的一种高速串行通信标准,主要用于数据转换器(如ADC、DAC)与数字处理单元(如FPGA、ASIC)之间的高速数据传输。以下是JESD204B的主要特点和优势: 1. 高速串行通信: * JESD204B采用差分对(SerDes)进行高速串行数据传输,单通道速率可达12.5 Gbps(JESD204C进一步提升至32 Gbps)。 * 通过多通道(lanes)并行传输,支持更高的总带宽,适合高采样率、高分辨率的数据转换器。 2. 主要特性: * 同步性:提供确定性延迟(Deterministic Latency),通过子类(Subclass 0/1/2)支持不同同步需求,Subclass 1广泛用于需要精确同步的应用。 * 多设备同步:支持多个ADC/DAC与FPGA之间的同步,SYSREF信号用于对齐时钟和帧。

By Ne0inhk

【GitHub项目推荐--AI-Goofish-Monitor:闲鱼智能监控机器人完全指南】

简介 AI-Goofish-Monitor 是一个基于 Playwright 和 AI 技术的闲鱼(Goofish)多任务实时监控与智能分析工具。该项目由 dingyufei615 开发,通过先进的浏览器自动化技术和多模态大语言模型,为用户提供智能化的闲鱼商品监控解决方案。该工具不仅具备强大的数据采集能力,还配备了功能完善的 Web 管理界面,让用户能够轻松管理和配置监控任务。 🔗 GitHub地址 : https://github.com/dingyufei615/ai-goofish-monitor ⚡ 核心价值 : AI智能分析 · 多任务监控 · 实时通知 · Web管理界面 技术特色 : * AI驱动 :集成多模态大语言模型(GPT-4o、Gemini等),深度分析商品信息 * Web管理 :完整的可视化界面,无需命令行操作 * 多平台通知 :支持 ntfy.sh、企业微信、Bark 等多种通知方式 * 智能过滤 :基于自然语言的任务创建和AI分析标准生成 * 云原生支持 :提供

By Ne0inhk