ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

200行Python实现极简智能体(Agent)核心原理与实战

200行Python实现极简智能体(Agent)核心原理与实战 1. 项目概述200行Python实现极简Agent这个项目旨在用最精简的代码约200行Python实现一个具备基础能力的智能体Agent帮助开发者快速理解智能体的核心工作原理。不同于复杂的商业框架这个实现剥离了所有非必要组件聚焦三个核心能力意图理解、工具调用和结果整合。我选择Python作为实现语言因为它具有丰富的AI生态和简洁的语法特性。在200行代码的约束下我们需要做出一些关键设计取舍使用字典而非类来存储状态节省约30%的代码量直接调用OpenAI API而非封装中间层简化错误处理流程这种极简实现虽然不适合生产环境但能清晰展示智能体的核心工作流程。下面是一个基础调用示例agent create_agent(tools[weather_tool]) response agent.run(北京明天会下雨吗) # 输出: {location: 北京, date: 2024-06-25, forecast: 小雨}2. 智能体核心原理拆解2.1 功能调用Function Calling机制现代智能体的核心能力之一是函数调用其本质是让LLM完成文本到结构化数据的转换。在我们的极简实现中这个流程被拆解为四个步骤工具注册每个工具需要提供名称、描述和参数schemaweather_tool { name: get_weather, description: 查询指定日期的天气情况, parameters: { location: {type: string, description: 城市名称}, date: {type: string, format: YYYY-MM-DD} } }意图识别LLM判断是否需要调用工具# 伪代码展示判断逻辑 def should_call_tool(prompt, tools): messages [ {role: system, content: f可用的工具: {tools}}, {role: user, content: prompt} ] response openai.ChatCompletion.create( modelgpt-3.5-turbo, messagesmessages, temperature0.3 ) return tool_call in response.choices[0].message参数提取LLM从自然语言中提取结构化参数# 关键参数提取示例 params llm_extract_parameters( 上海后天下午的天气, tool_schemaweather_tool ) # 返回: {location: 上海, date: 2024-06-27}结果整合将工具返回的结果转换为自然语言响应提示在实际开发中参数提取是最容易出错的环节。建议添加参数校验逻辑当LLM返回非法参数时可以要求其重新生成。2.2 与ReACT架构的对比我们的极简实现采用了Function Calling模式而非ReACT主要基于以下考量维度Function CallingReACT代码复杂度约120行核心代码需要200行实现完整链条响应速度单次API调用需要多轮交互调试难度结构化日志易于追踪自然语言日志解析困难适用场景明确工具调用的场景需要复杂推理的场景在200行代码的约束下Function Calling模式能更好地保持代码可读性。不过这也意味着我们的智能体缺乏反思Reflection能力——这是后续可以扩展的方向。3. 完整实现解析3.1 基础架构设计整个系统由三个主要组件构成工具管理器维护工具注册表处理工具查找和调用class ToolManager: def __init__(self): self.tools {} def register(self, tool): self.tools[tool[name]] tool def call(self, tool_name, params): tool self.tools.get(tool_name) if not tool: raise ValueError(f未知工具: {tool_name}) return tool[function](**params)LLM交互模块封装与OpenAI API的通信def query_llm(messages, toolsNone, temperature0.3): payload { model: gpt-3.5-turbo, messages: messages, temperature: temperature } if tools: payload[functions] tools response openai.ChatCompletion.create(**payload) return response.choices[0].message智能体核心协调整个工作流程def agent_loop(prompt, tool_manager): # 第一步判断是否需要工具调用 decision decide_tool_usage(prompt, tool_manager.tools.values()) if decision[action] direct_response: return decision[response] # 第二步提取工具参数 params extract_parameters(prompt, decision[tool]) # 第三步执行工具调用 result tool_manager.call(decision[tool][name], params) # 第四步生成最终响应 return generate_final_response(prompt, result)3.2 关键实现技巧工具描述优化通过改进工具描述可以显著提升调用准确率# 较差描述 查询天气 # 优化后描述 获取指定城市在特定日期的天气预报信息包括温度、降水概率和风速等数据。输入应为具体的地理位置和明确的日期。参数提取增强添加示例能提高LLM理解能力def get_weather_schema(): return { name: get_weather, description: ..., parameters: { location: { type: string, description: 城市名称如北京、上海市, examples: [北京, 纽约] }, # 其他参数... } }错误处理机制添加重试逻辑应对LLM输出不稳定def safe_extract_params(prompt, tool_schema, max_retries3): for _ in range(max_retries): try: return extract_parameters(prompt, tool_schema) except InvalidParamsError: continue raise ParamExtractionFailed(参数提取失败)4. 实战应用与扩展4.1 典型应用场景这个极简Agent虽然功能有限但已经可以处理许多实用场景数据查询天气、股票、航班等信息查询内容处理文本摘要、关键词提取、翻译等系统控制智能家居指令转换、自动化任务触发例如我们可以构建一个智能家居控制Agentlight_tool { name: control_light, description: 控制智能灯具的开关和亮度, parameters: { action: {type: string, enum: [on, off, dim]}, brightness: {type: integer, minimum: 0, maximum: 100} }, function: homekit_control # 实际控制函数 } agent create_agent(tools[light_tool]) agent.run(把客厅的灯调暗到50%)4.2 性能优化技巧在资源受限环境下这些技巧可以提升Agent性能提示词压缩精简工具描述但不损失关键信息# 原始描述约50 tokens 获取指定城市在特定日期的天气预报信息... # 优化后约30 tokens 查询城市天气输入地点和日期返回天气数据结果缓存对相同参数的查询进行缓存from functools import lru_cache lru_cache(maxsize100) def get_cached_weather(location, date): return original_weather_api(location, date)批量处理合并多个工具调用请求def batch_process_queries(queries): # 合并相似查询 combined merge_similar_queries(queries) # 批量调用LLM responses batch_llm_requests(combined) # 拆分结果 return split_responses(responses)5. 常见问题与调试技巧5.1 典型问题排查工具未被调用检查工具描述是否清晰验证prompt是否包含足够触发信息测试直接提供工具参数是否能正确调用参数提取错误添加参数示例和枚举值限制在schema中添加参数格式说明实现参数校验和重试机制响应速度慢检查网络延迟评估LLM响应时间考虑实现本地缓存5.2 调试日志示例添加详细的调试日志能快速定位问题def debug_agent_run(prompt): print(f[输入] {prompt}) decision decide_tool_usage(prompt, tools) print(f[决策] {decision}) if decision[action] call_tool: print(f[工具选择] {decision[tool][name]}) params extract_parameters(prompt, decision[tool]) print(f[参数提取] {params}) result call_tool(decision[tool][name], params) print(f[工具结果] {result}) final_response generate_response(prompt, result) print(f[最终响应] {final_response}) return final_response5.3 扩展方向建议记忆能力添加对话历史管理class ConversationMemory: def __init__(self, max_turns5): self.history [] self.max_turns max_turns def add(self, role, content): self.history.append({role: role, content: content}) if len(self.history) self.max_turns * 2: self.history self.history[-self.max_turns * 2:]多工具协作实现工具间的结果传递def multi_tool_agent(prompt): # 第一步获取城市名称 city extract_city(prompt) # 第二步查询天气 weather get_weather(city) # 第三步生成建议 return generate_suggestion(weather)验证机制添加结果可信度检查def validate_response(response): if 不确定 in response or 可能 in response: return False return True这个200行的极简实现已经包含了智能体的核心要素。在实际项目中开发者可以基于这个框架根据具体需求逐步扩展功能。我在实际开发中发现保持核心简洁而通过插件机制扩展功能是维护AI Agent项目的有效策略。
返回列表