跳到主要内容
NanoBot - 轻量级 AI Agent 框架与智能体构建工具 | 极客日志
Python AI 算法
NanoBot - 轻量级 AI Agent 框架与智能体构建工具 NanoBot 是由香港大学数据科学实验室开发的轻量级 AI Agent 框架。它旨在提供简洁的 API 和灵活的架构,帮助开发者快速构建和部署 AI 智能体,避免复杂配置。核心功能包括 Agent 构建、工具集成、规划执行、记忆管理及多 LLM 支持。相比 LangChain 等重型框架,NanoBot 更适合快速原型开发和小型项目,具有代码精简、易于理解和扩展的特点。
狂少 发布于 2026/4/6 更新于 2026/5/22 26 浏览引言
'大道至简——最强大的工具往往拥有最简单的接口。'
NanoBot (GitHub: HKUDS/nanobot )是一个轻量级、极简的 AI Agent 框架,由香港大学数据科学实验室(HKUDS)开发。在 AI Agent 框架领域,LangChain、CrewAI 等框架功能强大但学习曲线陡峭,对于快速原型开发和小型项目来说可能过于复杂。NanoBot 专注于提供简洁的 API、灵活的架构和强大的扩展能力,让开发者能够快速构建和部署 AI 智能体,而无需陷入复杂的配置和抽象层。
核心优势
轻量级设计 :极简的代码库,易于理解和定制
快速上手 :简洁的 API,几分钟内即可构建第一个 Agent
灵活架构 :模块化设计,按需扩展功能
专注核心 :专注于 Agent 的核心能力,避免过度设计
易于集成 :可以轻松集成到现有项目中
扩展性强 :支持自定义工具、记忆、规划器等组件
前置知识
对 AI Agent 概念有基本了解
熟悉 Python 编程
了解 LLM(大语言模型)的基本使用
对函数调用(Function Calling)有基本认识(可选)
项目简介
NanoBot 旨在提供一个简洁、高效、易于使用的框架,让开发者能够快速构建和部署 AI 智能体,而无需处理复杂的配置和抽象层。
面向的用户群体 :
需要快速构建 AI Agent 的开发者
进行 AI Agent 研究和实验的研究人员
希望学习 Agent 框架设计的学生和开发者
需要轻量级 Agent 解决方案的小型项目
项目特点 :
轻量级 :代码库精简,核心功能清晰
易用性 :简洁的 API,快速上手
灵活性 :模块化设计,易于扩展
学术性 :来自知名大学实验室,有扎实的理论基础
核心功能
主要作用
Agent 构建 :快速创建和配置 AI Agent
工具集成 :支持自定义工具和函数调用
规划与执行 :Agent 的规划、执行和反思机制
记忆管理 :短期和长期记忆支持
多 Agent 协作 :支持多个 Agent 协同工作
LLM 集成 :支持多种 LLM 提供商
流式响应 :支持流式输出和实时交互
使用场景
快速原型开发 :快速验证 Agent 想法,构建 MVP
研究和教学 :AI Agent 相关研究,教学和演示
小型项目 :个人项目和小型应用,不需要复杂框架
学习和实验 :学习 Agent 框架设计,理解工作原理
工具集成 :将 Agent 集成到现有系统,为应用添加 AI 能力
快速开始
安装方式
pip install git+https://github.com/HKUDS/nanobot.git
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
pip install -e .
pip install nanobot
Python 3.8+
支持的 LLM API(OpenAI、Anthropic 等)
基本使用
1. 创建简单的 Agent from nanobot import Agent, LLM
llm = LLM(provider="openai" , model="gpt-4" )
agent = Agent(
name="Assistant" ,
llm=llm,
system_prompt="You are a helpful assistant."
)
response = agent.chat("Hello, how are you?" )
print (response)
2. 添加工具支持 from nanobot import Agent, Tool
def get_weather (location: str ) -> str :
"""Get weather information for a location."""
return f"Weather in {location} : Sunny, 25°C"
weather_tool = Tool(
name="get_weather" ,
description="Get weather information" ,
function=get_weather
)
agent = Agent(
name="WeatherBot" ,
llm=llm,
tools=[weather_tool]
)
response = agent.chat("What's the weather in Hong Kong?" )
print (response)
3. 使用规划器 from nanobot import Agent, Planner
planner = Planner(llm=llm)
agent = Agent(
name="PlannerBot" ,
llm=llm,
planner=planner
)
response = agent.chat("Plan a trip to Japan: research flights, hotels, and attractions" )
print (response)
4. 流式响应
for chunk in agent.chat_stream("Tell me a story" ):
print (chunk, end="" , flush=True )
架构设计 NanoBot 采用模块化、可扩展的架构设计 ,核心组件清晰分离,便于理解和定制。
核心架构 NanoBot/
├── Agent (核心)
│ ├── LLM 接口
│ ├── 工具系统
│ ├── 规划器
│ ├── 记忆管理
│ └── 执行引擎
├── Tools (工具)
│ ├── 内置工具
│ ├── 自定义工具
│ └── 工具链
├── Planner (规划器)
│ ├── 任务分解
│ ├── 步骤规划
│ └── 执行策略
├── Memory (记忆)
│ ├── 对话历史
│ ├── 长期记忆
│ └── 上下文管理
└── LLM (大模型)
├── 多提供商支持
├── 统一接口
└── 流式响应
设计原则
简洁性优先 :最少的代码实现最多的功能
模块化设计 :每个组件都是独立的模块,可以单独使用或替换
可扩展性 :通过继承和组合轻松扩展功能
核心模块详解
1. Agent 核心模块
Agent 的创建和配置
对话管理和响应生成
工具调用和规划执行
状态管理和上下文维护
class Agent :
def __init__ (
self,
name: str ,
llm: LLM,
system_prompt: str = None ,
tools: List [Tool] = None ,
planner: Planner = None ,
memory: Memory = None
):
self .name = name
self .llm = llm
self .system_prompt = system_prompt
self .tools = tools or []
self .planner = planner
self .memory = memory or SimpleMemory()
self .conversation_history = []
def chat (self, message: str ) -> str :
self .conversation_history.append({"role" : "user" , "content" : message})
if self .planner:
plan = self .planner.plan(message, self .conversation_history)
tool_calls = self ._detect_tool_calls(message)
if tool_calls:
results = self ._execute_tools(tool_calls)
message = self ._format_with_tool_results(message, results)
response = self .llm.chat(
messages=self ._build_messages(),
tools=self ._format_tools()
)
self .conversation_history.append({"role" : "assistant" , "content" : response})
return response
def _detect_tool_calls (self, message: str ) -> List [dict ]:
pass
def _execute_tools (self, tool_calls: List [dict ] ) -> List [dict ]:
results = []
for tool_call in tool_calls:
tool = self ._find_tool(tool_call["name" ])
result = tool.execute(tool_call["arguments" ])
results.append(result)
return results
2. 工具系统模块
工具的定义和注册
工具调用的执行
工具链的组合
工具结果的格式化
class Tool :
def __init__ (self, name: str , description: str , function: Callable , parameters: dict = None ):
self .name = name
self .description = description
self .function = function
self .parameters = parameters or {}
def execute (self, **kwargs ) -> Any :
self ._validate_parameters(kwargs)
try :
result = self .function(**kwargs)
return {"success" : True , "result" : result}
except Exception as e:
return {"success" : False , "error" : str (e)}
def to_openai_format (self ) -> dict :
return {
"type" : "function" ,
"function" : {
"name" : self .name,
"description" : self .description,
"parameters" : self .parameters
}
}
3. 规划器模块 class Planner :
def __init__ (self, llm: LLM ):
self .llm = llm
def plan (self, task: str , context: List [dict ] = None ) -> dict :
prompt = self ._build_planning_prompt(task, context)
response = self .llm.chat(
messages=[{"role" : "user" , "content" : prompt}],
response_format="json"
)
plan = json.loads(response)
return {
"task" : task,
"steps" : plan["steps" ],
"estimated_time" : plan.get("estimated_time" ),
"dependencies" : plan.get("dependencies" , [])
}
def _build_planning_prompt (self, task: str , context: List [dict ] ) -> str :
return f"""
Given the following task, create a detailed plan:
Task: {task}
Context: {json.dumps(context, indent=2 ) if context else "None" }
Please provide a JSON response with:
- steps: List of steps to complete the task
- estimated_time: Estimated time for each step
- dependencies: Dependencies between steps
"""
4. 记忆管理模块 class SimpleMemory :
def __init__ (self, max_history: int = 100 ):
self .max_history = max_history
self .history = []
def add (self, role: str , content: str ):
self .history.append({"role" : role, "content" : content, "timestamp" : time.time()})
if len (self .history) > self .max_history:
self .history = self .history[-self .max_history:]
def get_context (self, max_tokens: int = None ) -> List [dict ]:
if max_tokens:
return self ._truncate_by_tokens(self .history, max_tokens)
return self .history
def _truncate_by_tokens (self, history: List [dict ], max_tokens: int ) -> List [dict ]:
truncated = []
current_tokens = 0
for message in reversed (history):
message_tokens = self ._count_tokens(message["content" ])
if current_tokens + message_tokens > max_tokens:
break
truncated.insert(0 , message)
current_tokens += message_tokens
return truncated
5. LLM 集成模块
多 LLM 提供商支持
统一的接口抽象
流式响应处理
class LLM :
def __init__ (self, provider: str , model: str , api_key: str = None ):
self .provider = provider
self .model = model
self .api_key = api_key or os.getenv(f"{provider.upper()} _API_KEY" )
self .client = self ._create_client()
def _create_client (self ):
if self .provider == "openai" :
import openai
return openai.OpenAI(api_key=self .api_key)
elif self .provider == "anthropic" :
import anthropic
return anthropic.Anthropic(api_key=self .api_key)
def chat (self, messages: List [dict ], tools: List [dict ] = None , response_format: str = None ) -> str :
if self .provider == "openai" :
return self ._openai_chat(messages, tools, response_format)
elif self .provider == "anthropic" :
return self ._anthropic_chat(messages, tools, response_format)
def chat_stream (self, messages: List [dict ], tools: List [dict ] = None ):
if self .provider == "openai" :
stream = self .client.chat.completions.create(
model=self .model,
messages=messages,
tools=tools,
stream=True
)
for chunk in stream:
if chunk.choices[0 ].delta.content:
yield chunk.choices[0 ].delta.content
关键技术实现
1. 工具自动调用 NanoBot 通过 LLM 的函数调用能力自动检测和执行工具:
def _detect_and_execute_tools (self, message: str , context: List [dict ] ) -> str :
messages = self ._build_messages_with_tools(context)
response = self .llm.chat(
messages=messages,
tools=[tool.to_openai_format() for tool in self .tools]
)
if hasattr (response, "tool_calls" ) and response.tool_calls:
tool_results = []
for tool_call in response.tool_calls:
tool = self ._find_tool(tool_call.function.name)
result = tool.execute(**json.loads(tool_call.function.arguments))
tool_results.append({
"tool_call_id" : tool_call.id ,
"role" : "tool" ,
"name" : tool_call.function.name,
"content" : json.dumps(result)
})
messages.extend(tool_results)
final_response = self .llm.chat(messages=messages)
return final_response.content
return response.content
2. 规划与执行循环 def execute_with_planning (self, task: str ) -> str :
plan = self .planner.plan(task, self .conversation_history)
results = []
for step in plan["steps" ]:
if step.get("requires_tool" ):
tool_result = self ._execute_tool_for_step(step)
results.append(tool_result)
else :
response = self .llm.chat(
messages=self ._build_messages() + [{"role" : "user" , "content" : step["description" ]}]
)
results.append(response.content)
if step.get("requires_reflection" ):
reflection = self ._reflect_on_step(step, results[-1 ])
if reflection["should_adjust" ]:
plan = self ._adjust_plan(plan, reflection)
summary = self ._summarize_execution(plan, results)
return summary
3. 上下文窗口优化 def optimize_context (self, messages: List [dict ], max_tokens: int ) -> List [dict ]:
system_messages = [msg for msg in messages if msg["role" ] == "system" ]
recent_messages = messages[-10 :]
current_tokens = self ._count_tokens(system_messages + recent_messages)
if current_tokens > max_tokens:
old_messages = messages[:-10 ]
summary = self ._summarize_messages(old_messages)
return system_messages + [
{"role" : "assistant" , "content" : f"Previous conversation summary: {summary} " }
] + recent_messages
return system_messages + recent_messages
扩展机制
自定义 Agent class CustomAgent (Agent ):
def __init__ (self, *args, **kwargs ):
super ().__init__(*args, **kwargs)
self .custom_state = {}
def custom_method (self, input_data ):
result = self .llm.chat([{"role" : "user" , "content" : f"Process: {input_data} " }])
self .custom_state["last_result" ] = result
return result
自定义工具 class DatabaseTool (Tool ):
def __init__ (self, connection_string: str ):
super ().__init__(
name="query_database" ,
description="Query a SQL database" ,
function=self ._query
)
self .db = connect(connection_string)
def _query (self, sql: str ) -> dict :
try :
result = self .db.execute(sql)
return {
"success" : True ,
"data" : result.fetchall(),
"columns" : result.keys()
}
except Exception as e:
return {"success" : False , "error" : str (e)}
自定义规划器 class HierarchicalPlanner (Planner ):
def plan (self, task: str , context: List [dict ] = None ) -> dict :
high_level_plan = self ._high_level_planning(task)
detailed_steps = []
for goal in high_level_plan["goals" ]:
steps = self ._detailed_planning(goal)
detailed_steps.extend(steps)
return {
"task" : task,
"high_level_goals" : high_level_plan["goals" ],
"detailed_steps" : detailed_steps
}
资源链接 相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
随机西班牙地址生成器 随机生成西班牙地址(支持马德里、加泰罗尼亚、安达卢西亚、瓦伦西亚筛选),支持数量快捷选择、显示全部与下载。 在线工具,随机西班牙地址生成器在线工具,online
Gemini 图片去水印 基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online