Agent Loop:AI Agent 的核心引擎【nanobot架构分析系列】

Manus AI 原理深度解析第二篇:Modules & Agent Loop 阅读详情

玄同 765

大语言模型 (LLM) 开发工程师 | 中国传媒大学 · 数字媒体技术(智能交互与游戏设计)

优快云 · 个人主页 | GitHub · Follow


关于作者

  • 深耕领域:大语言模型开发 / RAG 知识库 / AI Agent 落地 / 模型微调
  • 技术栈:Python | RAG (LangChain / Dify + Milvus) | FastAPI + Docker
  • 工程能力:专注模型工程化部署、知识库构建与优化,擅长全流程解决方案

「让 AI 交互更智能,让技术落地更高效」
欢迎技术探讨与项目合作,解锁大模型与智能交互的无限可能!


Agent Loop:AI Agent 的核心引擎

Agent Loop 是 nanobot 的心脏,负责消息处理、上下文构建、LLM 交互和工具调用的完整循环。

概述

Agent Loop 是 nanobot 的核心处理引擎,实现了"感知-思考-行动"的完整循环。它从消息总线接收用户消息,构建包含历史、记忆、技能的上下文,调用 LLM 进行推理,执行工具调用,最后将响应返回给用户。本文将深入剖析 Agent Loop 的设计与实现。

问题背景

Agent Loop 的核心挑战

构建一个 AI Agent 的核心循环需要解决以下问题:

挑战描述nanobot 的解决方案
消息处理如何高效处理异步消息消息总线 + 异步队列
上下文构建如何组装完整的对话上下文ContextBuilder 模块化构建
工具调用如何处理多轮工具调用迭代循环 + 结果反馈
会话管理如何维护对话历史SessionManager 持久化
错误处理如何优雅处理异常try-catch + 错误响应

Agent Loop 的设计目标

设计目标

可靠性

可扩展性

可观测性

错误恢复

迭代限制

工具注册

上下文扩展

日志记录

状态追踪

核心架构

AgentLoop 类结构

AgentLoop 是整个系统的核心协调者:

class AgentLoop:
    """
    The agent loop is the core processing engine.
  
    It:
    1. Receives messages from the bus
    2. Builds context with history, memory, skills
    3. Calls the LLM
    4. Executes tool calls
    5. Sends responses back
    """
  
    def __init__(
        self,
        bus: MessageBus,
        provider: LLMProvider,
        workspace: Path,
        model: str | None = None,
        max_iterations: int = 20,
        brave_api_key: str | None = None,
        exec_config: "ExecToolConfig | None" = None,
        cron_service: "CronService | None" = None,
        restrict_to_workspace: bool = False,
        session_manager: SessionManager | None = None,
    ):
        # ... 初始化代码

依赖组件

InboundMessage

MessageBus

AgentLoop

ContextBuilder

LLMProvider

ToolRegistry

SessionManager

SubagentManager

OutboundMessage

消息处理流程

主循环实现

Agent Loop 的核心是一个异步消息处理循环:

async def run(self) -> None:
    """Run the agent loop, processing messages from the bus."""
    self._running = True
    logger.info("Agent loop started")
  
    while self._running:
        try:
            # 等待下一条消息
            msg = await asyncio.wait_for(
                self.bus.consume_inbound(),
                timeout=1.0
            )
          
            # 处理消息
            try:
                response = await self._process_message(msg)
                if response:
                    await self.bus.publish_outbound(response)
            except Exception as e:
                logger.error(f"Error processing message: {e}")
                # 发送错误响应
                await self.bus.publish_outbound(OutboundMessage(
                    channel=msg.channel,
                    chat_id=msg.chat_id,
                    content=f"Sorry, I encountered an error: {str(e)}"
                ))
        except asyncio.TimeoutError:
            continue

消息处理详解

MessageBus

AgentLoop

SessionManager

ContextBuilder

LLMProvider

ToolRegistry

上下文构建

ContextBuilder 的职责

ContextBuilder 负责组装完整的对话上下文:

class ContextBuilder:
    """
    Builds the context (system prompt + messages) for the agent.
  
    Assembles bootstrap files, memory, skills, and conversation history
    into a coherent prompt for the LLM.
    """
  
    BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md", "TOOLS.md", "IDENTITY.md"]

上下文构建流程

Identity

System Prompt

Bootstrap Files

Memory System

Skills System

Messages

Session History

Current Message

System Prompt 构建

def build_system_prompt(self, skill_names: list[str] | None = None) -> str:
    """Build the system prompt from bootstrap files, memory, and skills."""
    parts = []
  
    # 核心身份
    parts.append(self._get_identity())
  
    # Bootstrap 文件
    bootstrap = self._load_bootstrap_files()
    if bootstrap:
        parts.append(bootstrap)
  
    # 记忆上下文
    memory = self.memory.get_memory_context()
    if memory:
        parts.append(f"# Memory\n\n{memory}")
  
    # 技能 - 渐进式加载
    # 1. Always-loaded 技能: 包含完整内容
    always_skills = self.skills.get_always_skills()
    if always_skills:
        always_content = self.skills.load_skills_for_context(always_skills)
        if always_content:
            parts.append(f"# Active Skills\n\n{always_content}")
  
    # 2. 可用技能: 只显示摘要
    skills_summary = self.skills.build_skills_summary()
    if skills_summary:
        parts.append(f"""# Skills

The following skills extend your capabilities. To use a skill, read its SKILL.md file using the read_file tool.
Skills with available="false" need dependencies installed first.

{skills_summary}""")
  
    return "\n\n---\n\n".join(parts)

核心身份信息

def _get_identity(self) -> str:
    """Get the core identity section."""
    now = datetime.now().strftime("%Y-%m-%d %H:%M (%A)")
    tz = _time.strftime("%Z") or "UTC"
    workspace_path = str(self.workspace.expanduser().resolve())
    system = platform.system()
    runtime = f"{'macOS' if system == 'Darwin' else system} {platform.machine()}, Python {platform.python_version()}"
  
    return f"""# nanobot

You are nanobot, a helpful AI assistant. You have access to tools that allow you to:
- Read, write, and edit files
- Execute shell commands
- Search the web and fetch web pages
- Send messages to users on chat channels
- Spawn subagents for complex background tasks

## Current Time
{now} ({tz})

## Runtime
{runtime}

## Workspace
Your workspace is at: {workspace_path}
- Memory files: {workspace_path}/memory/MEMORY.md
- Daily notes: {workspace_path}/memory/YYYY-MM-DD.md
- Custom skills: {workspace_path}/skills/{{skill-name}}/SKILL.md
"""

工具调用循环

迭代处理机制

Agent Loop 使用迭代循环处理多轮工具调用:

async def _process_message(self, msg: InboundMessage) -> OutboundMessage | None:
    """Process a single inbound message."""
  
    # 获取或创建会话
    session = self.sessions.get_or_create(msg.session_key)
  
    # 构建初始消息
    messages = self.context.build_messages(
        history=session.get_history(),
        current_message=msg.content,
        media=msg.media if msg.media else None,
        channel=msg.channel,
        chat_id=msg.chat_id,
    )
  
    # Agent 循环
    iteration = 0
    final_content = None
  
    while iteration < self.max_iterations:
        iteration += 1
      
        # 调用 LLM
        response = await self.provider.chat(
            messages=messages,
            tools=self.tools.get_definitions(),
            model=self.model
        )
      
        # 处理工具调用
        if response.has_tool_calls:
            # 添加助手消息(包含工具调用)
            tool_call_dicts = [
                {
                    "id": tc.id,
                    "type": "function",
                    "function": {
                        "name": tc.name,
                        "arguments": json.dumps(tc.arguments)
                    }
                }
                for tc in response.tool_calls
            ]
            messages = self.context.add_assistant_message(
                messages, response.content, tool_call_dicts,
                reasoning_content=response.reasoning_content,
            )
          
            # 执行工具
            for tool_call in response.tool_calls:
                args_str = json.dumps(tool_call.arguments, ensure_ascii=False)
                logger.info(f"Tool call: {tool_call.name}({args_str[:200]})")
                result = await self.tools.execute(tool_call.name, tool_call.arguments)
                messages = self.context.add_tool_result(
                    messages, tool_call.id, tool_call.name, result
                )
            # 交错思维链: 在下一步行动前反思
            messages.append({"role": "user", "content": "Reflect on the results and decide next steps."})
        else:
            # 无工具调用,完成处理
            final_content = response.content
            break
  
    if final_content is None:
        final_content = "I've completed processing but have no response to give."
  
    # 保存到会话
    session.add_message("user", msg.content)
    session.add_message("assistant", final_content)
    self.sessions.save(session)
  
    return OutboundMessage(
        channel=msg.channel,
        chat_id=msg.chat_id,
        content=final_content,
        metadata=msg.metadata or {},
    )

工具调用流程图

Yes

No

Yes

No

Start

Build Context

Call LLM

Tool Calls?

Add Assistant Msg

Execute Tool

Add Tool Result

Add Reflection

Iteration Limit?

Timeout

Final Response

Save Session

Return Response

会话管理

Session 数据结构

@dataclass
class Session:
    """
    A conversation session.
  
    Stores messages in JSONL format for easy reading and persistence.
    """
  
    key: str  # channel:chat_id
    messages: list[dict[str, Any]] = field(default_factory=list)
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)
    metadata: dict[str, Any] = field(default_factory=dict)
  
    def add_message(self, role: str, content: str, **kwargs: Any) -> None:
        """Add a message to the session."""
        msg = {
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat(),
            **kwargs
        }
        self.messages.append(msg)
        self.updated_at = datetime.now()
  
    def get_history(self, max_messages: int = 50) -> list[dict[str, Any]]:
        """Get message history for LLM context."""
        recent = self.messages[-max_messages:] if len(self.messages) > max_messages else self.messages
        return [{"role": m["role"], "content": m["content"]} for m in recent]

SessionManager 实现

class SessionManager:
    """Manages conversation sessions."""
  
    def __init__(self, workspace: Path):
        self.workspace = workspace
        self.sessions_dir = ensure_dir(Path.home() / ".nanobot" / "sessions")
        self._cache: dict[str, Session] = {}
  
    def get_or_create(self, key: str) -> Session:
        """Get an existing session or create a new one."""
        # 检查缓存
        if key in self._cache:
            return self._cache[key]
      
        # 尝试从磁盘加载
        session = self._load(key)
        if session is None:
            session = Session(key=key)
      
        self._cache[key] = session
        return session

系统消息处理

子代理通知机制

Agent Loop 还处理系统消息,如子代理完成通知:

async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None:
    """
    Process a system message (e.g., subagent announce).
  
    The chat_id field contains "original_channel:original_chat_id" to route
    the response back to the correct destination.
    """
    # 解析来源
    if ":" in msg.chat_id:
        parts = msg.chat_id.split(":", 1)
        origin_channel = parts[0]
        origin_chat_id = parts[1]
    else:
        origin_channel = "cli"
        origin_chat_id = msg.chat_id
  
    # 使用原始会话的上下文
    session_key = f"{origin_channel}:{origin_chat_id}"
    session = self.sessions.get_or_create(session_key)
  
    # ... 处理逻辑与普通消息类似

关键设计决策

1. 最大迭代限制

max_iterations: int = 20

防止无限循环,确保系统稳定性。

2. 交错思维链

messages.append({"role": "user", "content": "Reflect on the results and decide next steps."})

在工具执行后添加反思提示,帮助 LLM 更好地规划下一步行动。

3. 错误恢复

except Exception as e:
    logger.error(f"Error processing message: {e}")
    await self.bus.publish_outbound(OutboundMessage(
        channel=msg.channel,
        chat_id=msg.chat_id,
        content=f"Sorry, I encountered an error: {str(e)}"
    ))

确保错误不会导致系统崩溃,并向用户提供有意义的反馈。

性能优化

1. 会话缓存

self._cache: dict[str, Session] = {}

避免频繁的磁盘 I/O,提高响应速度。

2. 历史消息限制

def get_history(self, max_messages: int = 50) -> list[dict[str, Any]]:

限制上下文长度,避免超出 LLM 的 token 限制。

3. 异步处理

async def run(self) -> None:
    while self._running:
        msg = await asyncio.wait_for(
            self.bus.consume_inbound(),
            timeout=1.0
        )

使用异步 I/O 提高并发处理能力。

总结

Agent Loop 是 nanobot 的核心引擎,其设计体现了以下原则:

设计原则实现方式
模块化ContextBuilder、SessionManager、ToolRegistry 各司其职
可扩展通过注册机制动态添加工具和技能
可靠性迭代限制、错误恢复、会话持久化
可观测完善的日志记录和状态追踪

Agent Loop 的核心是一个简洁但强大的迭代循环,通过上下文构建、LLM 调用和工具执行的组合,实现了完整的 Agent 功能。


Nanobot架构解析:本地AI Agent的实现与优化 AI Agent作为人工智能领域的重要技术范式,通过大语言模型与工具系统的结合实现任务自动化。其核心原理基于ReAct架构,通过循环执行"思考-行动-观察"的流程完成复杂任务。在工程实现层面,本地化部署的AI Agent需要解决系统集成、安全控制、性能优化等关键技术挑战。Nanobot作为典型的本地AI Agent框架,采用模块化设计实现Shell命令执行、Python脚本调用等系统级操作,并通过多层次的记忆管理机制平衡上下文窗口限制。这类技术在个人自动化助手、开发环境增强、智能运维等场景具有广泛应用前景, 阅读详情

相关推荐

从OpenClaw到Nanobot:轻量级AI Agent核心原理与实现解析

AI Agent(智能体)作为连接大语言模型与现实世界的关键技术,其核心在于实现自主推理与工具调用。其底层原理通常围绕一个简洁的“消息循环”架构展开:Agent接收用户指令,通过精心设计的提示工程引导大模型进行思考与规划,解析出结构化的工具调用指令,随后在安全的执行环境中调用注册的工具函数,并将结果反馈至上下文,循环往复直至任务完成。这种设计模式在工程上实现了逻辑的清晰解耦与高效调度,是构建自动化助手、智能客服等应用的基础。本文聚焦于轻量级Agent框架Nanobot,它正是对这一核心原理的极致简化实践,旨

weixin_34248487的博客 465

Agent 三层 API 设计:agentLoop / Agent / AgentHarness 一个比一个高级

await emit({ type: "agent_end", messages: newMessages }); return; } } ### 1.3 为什么这么设计? - **无状态**:所有状态通过 `currentContext` 传入传出,`emit` 负责事件流; - **可插拔**:`config` 里可以换模型、换工具、换 prompt; - **可组合**:`agentLoopContinue` 复用同一套事件流,从任意中间状态继续; - **可观测**:事件流足够细,能还原出完整的 U

宇擎智脑科技的博客 1210

基于STM32的Keil5代码自动补全设置操作指南

掌握Keil5代码自动补全设置技巧,提升STM32开发效率。通过合理配置编辑器选项,实现智能提示与语法补全,让嵌入式编程更流畅,尤其适合使用keil5代码自动补全设置的开发者快速上手。

weixin_32287387的博客 763

【大模型LLM第十六篇】Agent学习之浅谈Agent loop的几种常见范式

主要有以下几种范式tool里面存在stop 相关的 tool,如果输出stop tool则stop,输出final ouput和1相似, 在loop中存在一个固定的类似于意图识别的模块,决定agent是否结束。

AI蜗牛车 2318

4G+GNSS定位模块DX-CT511N-B:AT指令实战与多协议通信指南

本文详细介绍了4G+GNSS定位模块DX-CT511N-B的AT指令实战应用与多协议通信配置。内容涵盖TCP/UDP通信、MQTT协议集成、HTTP服务交互以及GNSS定位功能的深度解析,为开发者提供从基础指令到高级调试的完整指南,助力物联网设备开发。

hope8的博客 289

使用freesurfer和3Dslicer进行脑区分割和电极定点(详细版)

1、安装好matlab和freesurfer2、在目标位置创建文件夹3、开放权限4、将需要计算的nii文件放入文件夹。

zQIANYUN的博客 5629

Agent Loop:大模型 “能做事” 的核心机制

这些大型预训练模型,如GPT-3、BERT、XLNet等,以其强大的语言理解和生成能力,正在改变我们对人工智能的认识。那以下这些PDF籍就是非常不错的学习资源。作为普通人,入局大模型时代需要持续学习和实践,不断提高自己的技能和认知水平,同时也需要有责任感和伦理意识,为人工智能的健康发展贡献力量。如果你想更深入地学习大模型,以下是一些非常有价值的学习资源,这些资源将帮助你从不同角度学习大模型,提升你的实践能力。,模型不仅看到用户最初的问题,还能看到自己调用过哪些工具、拿到了哪些结果,从而完成多步推理与决策。

m0_64363449的博客 914

《21天学通C++》阶段性成果测试题——hstring(手写string类)

总体考察了类的使用,缓冲区考察了指针和数组的使用、增删改查、考察编码思维、考察了类的重载。1.初始化子字符串的起始位置为-1,表示未找到,若buffer或findHstring为空,则返回-1。右边的字符串不为空,则分别获取母串和子串的长度(用循环),然后创建一个固定大小的数组。3.然后循环遍历寻找子串在母串中的起始位置,循环时可以通过两个长度相减,避免循环越界。2.如都不为空,则分别获取双方的字符串长度(用循环),然后。右边的字符串为空,则输出原来的字符串。是否为空,有一方为空则返回另一方。

立志成为炼丹师? 1265

谁才真正拥有 Agent Loop?从 OpenClaw、Claude Code 到 LangGraph、Temporal 的一次工程级拆解

过去一年,“Agent”这个词被说得太轻了。很多系统只要能,就被称为 Agent。真正做过工程落地的人很快会发现:👉这篇文章我们把这个问题一次性讲清楚,并给出一个可以直接用于系统设计的判断标准。

aifs2025的博客 579

RK3399平台开发系列讲解(内核入门篇)1.1、通过sysfs清楚了解设备的系统状况

文章目录1、不敢高声语,恐惊天上人:sysfs目的2、窥一斑而知全豹:sysfs目录介绍3、千丝万缕:sysfs中要素的关系4、数据观星:sysfs中相关结构体 1、不敢高声语,恐惊天上人:sysfs目的 我们想通过sys下面的目录和文件清楚的了解跑Liunx系统的嵌入式设备的系统状况。 2、窥一斑而知全豹:sysfs目录介绍 sysfs把连接在系统上的设备和总线组织成为一个分级的文件,它们可以由用户空间存取,向用户空间导出内核的数据结构以及它们的属性。sysfs的一个目的就是展示设备驱动模型中各组件.

内核笔记 1万+

DBT关键切片重建算法

DBT通过有限角度(通常15°~50°)扫描,获取一系列低剂量投影图,重建出三维断层图像。传统FBP在稀疏角度下会产生严重的“伪影拖尾”和层间干扰。临床诊断中,放射科医生往往只关注几层关键切片(即病灶所在层),其余层仅作参考。

AI的内部世界的博客 89

深入解析 nanobot-agent 核心引擎:AgentLoop 代码详解

AgentLoop 作为消息处理中枢,具备以下关键功能:1)从消息总线接收消息;2)构建提示上下文;3)调用 LLM 推理并执行工具调用;4)管理会话状态和记忆。文章详细介绍了其初始化过程、默认工具注册、MCP 动态扩展机制、主循环设计以及核心消息处理流程。通过精巧的架构设计,AgentLoop 在几百行代码内实现了完整的 Agent 能力,支持会话管理、工具调用、记忆整合等核心功能,展现了高度可扩展性与极简代码量的完美平衡。

weixin_53961451的博客 1896

matlab电子科技大学数学实验期末模拟35道(1)

【代码】matlab电子科技大学数学实验期末模拟35道。

c_wrj_的博客 2044

深入剖析 nanobot:轻量级 AI Agent 框架的架构之道

nanobot 并没有发明新的算法,它的高明之处在于工程实现的克制与优雅极简的接口设计:让接入一个新的 IM 渠道变得异常简单。巧妙的 Prompt 工程:利用虚拟工具解决了结构化输出的难题。务实的记忆管理:通过分层存储,在 Token 消耗和记忆持久性之间找到了平衡。

tho7Dy7M3的博客 699

PD详解—第一章—Type-C连接

Type-C连接 今天大师匈下班比较早,再给大家侃一侃PD,希望大家支持。 PD和Type-c的关系 首先讲一下PD快充的实现步骤,本文主要是Source端(电源),Sink端的差不多也一样,只是策略不同而已。 TypeC连接-->广播电源能力Source capbility(数据交互)->打电压电流->等待其他指令。 所以typec连接是第一步,很多人会从字面意思理解typec连接,这不就是把线给插上去就好了吗? 不知道有没有优秀的同学想到正确答案; 正确答案:typec连接的本质是为

大师匈的博客 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

深入解析AI Agent核心架构:AgentLoop状态机与事件驱动设计

在人工智能领域,智能体(Agent)架构是实现自主决策系统的关键技术。其核心原理基于感知-思考-行动的循环机制,通过状态机管理智能体的行为流程。这一技术价值在于将大语言模型的一次性推理能力嵌入到持续运行的系统中,实现真正的自主交互。在实际应用场景中,AgentLoop通过事件驱动架构实现模块解耦,结合工具执行引擎完成具体任务。本文以开源框架Nanobot为例,深入剖析其AgentLoop实现,涵盖状态管理、工具调度和记忆系统等核心组件,为构建实用AI应用提供工程实践参考。

weixin_33922672的博客 420

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

【Nanobot项目笔记】项目架构

在阅读一个项目之前,我们需要先知道这个项目是做什么的,以及其整体架构。支持多通道接入(Telegram、Discord、Slack、飞书、钉钉、微信等 15+ 平台)支持多 LLM Provider(OpenAI、Anthropic、Azure、GitHub Copilot 等)实现 AI Agent 工具调用循环(Tool Use Loop)具备记忆系统和会话管理UI层:支持多通道,包括飞书、微信、Telegram等;Gateway层:消息网关,负责收发消息;Core Agent。

m0_54394021的博客 458

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

超轻量级AI Agent运行时Nanobot架构解析与实战集成指南

AI Agent作为连接大语言模型(LLM)推理能力与现实世界任务执行的关键技术,其核心在于构建一个稳定、可控的执行环境。其工作原理通常基于事件驱动与任务规划,通过将自然语言指令分解为可执行的步骤序列,并协调工具调用与状态管理来完成复杂目标。这一架构的价值在于将LLM的认知能力转化为可编程、可集成的自动化工作流,从而在智能客服、自动化数据清洗、个人助理等场景中实现效率的显著提升。本文聚焦的Nanobot项目,正是一个为解决上述工程化痛点而设计的超轻量级、可嵌入的AI Agent运行时。它通过极简的层次化设计

weixin_30411819的博客 401

Nanobot 源码深度剖析:一个轻量级 AI Agent 框架的架构设计与实现原理

Nanobot 虽然自称"lightweight",但在架构设计上相当成熟。它展示了如何在有限的代码量内构建一个生产可用消息总线解耦让系统天然支持多渠道扩展ReAct 循环让 LLM 成为灵活的决策引擎两层记忆 + Token 预算管理解决了长对话的持久性问题虚拟工具调用让 LLM 输出结构化且可靠渐进式降级保证系统在各种异常情况下的可用性纵深安全防护应对 prompt injection 和 SSRF 等实际威胁。

ningyanggege的博客 1350

【OpenClaw】通过 Nanobot 源码学习架构---(3)AgentLoop

AgentLoop 的定义和初始化代码如下"""It:"""self,bus: MessageBus, # 消息总线,用于接收/发送消息provider: LLMProvider, # LLM提供者(如OpenAI/本地模型)workspace: Path, # Agent工作目录,用于隔离文件操作model: str | None = None, # 使用的LLM模型名称max_iterations: int = 40, # Agent最大迭代次数(防止无限循环)

罗西的思考 536

通过Nanobot源码学习架构---(3)AgentLoop

AgentLoop 的定义和初始化代码如下"""It:"""self,bus: MessageBus, # 消息总线,用于接收/发送消息provider: LLMProvider, # LLM提供者(如OpenAI/本地模型)workspace: Path, # Agent工作目录,用于隔离文件操作model: str | None = None, # 使用的LLM模型名称max_iterations: int = 40, # Agent最大迭代次数(防止无限循环)

Gp7HH6hrE的博客 179

智能写作助手:基于OpenClaw的Nanobot内容生成

本文介绍了如何在星图GPU平台上自动化部署🐈 nanobot:超轻量级OpenClaw镜像,快速搭建智能写作助手。该镜像能够自动生成高质量的技术文章、营销文案等多种内容,并具备风格转换与SEO优化功能,可大幅提升内容创作效率,是技术博主和营销团队的理想AI助手。

weixin_42588877的博客 284

Nanobot-Eino 上手笔记:从克隆到跑通,以及架构拆解

整个项目的核心在,基于 Eino 框架的构建,但做了大幅度的业务包装。

Alexandrs的博客 722

【OpenClaw】通过Nanobot源码学习架构---(3)AgentLoop

AgentLoop 的定义和初始化代码如下"""It:"""self,bus: MessageBus, # 消息总线,用于接收/发送消息provider: LLMProvider, # LLM提供者(如OpenAI/本地模型)workspace: Path, # Agent工作目录,用于隔离文件操作model: str | None = None, # 使用的LLM模型名称max_iterations: int = 40, # Agent最大迭代次数(防止无限循环)

NHw77QO9t的博客 460

深入解析nanobot的原理与架构

用户输入 → 构建上下文 → LLM 推理 → 决定调用工具 / 直接回答 → 执行工具 → 把结果当作新观察 → 再次推理,直到任务完成。对于想学习 Agent 原理、搭建个人/团队 AI 助手的开发者来说,nanobot 是一个非常好的“教材级项目”。一个功能完整的 AI Agent,不需要几十万行代码,也不需要复杂的“平台化”设计。,按官方文档填写 Telegram / 飞书 / Discord 的凭证。下面是几个比较典型的应用方向,你可以结合自己公司的场景改写。nanobot 的核心是一个典型的。

weixin_53961451的博客 3749
上一篇: nanobot:极简 AI Agent 框架的设计哲学
下一篇: nanobot 工具系统:可扩展的能力框架
玄同765
玄同765 新星创作者: 人工智能技术领域 新星创作者: 人工智能技术领域
博客等级 码龄6年 1万+粉丝 262原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值