AstrBot 源码学习
整合大量即时通讯渠道的 AI Agent 助理与开发框架。这不是 API 速查表,而是一条可以重复走的源码路线:每天用 30 分钟,从一个真实相对路径出发,先用类比建立直觉,再把它接回整条运行链路。
开篇 · 这是个什么项目
AstrBot 可以先想成一间多 IM 机器人中枢。它的代码不是一堆孤立文件:入口接到需求,核心对象做判断,工具或模型完成工作,状态把结果交给下一个环节。
架构全景(动起来看)
发光扫过的每一层都是一次任务可能经过的站点。不同仓库命名不同,但「接入 → 编排 → 核心能力 → 资源」的责任边界很相似。
怎么使用这份教程
每天 30 分钟
6 讲,每讲先问问题,再给本质和大白话。
真实相对路径
所有路径都从项目根目录算,不把你的机器路径写进源码引用。
先验证再推理
每页都有可复制 bash 命令;文件版本变化时以本地实际内容为准。
可迁移方法
学会从入口、数据结构、循环和扩展点读任何 AI 项目。
从 README.md 认识项目大门
README.md:围绕 README.md 建立因果链:谁调用、处理什么、交给谁;对应阶段是「入口与地图」。
配置与依赖:pyproject.toml
pyproject.toml:围绕 pyproject.toml 建立因果链:谁调用、处理什么、交给谁;对应阶段是「入口与地图」。
顶层入口与启动路径
main.py:围绕 main.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「入口与地图」。
核心对象:config.py
astrbot/core/agent/context/config.py:围绕 astrbot/core/agent/context/config.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「核心循环」。
运转循环里的 server.py
astrbot/core/platform/sources/lark/server.py:围绕 astrbot/core/platform/sources/lark/server.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「核心循环」。
协作主线穿过 agent
tests/agent:围绕 tests/agent 建立因果链:谁调用、处理什么、交给谁;对应阶段是「核心循环」。
能力模块:tool.py
astrbot/core/agent/tool.py:围绕 astrbot/core/agent/tool.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「核心能力」。
业务动作落在 tool_executor.py
astrbot/core/agent/tool_executor.py:围绕 astrbot/core/agent/tool_executor.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「核心能力」。
把任务交给 tool_image_cache.py
astrbot/core/agent/tool_image_cache.py:围绕 astrbot/core/agent/tool_image_cache.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「核心能力」。
扩展点附近的 tool_loop_agent_runner.py
astrbot/core/agent/runners/tool_loop_agent_runner.py:围绕 astrbot/core/agent/runners/tool_loop_agent_runner.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「核心能力」。
状态如何进入 message.py
astrbot/core/agent/message.py:围绕 astrbot/core/agent/message.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「状态与协作」。
消息与协作:message_tools.py
astrbot/core/tools/message_tools.py:围绕 astrbot/core/tools/message_tools.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「状态与协作」。
持久化视角下的 session_status_check
astrbot/core/pipeline/session_status_check:围绕 astrbot/core/pipeline/session_status_check 建立因果链:谁调用、处理什么、交给谁;对应阶段是「状态与协作」。
模型侧连接:server.py
astrbot/dashboard/server.py:围绕 astrbot/dashboard/server.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「模型与扩展」。
工具/MCP 桥:mcp_client.py
astrbot/core/agent/mcp_client.py:围绕 astrbot/core/agent/mcp_client.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「模型与扩展」。
检索与知识:provider
astrbot/api/provider:围绕 astrbot/api/provider 建立因果链:谁调用、处理什么、交给谁;对应阶段是「模型与扩展」。
集成层:__init__.py
astrbot/api/provider/__init__.py:围绕 astrbot/api/provider/__init__.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「模型与扩展」。
样例与复盘:test_context_manager.py
tests/agent/test_context_manager.py:围绕 tests/agent/test_context_manager.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「复盘与扩展」。
测试与边界:test_token_counter.py
tests/agent/test_token_counter.py:围绕 tests/agent/test_token_counter.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「复盘与扩展」。
收官:沿 test_truncator.py 串回全图
tests/agent/test_truncator.py:围绕 tests/agent/test_truncator.py 建立因果链:谁调用、处理什么、交给谁;对应阶段是「复盘与扩展」。