源码级别解析 · 源码解析 · 自主智能体 · CodeAct范式
2026-05-04 | 每日技术深度解读
OpenHands是AI驱动的开发平台,使AI代理能够编写、调试、测试和重构代码
相比传统代码助手,OpenHands提供完整的软件工程工作流支持
组件化设计满足不同场景需求,从个人开发者到企业团队
架构设计强调可扩展性和生产环境可靠性
OpenHands采用分层架构,支持多种部署模式和工具扩展
SDK提供完整的编程接口,支持构建自定义AI代理
import os
from openhands.sdk import LLM, Agent, Conversation, Tool
from openhands.tools.file_editor import FileEditorTool
from openhands.tools.task_tracker import TaskTrackerTool
from openhands.tools.terminal import TerminalTool
# 初始化LLM
llm = LLM(
model="anthropic/claude-sonnet-4-5-20250929",
api_key=os.getenv("LLM_API_KEY"),
)
# 创建代理
agent = Agent(
llm=llm,
tools=[
Tool(name=TerminalTool.name),
Tool(name=FileEditorTool.name),
Tool(name=TaskTrackerTool.name),
],
)
# 启动会话
cwd = os.getcwd()
conversation = Conversation(agent=agent, workspace=cwd)
# 执行任务
conversation.send_message("Write 3 facts about the current project into FACTS.txt.")
conversation.run()
print("All done!")
简单的Hello World示例展示OpenHands SDK的基本用法
Agent是智能体的核心,负责LLM交互和工具协调
class Agent:
"""Core agent implementation for OpenHands"""
def __init__(self, llm: LLM, tools: List[Tool]):
self.llm = llm
self.tools = tools
self.tool_registry = ToolRegistry(tools)
self.conversation_state = ConversationState()
def process_message(self, message: str) -> Action:
"""Process user message and return action"""
# 1. 构建上下文
context = self._build_context(message)
# 2. LLM推理
response = self.llm.generate(context)
# 3. 解析工具调用
action = self._parse_tool_call(response)
# 4. 工具执行
result = self._execute_tool(action)
# 5. 更新状态
self._update_state(action, result)
return action
Agent核心处理流程:上下文构建→LLM推理→工具解析→执行→状态更新
工具系统采用插件化设计,支持自定义工具扩展
class CustomTool(BaseTool):
"""自定义工具实现示例"""
name = "custom_tool"
description = "A custom tool for specific operations"
def __init__(self):
super().__init__()
self.initialize()
def initialize(self):
"""工具初始化"""
# 初始化资源
pass
def run(self, arguments: dict) -> str:
"""工具执行逻辑"""
try:
result = self._execute(arguments)
return self._format_result(result)
except Exception as e:
return self._handle_error(e)
def _execute(self, args: dict):
"""具体执行逻辑"""
# 实现具体功能
pass
自定义工具继承BaseTool,实现标准接口
会话系统支持复杂的多轮对话和任务管理
class Conversation:
"""会话状态管理"""
def __init__(self, agent: Agent, workspace: str):
self.agent = agent
self.workspace = workspace
self.history = []
self.current_state = ConversationState.INIT
self.task_stack = []
def send_message(self, message: str):
"""发送消息并处理响应"""
# 添加到历史
self.history.append({
"role": "user",
"content": message,
"timestamp": datetime.now()
})
# 调用代理
response = self.agent.process_message(message)
# 添加响应
self.history.append({
"role": "assistant",
"content": response.content,
"timestamp": datetime.now()
})
return response
会话管理跟踪对话历史,维护状态上下文
CodeAct将抽象思考转化为具体代码执行行动
结构化的工作流设计确保任务高效完成
复杂任务的并行处理和状态管理机制
CLI支持多种使用模式,适应不同开发场景
轻量级安装,支持多种LLM模型
# 使用uv安装
uv tool install openhands --python 3.12
# 使用二进制安装
curl -fsSL https://install.openhands.dev/install.sh | sh
# 配置LLM环境变量
export LLM_API_KEY="your-api-key"
export LLM_MODEL="anthropic/claude-sonnet-4-5-20250929"
export LLM_BASE_URL="https://api.anthropic.com"
# 启动CLI
openhands
多种安装方式支持快速部署
不同模式满足从个人开发到企业自动化的全场景需求
# Terminal模式 - 交互式开发
openhands
# IDE集成模式
openhands acp
# Headless模式 - 自动化
openhands --headless -t "Write unit tests for auth.py"
openhands --headless --json -t "Create a Flask app"
# 恢复会话
openhands --resume --last
# 云端执行
openhands login
openhands cloud -t "Fix the login bug"
丰富的命令行选项支持各种使用场景
灵活的配置管理支持个性化设置
MCP协议扩展了OpenHands的能力边界
# 启用MCP服务器
openhands mcp enable
# 添加Tavily搜索服务器
openhands mcp add tavily --transport stdio \
npx -- -y mcp-remote "https://mcp.tavily.com/mcp/?tavilyApiKey=<your-api-key>"
# 管理服务器
openhands mcp list
openhands mcp disable tavily
通过MCP协议集成外部服务和工具
Agent Server提供云端代理执行环境
企业级云端服务支持团队协作
企业版提供定制化部署和技术支持
丰富的工具生态支持各种开发任务
class FileEditorTool(BaseTool):
"""文件编辑工具实现"""
def __init__(self):
super().__init__()
self.backup_dir = "/tmp/openhands_backups"
os.makedirs(self.backup_dir, exist_ok=True)
def read_file(self, filepath: str) -> str:
"""读取文件内容"""
try:
with open(filepath, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
return f"Error reading file: {e}"
def write_file(self, filepath: str, content: str) -> bool:
"""写入文件内容"""
try:
# 创建备份
backup_path = os.path.join(self.backup_dir, f"{os.path.basename(filepath)}.bak")
if os.path.exists(filepath):
shutil.copy2(filepath, backup_path)
# 写入新内容
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
return True
except Exception as e:
return False
安全的文件编辑工具,支持备份和恢复
class TerminalTool(BaseTool):
"""终端执行工具"""
def __init__(self, timeout: int = 30):
super().__init__()
self.timeout = timeout
self.pwd = os.getcwd()
def run_command(self, command: str) -> dict:
"""执行终端命令"""
try:
result = subprocess.run(
command,
shell=True,
cwd=self.pwd,
capture_output=True,
text=True,
timeout=self.timeout
)
return {
"success": result.returncode == 0,
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode
}
except subprocess.TimeoutExpired:
return {"success": False, "error": "Command timeout"}
def change_directory(self, path: str) -> bool:
"""切换工作目录"""
try:
os.chdir(path)
self.pwd = os.getcwd()
return True
except OSError:
return False
安全的终端执行工具,超时控制和权限管理
智能任务追踪确保项目按时完成
class TaskTrackerTool(BaseTool):
"""任务追踪工具"""
def __init__(self):
super().__init__()
self.tasks = []
self.current_task = None
def create_task(self, description: str, priority: str = "medium"):
"""创建新任务"""
task = {
"id": len(self.tasks) + 1,
"description": description,
"priority": priority,
"status": "pending",
"created_at": datetime.now(),
"subtasks": []
}
self.tasks.append(task)
return task["id"]
def update_task(self, task_id: int, status: str, result: str = None):
"""更新任务状态"""
for task in self.tasks:
if task["id"] == task_id:
task["status"] = status
if result:
task["result"] = result
break
结构化的任务管理系统支持复杂项目
技能系统扩展了Agent的能力范围
from openhands.sdk import Agent, Conversation
from openhands.context import AgentContext
# 启用公共技能
context = AgentContext(
load_public_skills=True,
workspace="/path/to/project"
)
# 创建代理
agent = Agent(
llm=llm,
tools=[],
context=context
)
# 自动检测项目类型
if os.path.exists("uv.lock"):
# 自动使用uv技能
agent.enable_skill("uv")
elif os.path.exists("deno.json"):
# 自动使用deno技能
agent.enable_skill("deno")
智能技能检测和自动启用
真实项目场景中的应用示例
与GitHub原生集成,自动化软件工程流程
多层次安全保障确保系统安全可靠
性能优化确保大规模部署的可靠性
OpenHands在多个维度具有独特优势
| 特性 | OpenHands | AutoGen | LangChain | Devin |
|---|---|---|---|---|
| 开源协议 | MIT | Apache 2.0 | MIT | 商业 |
| CodeAct支持 | ✅ | ❌ | ❌ | ✅ |
| 多LLM支持 | ✅ | ✅ | ✅ | ❌ |
| 企业级部署 | ✅ | ✅ | ✅ | ✅ |
| 协作功能 | ✅ | ❌ | ✅ | ❌ |
强大的社区支持确保项目可持续发展
清晰的 roadmap 引领项目发展方向
灵活的部署方案满足不同需求
遵循最佳实践提高使用效果
全面的监控系统确保系统稳定运行
完整的故障排除指南
企业级部署的完整解决方案
OpenHands在权威基准测试中表现优异
欢迎社区参与项目开发
OpenHands代表了AI驱动开发的未来方向
感谢阅读!
访问 https://atcfu.com/ai-articles/openhands/ 回顾本文