拓冰建站拓冰建站
首页 / 资讯中心 / 正文

DeepSeek Harness 上手:一切皆插件的 Agent 运行时核心流程详解与代码实战

1. 引言什么是 DeepSeek HarnessDeepSeek Harness 是一个创新的 Agent 运行时框架其核心理念是“一切皆插件”。它将 Agent 的各个组件——包括工具调用、记忆管理、推理决策、状态跟踪等——都设计为可插拔的插件开发者可以通过组合不同的插件来构建高度定制化的智能体工作流。与传统的固定架构 Agent 框架不同Harness 提供了极致的灵活性你可以替换 LLM 后端、自定义工具执行逻辑、调整记忆策略甚至改变整个 Agent 的决策循环而无需修改核心运行时代码。2. 核心概念解析2.1 插件Plugin插件是 Harness 的基本构建块每个插件负责一个特定的功能LLM 插件连接大语言模型如 DeepSeek、GPT、Claude 等工具插件执行具体的功能调用搜索、计算、API 调用等记忆插件管理对话历史、上下文窗口推理插件控制 Agent 的思考过程ReAct、Chain-of-Thought 等输出插件格式化最终响应2.2 运行时Runtime运行时是插件的协调者负责加载和初始化插件管理插件间的依赖关系执行插件生命周期钩子处理插件间的通信和数据流2.3 工作流Workflow工作流定义了 Agent 处理请求的完整流程通常包括输入解析上下文构建工具调用决策执行工具结果整合响应生成3. 环境准备与安装3.1 安装 DeepSeek Harness# 使用 pip 安装 pip install deepseek-harness 或者从源码安装 git clone https://github.com/deepseek-ai/harness.git cd harness pip install -e .3.2 配置 API 密钥# 在环境变量中设置 DeepSeek API 密钥 export DEEPSEEK_API_KEYyour-api-key-here 或者在代码中配置 import os os.environ[DEEPSEEK_API_KEY] your-api-key-here4. 核心流程代码实战4.1 基础 Agent 创建让我们从创建一个最简单的 Agent 开始from harness import Harness from harness.plugins.llm import DeepSeekLLMPlugin from harness.plugins.memory import ConversationMemoryPlugin 1. 创建 Harness 实例 harness Harness() 2. 添加 LLM 插件 llm_plugin DeepSeekLLMPlugin( modeldeepseek-chat, temperature0.7, max_tokens2048 ) harness.add_plugin(llm_plugin) 3. 添加记忆插件 memory_plugin ConversationMemoryPlugin( max_history_messages10 ) harness.add_plugin(memory_plugin) 4. 初始化 Agent agent harness.create_agent() 5. 运行 Agent response agent.run(你好请介绍一下你自己) print(response)4.2 添加工具插件工具插件让 Agent 能够执行具体操作from harness.plugins.tools import ToolPlugin from harness.tools import BaseTool 定义自定义工具 class CalculatorTool(BaseTool): name calculator description 执行数学计算 def execute(self, expression: str) - str: 计算数学表达式 try: # 安全地评估表达式 result eval(expression, {__builtins__: {}}) return f计算结果: {result} except Exception as e: return f计算错误: {e} class WeatherTool(BaseTool): name get_weather description 获取城市天气信息 def execute(self, city: str) - str: 模拟获取天气实际应用中会调用 API # 这里简化实现实际应该调用天气 API weather_data { 北京: 晴25°C, 上海: 多云23°C, 深圳: 阵雨28°C } return weather_data.get(city, f未找到{city}的天气信息) 创建工具插件并添加到 Harness tools_plugin ToolPlugin() tools_plugin.register_tool(CalculatorTool()) tools_plugin.register_tool(WeatherTool()) harness.add_plugin(tools_plugin) 现在 Agent 可以使用工具了 agent harness.create_agent() response agent.run(计算一下 15 * 8 20 等于多少) print(response)4.3 完整工作流示例下面展示一个完整的 Agent 工作流包含所有核心组件from harness import Harness from harness.plugins.llm import DeepSeekLLMPlugin from harness.plugins.memory import ConversationMemoryPlugin from harness.plugins.tools import ToolPlugin from harness.plugins.reasoning import ReActReasoningPlugin from harness.plugins.output import JSONOutputPlugin from harness.tools import BaseTool import json 定义更复杂的工具 class WebSearchTool(BaseTool): name web_search description 在互联网上搜索信息 def execute(self, query: str) - str: 模拟网络搜索实际应调用搜索 API # 模拟搜索结果 results [ {title: DeepSeek Harness 官方文档, snippet: Harness 是一个灵活的 Agent 框架...}, {title: Agent 开发最佳实践, snippet: 如何构建可靠的智能体系统...} ] return json.dumps(results, ensure_asciiFalse) class DataAnalysisTool(BaseTool): name analyze_data description 分析数据集并生成报告 def execute(self, data_description: str) - str: 分析数据并生成摘要 return f已分析数据: {data_description}\n分析结果: 数据质量良好建议进行进一步可视化 创建并配置 Harness def create_advanced_agent(): harness Harness() # 1. LLM 插件 llm DeepSeekLLMPlugin( modeldeepseek-chat, temperature0.3, # 降低温度以获得更稳定的输出 max_tokens4096 ) harness.add_plugin(llm) 2. 记忆插件带总结功能 memory ConversationMemoryPlugin( max_history_messages20, summarize_threshold10 # 每10条消息自动总结 ) harness.add_plugin(memory) 3. 工具插件 tools ToolPlugin() tools.register_tool(WebSearchTool()) tools.register_tool(DataAnalysisTool()) tools.register_tool(CalculatorTool()) harness.add_plugin(tools) 4. 推理插件使用 ReAct 模式 reasoning ReActReasoningPlugin( max_iterations5, # 最多迭代5次 allow_self_correctionTrue ) harness.add_plugin(reasoning) 5. 输出插件JSON 格式 output JSONOutputPlugin( include_traceTrue # 包含执行轨迹 ) harness.add_plugin(output) return harness.create_agent() 使用高级 Agent agent create_advanced_agent() 执行复杂任务 task 请帮我完成以下任务 搜索最新的机器学习框架趋势 分析搜索结果 计算如果采用这些框架预计的开发成本假设每个框架需要2人月 给出最终建议 response agent.run(task) print(原始响应:, response) 解析 JSON 响应 try: result json.loads(response) print(\n解析后的结果:) print(f最终答案: {result.get(answer, )}) print(f使用的工具: {result.get(tools_used, [])}) print(f思考过程: {result.get(reasoning, )}) except: print(响应不是 JSON 格式直接显示:, response)5. 核心流程详解5.1 请求处理流程Harness 处理每个请求的完整流程如下输入接收接收用户查询上下文构建从记忆插件获取历史对话工具选择LLM 决定是否需要使用工具工具执行调用相应的工具插件结果整合将工具结果整合到上下文中响应生成生成最终回答记忆更新将本次交互存入记忆5.2 插件生命周期每个插件在运行时中经历以下生命周期# 伪代码展示插件生命周期 class PluginLifecycle: def __init__(self): self.states [] def on_initialize(self): 插件初始化时调用 self.states.append(initialized) def on_before_run(self, context): Agent 运行前调用 self.states.append(before_run) return context def on_tool_call(self, tool_name, arguments): 工具调用时调用 self.states.append(ftool_called: {tool_name}) def on_after_run(self, result): Agent 运行后调用 self.states.append(after_run) return result def on_error(self, error): 发生错误时调用 self.states.append(ferror: {error})/code/pre 5.3 自定义工作流 你可以完全自定义 Agent 的工作流 from harness.workflows import BaseWorkflow class CustomWorkflow(BaseWorkflow): 自定义工作流先搜索再分析 def execute(self, input_text: str, context: dict) - dict: # 步骤1搜索相关信息 search_result self.call_tool(web_search, {query: input_text}) # 步骤2分析搜索结果 analysis_result self.call_tool(analyze_data, { data_description: f搜索到的信息: {search_result} }) 步骤3生成最终回答 final_prompt f 基于以下信息生成回答 搜索到的信息: {search_result} 分析结果: {analysis_result} 原始问题: {input_text} response self.call_llm(final_prompt) return { search_result: search_result, analysis: analysis_result, final_answer: response } 使用自定义工作流 harness Harness() ... 添加插件 ... harness.set_workflow(CustomWorkflow()) agent harness.create_agent() 6. 高级特性与最佳实践 6.1 插件依赖管理 from harness.plugins import Plugin, requires requires(llm_plugin, memory_plugin) class AdvancedToolPlugin(Plugin): 需要 LLM 和记忆插件的高级工具插件 def init(self): super().init() self.llm None self.memory None def on_initialize(self): 获取依赖的插件实例 self.llm self.get_plugin(llm_plugin) self.memory self.get_plugin(memory_plugin) def execute_complex_task(self, task): 使用依赖的插件 history self.memory.get_history() enhanced_prompt f历史: {history}\n任务: {task} return self.llm.generate(enhanced_prompt)/code/pre 6.2 错误处理与重试 from tenacity import retry, stop_after_attempt, wait_exponential class RobustToolPlugin(ToolPlugin): retry( stopstop_after_attempt(3), waitwait_exponential(multiplier1, min4, max10) ) def execute_with_retry(self, tool_name, arguments): 带重试机制的工具执行 tool self.get_tool(tool_name) if not tool: raise ValueError(f工具 {tool_name} 不存在) try: return tool.execute(**arguments) except Exception as e: self.logger.error(f工具 {tool_name} 执行失败: {e}) raise # 触发重试 def safe_execute(self, tool_name, arguments, fallback_valueNone): 安全的工具执行失败时返回备用值 try: return self.execute_with_retry(tool_name, arguments) except Exception as e: self.logger.warning(f工具 {tool_name} 最终失败使用备用值) return fallback_value/code/pre 6.3 性能监控 import time from dataclasses import dataclass from typing import Dict, List dataclass class PerformanceMetrics: total_requests: int 0 avg_response_time: float 0.0 tool_call_count: Dict[str, int] None def post_init(self): if self.tool_call_count is None: self.tool_call_count {} class MonitoringPlugin(Plugin): 性能监控插件 def init(self): super().init() self.metrics PerformanceMetrics() self.start_time None def on_before_run(self, context): self.start_time time.time() self.metrics.total_requests 1 return context def on_tool_call(self, tool_name, arguments): 记录工具调用次数 self.metrics.tool_call_count[tool_name] self.metrics.tool_call_count.get(tool_name, 0) 1 def on_after_run(self, result): elapsed time.time() - self.start_time 更新平均响应时间指数移动平均 alpha 0.1 self.metrics.avg_response_time alpha * elapsed (1 - alpha) * self.metrics.avg_response_time 将指标添加到结果中 if isinstance(result, dict): result[metrics] { response_time: elapsed, avg_response_time: self.metrics.avg_response_time, tool_calls: self.metrics.tool_call_count } return resultlt;/codegt;lt;/pregt; 实战案例构建数据分析 Agent 让我们构建一个完整的数据分析 Agent from harness import Harness from harness.plugins.llm import DeepSeekLLMPlugin from harness.plugins.tools import ToolPlugin from harness.plugins.reasoning import ChainOfThoughtPlugin import pandas as pd import numpy as np from typing import List, Dict, Any class DataLoaderTool(BaseTool): name load_data description 从文件或URL加载数据 def execute(self, source: str, format: str csv) - str: if format csv: df pd.read_csv(source) elif format excel: df pd.read_excel(source) elif format json: df pd.read_json(source) else: return f不支持的格式: {format} return df.to_string() class DataStatsTool(BaseTool): name calculate_stats description 计算数据的统计信息 def execute(self, data_summary: str, columns: List[str] None) - str: 这里简化处理实际应该解析数据 return f 数据统计信息: 行数: 1000 列数: 15 数值列: 10 分类列: 5 缺失值: 2% class VisualizationTool(BaseTool): name suggest_visualization description 根据数据特征建议可视化方案 def execute(self, data_type: str, analysis_goal: str) - str: suggestions { distribution: [直方图, 箱线图, 密度图], correlation: [散点图,
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门