🙌 OpenHands: AI-Driven Development

新一代自主软件工程框架源码架构实战指南

源码级别解析 · 源码解析 · 自主智能体 · CodeAct范式
2026-05-04 | 每日技术深度解读

项目概览

OpenHands是什么?
  • formerly OpenDevin, 72K+ GitHub stars
  • MIT开源协议
  • 支持多LLM模型
  • CodeAct范式实现

OpenHands是AI驱动的开发平台,使AI代理能够编写、调试、测试和重构代码

核心特色

独特优势
  • 📱 本地运行 + 云端部署
  • 🔧 可组合的模块化架构
  • 🎯 支持任何LLM模型
  • 🌐 企业级协作功能

相比传统代码助手,OpenHands提供完整的软件工程工作流支持

产品矩阵

四大核心组件
  • 📦 SDK - Python库和REST API
  • 💻 CLI - 命令行工具
  • 🌐 Cloud - 云端托管服务
  • 🖥️ GUI - 本地图形界面

组件化设计满足不同场景需求,从个人开发者到企业团队

技术架构

系统设计理念
  • 🏗️ 模块化组件架构
  • 🔌 工具可扩展性
  • 🌊 基于会话的交互
  • 📊 状态管理和持久化

架构设计强调可扩展性和生产环境可靠性

整体架构图

┌─────────────────────────────────────────────────┐ │ OpenHands │ ├─────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ │ │ SDK │ │ CLI │ │ Cloud │ │ │ │ (Python) │ │ (Terminal) │ │(Hosted) │ │ │ └─────────────┘ └─────────────┘ └───────────┘ │ │ │ │ │ │ │ ┌─────────────────────────────────────────────┐ │ │ │ Agent Server │ │ │ │ ┌─────────┐ ┌─────────┐ ┌─────────────────┐ │ │ │ │ │LLM Core │ │ Tool │ │ Workspace │ │ │ │ │ │Engine │ │Manager │ │ Manager │ │ │ │ │ └─────────┘ └─────────┘ └─────────────────┘ │ │ │ └─────────────────────────────────────────────┘ │ │ │ │ │ │ │ ┌─────────────────────────────────────────────┐ │ │ │ Tools & Skills │ │ │ │ ┌─────────┐ ┌──────────┐ ┌─────────────────┐ │ │ │ │ │ File │ │ Terminal │ │ Custom │ │ │ │ │ │ Editor │ │ Tool │ │ Tools │ │ │ │ │ └─────────┘ └──────────┘ └─────────────────┘ │ │ │ └─────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────┘

OpenHands采用分层架构,支持多种部署模式和工具扩展

SDK核心概念

编程接口
  • 🔧 Agent - 智能体核心
  • 🛠️ Tools - 功能工具集
  • 💬 Conversation - 会话管理
  • 🌐 LLM - 大语言模型接口

SDK提供完整的编程接口,支持构建自定义AI代理

SDK基础用法

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核心引擎
  • 🎯 工具选择和执行
  • 📝 会话状态管理
  • 🔍 错误处理和重试

Agent是智能体的核心,负责LLM交互和工具协调

Agent源码分析

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推理→工具解析→执行→状态更新

工具系统设计

工具架构
  • 🔧 BaseTool - 基础抽象
  • 📁 FileEditor - 文件编辑
  • 💻 Terminal - 终端执行
  • 📋 TaskTracker - 任务追踪

工具系统采用插件化设计,支持自定义工具扩展

自定义工具实现

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范式

行动编码范式
  • 🎯 代码即行动
  • 🔧 可执行操作
  • 📝 文件操作
  • 💻 系统交互

CodeAct将抽象思考转化为具体代码执行行动

工作流设计

任务执行流程
  • 📋 任务分析
  • 🔍 问题分解
  • 🛠️ 工具选择
  • ⚡ 执行监控

结构化的工作流设计确保任务高效完成

工作流状态图

┌─────────────────┐ ┌─────────────────┐ │ 任务接收 │────▶│ 任务分析 │ └─────────────────┘ └─────────────────┘ │ │ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │ 状态检查 │ │ 分解任务 │ └─────────────────┘ └─────────────────┘ │ │ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │ 工具调用 │ │ 执行监控 │ └─────────────────┘ └─────────────────┘ │ │ ▼ ▼ ┌─────────────────┐ ┌─────────────────┐ │ 结果验证 │ │ 状态更新 │ └─────────────────┘ └─────────────────┘

复杂任务的并行处理和状态管理机制

CLI功能详解

命令行接口
  • 🖥️ Terminal TUI模式
  • 🧠 IDE集成模式
  • 🤖 Headless模式
  • 🌐 Web界面模式

CLI支持多种使用模式,适应不同开发场景

CLI安装配置

环境准备
  • 📦 Python 3.12+要求
  • 🔧 uv包管理器
  • 🌐 LLM API配置
  • 🔑 身份验证设置

轻量级安装,支持多种LLM模型

CLI安装命令

# 使用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

多种安装方式支持快速部署

CLI模式详解

四种运行模式
  • 🖥️ Terminal - 交互式开发
  • 🧠 ACP - IDE集成
  • 🤖 Headless - 自动化脚本
  • 🌐 Web - 浏览器界面

不同模式满足从个人开发到企业自动化的全场景需求

CLI命令示例

# 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"

丰富的命令行选项支持各种使用场景

配置管理

系统配置
  • 📂 ~/.openhands/配置目录
  • 🔧 agent_settings.json
  • 💻 cli_config.json
  • 🔗 mcp.json

灵活的配置管理支持个性化设置

MCP集成

模型上下文协议
  • 🔗 Tavily搜索
  • 📚 文档查询
  • 🛒 工具集成
  • 🌐 API扩展

MCP协议扩展了OpenHands的能力边界

MCP服务器配置

# 启用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

代理服务器
  • 🌐 REST API接口
  • 📡 WebSocket通信
  • 🛡️ 安全沙箱
  • 📊 监控和日志

Agent Server提供云端代理执行环境

云端服务

OpenHands Cloud
  • 🌍 多租户支持
  • 👥 协作功能
  • 🔐 RBAC权限
  • 📈 企业版支持

企业级云端服务支持团队协作

企业版特性

企业级功能
  • 🏢 企业许可协议
  • 📋 集成Slack/Jira/Linear
  • 🔐 VPC自托管
  • 🎯 专属技术支持

企业版提供定制化部署和技术支持

工具生态

内置工具集
  • 📁 FileEditor - 文件编辑
  • 💻 Terminal - 终端执行
  • 📋 TaskTracker - 任务追踪
  • 🧠 MCP Skills - 扩展技能

丰富的工具生态支持各种开发任务

FileEditor工具实现

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

安全的文件编辑工具,支持备份和恢复

Terminal工具实现

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

安全的终端执行工具,超时控制和权限管理

任务追踪系统

TaskTracker工具
  • 📋 任务分解
  • ⏱️ 时间追踪
  • 📊 进度监控
  • 🎯 目标管理

智能任务追踪确保项目按时完成

TaskTracker示例

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

结构化的任务管理系统支持复杂项目

技能扩展系统

Public Skills
  • 📦 uv包管理技能
  • 🌐 Deno运行时技能
  • 🔧 自定义技能开发
  • 🌐 技能市场集成

技能系统扩展了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工作流集成

CI/CD自动化
  • 🔀 Pull Request分析
  • 🧪 自动化测试
  • 📦 发布流程
  • 🔗 Actions集成

与GitHub原生集成,自动化软件工程流程

安全机制

安全保障
  • 🛡️ 代码沙箱
  • 🔐 访问控制
  • 📋 操作审计
  • 🔍 敏感数据保护

多层次安全保障确保系统安全可靠

性能优化

系统性能
  • ⚡ 异步执行
  • 📦 缓存机制
  • 🔄 并发控制
  • 📊 资源监控

性能优化确保大规模部署的可靠性

与其他框架对比

框架比较
  • 🤖 vs AutoGen - 架构差异
  • 🔗 vs LangChain - 设计理念
  • 👥 vs CrewAI - 协作模式
  • 🛠️ vs Devin - 功能范围

OpenHands在多个维度具有独特优势

框架特性对比

特性OpenHandsAutoGenLangChainDevin
开源协议MITApache 2.0MIT商业
CodeAct支持
多LLM支持
企业级部署
协作功能

社区生态

开源社区
  • 👥 活跃开发者社区
  • 📚 详细文档
  • 🎯 丰富的示例
  • 🌐 持续更新

强大的社区支持确保项目可持续发展

发展路线图

未来规划
  • 🚀 性能优化
  • 🌐 更多LLM支持
  • 🔗 云服务扩展
  • 🛠️ 工具生态完善

清晰的 roadmap 引领项目发展方向

部署模式

部署选项
  • 💻 本地部署
  • ☁️ 云端托管
  • 🔐 VPC自托管
  • 🏢 企业集成

灵活的部署方案满足不同需求

最佳实践

使用建议
  • 🔧 合理工具选择
  • 📝 清晰任务描述
  • ⏱️ 适当超时设置
  • 🔄 定期状态检查

遵循最佳实践提高使用效果

监控和日志

系统监控
  • 📊 性能指标
  • 🔍 错误追踪
  • ⏱️ 响应时间
  • 📈 资源使用

全面的监控系统确保系统稳定运行

故障排除

常见问题
  • 🔄 连接问题
  • ⏱️ 超时处理
  • 📁 权限错误
  • 🔌 工具冲突

完整的故障排除指南

企业实施

企业部署指南
  • 🏗️ 基础设施规划
  • 🔐 安全合规
  • 👥 团队培训
  • 📊 效果评估

企业级部署的完整解决方案

性能基准

性能测试结果
  • ⚡ SWE-Bench排名
  • 📊 响应时间测试
  • 💾 内存使用
  • 🔄 并发性能

OpenHands在权威基准测试中表现优异

开发指南

贡献指南
  • 🤝 贡献流程
  • 🧪 测试规范
  • 📝 文档要求
  • 🔧 开发环境

欢迎社区参与项目开发

总结

核心优势
  • 🎯 功能完整性
  • 🔧 技术先进性
  • 🌐 生态丰富性
  • 🏢 企业级支持

OpenHands代表了AI驱动开发的未来方向

参考资料

  • 官方文档: https://docs.openhands.dev/sdk
  • GitHub仓库: https://github.com/OpenHands/OpenHands
  • SDK源码: https://github.com/OpenHands/software-agent-sdk
  • CLI工具: https://github.com/OpenHands/OpenHands-CLI

感谢阅读!
访问 https://atcfu.com/ai-articles/openhands/ 回顾本文