LLM-201: OpenHands与LLM交互链路分析

一、核心交互链路架构

HTTP请求 SSE/WebSocket 前端UI API路由 AgentSession AgentController LLM 工具执行

二、详细流程分解

  1. 前端交互层
    React组件通过React Query发起API请求:
typescript 复制代码
// OpenHands/frontend/src/components/ChatInput.tsx
const { trigger } = useSWRMutation('/api/chat', sendMessage);

async function sendMessage(url: string, { arg }: { arg: string }) {
  return axios.post(url, {
    session_id: sessionId,
    message: arg
  });
}
  1. API路由层
    FastAPI处理请求并创建会话:
python 复制代码
# OpenHands/openhands/server/routes/chat.py
@app.post("/chat")
async def chat_endpoint(request: ChatRequest):
    session = AgentSessionManager.get_session(request.session_id)
    await session.start()
    await session.process_event(MessageAction(content=request.message))
    return EventStreamResponse(session.event_stream)
  1. Agent控制层
    AgentController主循环处理事件:
python 复制代码
# OpenHands/openhands/controller/agent_controller.py
async def _execute_step(self):
    messages = self.conversation_memory.process_events(...)
    llm_response = await self.llm.acompletion(messages)
    actions = self.agent.response_to_actions(llm_response)
    for action in actions:
        await self._handle_action(action)
  1. LLM交互层
    通过LiteLLM集成多模型:
python 复制代码
# OpenHands/openhands/llm/llm.py

async def acompletion(self, messages: list[Message]) -> ModelResponse:
    return await litellm.acompletion(
        model=self.config.model_name,
        messages=convert_to_oa_messages(messages),
        tools=self.tool_schema
    )
  1. 工具执行层
    文件编辑工具示例:
python 复制代码
# OpenHands/openhands/tools/file_edit.py
class FileEditTool(BaseTool):
    async def execute(self, params: dict) -> FileEditObservation:
        with open(params['filepath'], 'w') as f:
            f.write(params['content'])
        return FileEditObservation(
            content=f"Updated {params['filepath']}"
        )

三、典型交互示例

  1. 用户请求

    前端发送:POST /chat {"message": "修改README.md第5行"}

  2. 链路处理

API 创建MessageAction AgentController生成LLM请求 LLM返回函数调用 解析为FileEditAction 执行文件编辑 生成FileEditObservation 通过event_stream返回前端

  1. 结果反馈

前端接收SSE事件:

json 复制代码
{
  "type": "observation",
  "data": {
    "content": "Successfully updated README.md",
    "type": "file_edit"
  }
}

四、关键技术特性

  1. 实时事件流:通过Server-Sent Events实现低延迟更新
  2. 上下文管理:ConversationMemory维护500轮对话上下文
  3. 错误恢复:_react_to_exception方法实现异常自动处理
  4. 多模型支持:LLM配置支持30+商业/开源模型接入

五、参考

  1. OpenHands document
  2. OpenHands on Github
相关推荐
斑点鱼 SpotFish1 分钟前
用Python可视化国庆期间旅游概况与消费趋势
开发语言·python·旅游
小兔崽子去哪了4 分钟前
Python 学习记录
python
埃泽漫笔24 分钟前
RabbitMQ四种交换机详解
python·mq
后端小肥肠34 分钟前
公众号对标账号文章总错过?用 WeWe-RSS+ n8n,对标文章定时到你的邮箱(上篇教程)
人工智能·agent
小猪快跑爱摄影1 小时前
【附代码】Jupyter 多进程调用 seaborn 并保留格式
python·jupyter
技术猴小猴1 小时前
如何使用Python实现LRU缓存
python·spring·缓存
2401_841495641 小时前
【自然语言处理】“bert-base-chinese”的基本用法及实战案例
人工智能·python·自然语言处理·bert·文本预处理·特征提取·训练验证
猫头虎1 小时前
AI_NovelGenerator:自动化长篇小说AI生成工具
运维·人工智能·python·自动化·aigc·gpu算力·ai-native
l1t2 小时前
DeepSeek辅助测试三种ODS电子表格写入程序
python·xlsx·ods·deepseek·xlsb
杜子不疼.2 小时前
【Linux】操作系统上的进程状态及其转换
linux·ai