分类: AI学习

  • 12. Dify 架构深度分析

    基于 langgenius/dify 源码分析(154k+ Stars,24.4k Forks)

    分析源码:api/core/agent/base_agent_runner.py、api/core/agent/cot_agent_runner.py、api/core/tools/tool_manager.py


    1. 项目概览与技术栈

    Dify 是一个开源 LLM 应用开发平台,提供 AI 工作流、RAG 管道、Agent 能力、模型管理和可观测性。后端使用 Python(Flask + SQLAlchemy),前端使用 Next.js,支持 Docker Compose 一键部署。

    # 项目结构(从仓库目录可见)
    # api/          — Python 后端核心(Agent、工具、模型运行时)
    # web/          — Next.js 前端
    # docker/       — Docker Compose 部署
    # dify-agent/   — 独立 Agent 运行时
    # dify-agent-runtime/ — Agent 运行时包
    # sdks/         — 多语言 SDK
    # packages/     — 共享包

    Dify 的 Agent 系统基于 graphon 模型运行时抽象层,支持数百种 LLM 提供商,通过统一的 PromptMessage 体系与模型交互。


    2. Agent 继承体系——三层架构

    Dify 的 Agent 采用清晰的三层继承结构:AppRunner → BaseAgentRunner → CotAgentRunner。

    (更多…)

  • 11. Composio 架构深度分析

    仓库: ComposioHQ/composio (26.2k ⭐)

    定位: 为 AI Agent 提供 1000+ 预认证工具集、会话管理、认证、触发器和沙箱执行环境

    语言: Python SDK + TypeScript SDK(monorepo)


    1. 整体架构:Provider 泛型 + Session 模型

    Composio 采用 Provider 泛型模式,核心 Composio 类通过泛型参数 TTool 和 TToolCollection 实现框架无关的工具适配。默认使用 OpenAI 格式,但可以无缝切换到 Anthropic、LangChain 等任何框架。

    # sdk.py - 核心 SDK 类定义
    class Composio(t.Generic[TTool, TToolCollection], WithLogger):
        """
        Generic parameters:
            TTool: The individual tool type returned by the provider
            TToolCollection: The collection type returned by get_tools
        """
    
        tools: "Tools[TTool, TToolCollection]"
    
        @t.overload
        def __init__(
            self: "Composio[OpenAITool, OpenAIToolCollection]",
            provider: None = None,
            **kwargs: te.Unpack[SDKConfig],
        ) -> None:
            """Initialize with default OpenAI provider."""
            ...
    
        @t.overload
        def __init__(
            self,
            provider: BaseProvider[TTool, TToolCollection],
            **kwargs: te.Unpack[SDKConfig],
        ) -> None:
            """Initialize with an explicit provider. Types are inferred from the provider."""
            ...

    设计亮点: 通过 @t.overload 实现两个初始化路径——无 provider 时默认 OpenAI 类型,有 provider 时自动推断泛型参数。这意味着 Composio(provider=AnthropicProvider()) 会自动得到 Composio[ToolParam, list[ToolParam]] 类型。


    2. HTTP 客户端:Stainless 生成器 + 运行时环境检测

    HTTP 客户端基于 Stainless 自动生成的 API 客户端包装,增加了运行时环境检测和请求拦截能力。

    (更多…)

  • AI编程(二十二):简易记账本 — 月底看看钱都去哪了

    文件存账目、列表管记录、函数做统计——第十二篇价格工具的”理财升级版”

    一、月底的灵魂拷问

    每个月底总有那么一个瞬间:看看银行卡余额,倒吸一口凉气,然后问出那个经典问题——

    “我钱呢??”

    明明没买什么大件,钱就是没了。吃饭、打车、奶茶、网购……每笔都不大,加起来吓人。

    (更多…)

  • 10. Letta 深度架构分析

    项目: letta-ai/letta | Stars: 24.6K | License: Apache 2.0

    定位: 有状态 AI Agent 平台——具有高级记忆系统,能够随时间学习和自我改进

    前身: MemGPT(UC Berkeley BAIR 实验室研究成果)

    当前状态: V1 服务器代码归档于此仓库 archive 分支,新代码已迁移至 letta-ai/letta-code


    1. 整体架构哲学:LLM 即操作系统

    Letta 的核心理念源自 MemGPT 论文——将 LLM 视为操作系统的内核,Agent 就是运行在这个操作系统上的进程。系统采用分层记忆架构,灵感来自计算机体系结构中的虚拟内存管理:

    • 核心记忆(Core Memory) → 寄存器/L1 缓存:始终在上下文窗口内
    • 对话记忆(Recall Memory) → RAM:可搜索的历史对话
    • 归档记忆(Archival Memory) → 磁盘:长期向量存储
    • 文件系统(Filesystem) → 外部存储:Git 版本化的文件
    class ContextWindowOverview(BaseModel):
        """Overview of the context window, including the number of messages and tokens."""
        context_window_size_max: int = Field(..., description="The maximum amount of tokens the context window can hold.")
        context_window_size_current: int = Field(..., description="The current number of tokens in the context window.")
        num_messages: int = Field(..., description="The number of messages in the context window.")
        num_archival_memory: int = Field(..., description="The number of messages in the archival memory.")
        num_recall_memory: int = Field(..., description="The number of messages in the recall memory.")
        num_tokens_external_memory_summary: int = Field(..., description="The number of tokens in the external memory summary.")
        num_tokens_system: int = Field(..., description="The number of tokens in the system prompt.")
        num_tokens_core_memory: int = Field(..., description="The number of tokens in the core memory.")
        num_tokens_memory_filesystem: int = Field(0, description="The number of tokens in the memory filesystem section.")
        num_tokens_summary_memory: int = Field(..., description="The number of tokens in the summary memory.")
        num_tokens_functions_definitions: int = Field(..., description="The number of tokens in the functions definitions.")

    这个 ContextWindowOverview 精确追踪上下文窗口中每个组成部分的 token 消耗,类似于操作系统的内存使用报告。


    2. Agent 类型体系:多形态 Agent 设计

    Letta 定义了丰富的 Agent 类型枚举,每种类型对应不同的运行时行为和工具集:

    (更多…)

  • AI编程(二十一):倒计时提醒器 — 教会程序看表

    煮面计时5分钟,开会前10分钟提醒——这次用上全系列唯一的新东西:time模块

    一、你缺的不是时间管理,是一个帮你盯时间的人

    场景一:煮面条,说好煮5分钟。你去刷手机,一抬头——20分钟过去了,面糊了。

    场景二:下午3点开会,你想提前10分钟准备。结果一忙起来抬头看表——3点05了。

    场景三:敷面膜15分钟、煮鸡蛋8分钟、烤箱25分钟、午睡20分钟……

    (更多…)

  • 09. Agno 深度架构分析

    项目: agno-agi/agno

    定位: Build, run, and manage agent platforms

    Stars: 42,131 | Forks: 5,903 | License: Apache-2.0

    语言: Python | 核心框架: Pydantic


    一、项目概览与分层架构

    Agno 不仅仅是一个 Agent 框架,而是一个完整的 Agent 平台运行时(AgentOS)。它由三层构成:

    1. SDK 层 (libs/agno/agno/) — Agent 构建的核心 API
    2. 运行时层 — 50+ REST/SSE/WebSocket 端点,提供生产级服务
    3. 管理层 — Web UI 控制面,JWT RBAC,多租户隔离

    源码目录结构清晰地反映了这种分层:

    libs/agno/agno/
    ├── agent/          # Agent 核心(拆分为 _init, _run, _tools, _session 等子模块)
    ├── models/         # 模型抽象层(100+ 提供商适配)
    ├── tools/          # 工具系统(Toolkit + Function + @tool 装饰器)
    ├── memory/         # 记忆管理(MemoryManager + 优化策略)
    ├── session/        # 会话持久化
    ├── run/            # 运行时事件系统
    ├── knowledge/      # 知识库协议
    ├── db/             # 数据库抽象
    └── ...

    Agent 核心类采用 模块拆分 模式——agent.py 只是入口,实际逻辑分散在 _init.py、_run.py、_tools.py、_session.py 等子模块中,通过 __init__.py 的 re-export 组合在一起:

    (更多…)

  • AI编程(二十):单位转换器 — 一个字典搞定所有换算

    做饭要换算克和毫升,出差要换算时区——让字典和函数帮你记住所有公式

    一、你一定经历过这种时刻

    做饭看菜谱:”面粉200克,牛奶150毫升”。你家只有量杯,怎么量?

    出差订机票:航班显示”当地时间14:30起飞”,北京时间是几点?

    健身看教程:”做3组,每组15磅的哑铃”。磅是多少斤?

    (更多…)

  • 08.BrowserUse架构分析

    项目: browser-use/browser-use

    定位: AI 浏览器自动化 Agent 框架,MIT 许可,86k+ Stars

    核心理念: 让 AI 像人类一样操控浏览器——理解页面结构、规划操作序列、执行交互动作

    架构总览

    Browser-Use 采用三层分离架构:Agent 层(LLM 决策)→ Tools/Controller 层(动作注册与执行)→ BrowserSession 层(CDP 浏览器控制)。事件总线(EventBus)贯穿全栈,所有浏览器操作以事件驱动方式执行。以下是 10 个核心维度的深度分析。


    1. Agent 核心循环(Step-Loop)

    Agent 的执行是一个经典的感知-思考-行动循环。每个 step 由三个阶段组成:准备上下文、获取 LLM 输出、执行动作。

    # agent/service.py - Agent.step()
    @observe(name='agent.step', ignore_output=True, ignore_input=True)
    @time_execution_async('--step')
    async def step(self, step_info: AgentStepInfo | None = None) -> None:
        """Execute one step of the task"""
        self.step_start_time = time.time()
        browser_state_summary = None
        try:
            # Phase 0: CAPTCHA 等待
            if self.browser_session:
                captcha_wait = await self.browser_session.wait_if_captcha_solving()
                if captcha_wait and captcha_wait.waited:
                    self.step_start_time = time.time()
    
            # Phase 1: 准备上下文(浏览器状态 + 消息构建)
            browser_state_summary = await self._prepare_context(step_info)
            self.state.last_model_output = None
            self.state.last_result = None
    
            # Phase 2: LLM 推理 + 动作执行
            await self._get_next_action(browser_state_summary)
            await self._execute_actions()
    
            # Phase 3: 后处理(下载追踪、循环检测、日志)
            await self._post_process()
    
        except Exception as e:
            await self._handle_step_error(e)
        finally:
            await self._finalize(browser_state_summary)

    关键设计:每个 step 的超时由 step_timeout=180 控制,LLM 调用有独立的 llm_timeout(根据模型自动配置,如 Gemini 75s、Claude 90s)。CAPTCHA 解算时间不计入 step 耗时。

    (更多…)

  • AI编程(十九):文字冒险游戏 — 把所有知识揉进一场冒险

    用字典搭一个地牢,用循环让你探索,用条件判断决定生死

    一、你还记得小时候的”选故事”书吗

    有一种书,读到一半会问你:主角面前有两条路,走左边翻到第30页,走右边翻到第57页。不同的选择,通向不同的结局。

    今天我们要做的,就是这种书的程序版——文字冒险游戏。

    程序会描述你身处的场景,给你几个选项。你输入选择,故事往前走。选对了找到宝藏,选错了掉进陷阱。而且这次不是小打小闹:我们要有多个结局、物品系统、存档功能。

    (更多…)

  • 07.PydanticAI架构分析

    项目: pydantic/pydantic-ai

    定位: “How Python does AI” — 基于 Pydantic 类型系统的类型安全 AI Agent 框架

    版本: 2026 年 9 月 main 分支

    源码分析: agent/__init__.py, _agent_graph.py, tools.py, models/__init__.py, models/_abstract.py, _tool_execution.py


    1. 整体架构概览

    PydanticAI 的核心设计哲学是 “typed end to end” —— 从用户输入到 LLM 输出,全链路类型安全。其架构基于 pydantic-graph 库实现的有向图执行引擎,将 Agent 的运行时分解为三个核心节点的循环:

    UserPromptNode → ModelRequestNode → CallToolsNode → ModelRequestNode → ... → End

    Agent 类本身是一个泛型类,参数化了依赖类型 AgentDepsT 和输出类型 OutputDataT:

    # agent/__init__.py
    class Agent(AbstractAgent[AgentDepsT, OutputDataT]):
        """Class for defining "agents" - a way to have a specific type of "conversation" with an LLM.
        Agents are generic in the dependency type they take AgentDepsT
        and the output type they return, OutputDataT.
        By default, if neither generic parameter is customised, agents have type Agent[object, str].
        """
        _model: models.Model | models.KnownModelName | str | None
        _name: str | None
        _description: TemplateStr[AgentDepsT] | str | None
        end_strategy: EndStrategy
        model_settings: AgentModelSettings[AgentDepsT] | None
        _output_type: OutputSpec[OutputDataT]
        _function_toolset: FunctionToolset[AgentDepsT]
        _output_toolset: OutputToolset[AgentDepsT] | None
        _user_toolsets: list[AbstractToolset[AgentDepsT]]

    这种泛型设计使得 Agent[int, str] 表示”依赖 int 类型上下文、返回 str”的 Agent,编译期即可获得类型检查。

    (更多…)