ChatPaper.aiChatPaper

单子上下文工程

Monadic Context Engineering

December 27, 2025
作者: Yifan Zhang, Mengdi Wang
cs.AI

摘要

大型语言模型(LLM)的激增推动了能够进行复杂推理和工具使用的自主智能体发展。然而,当前智能体架构常采用命令式的临时模式构建,导致系统脆弱性突出,存在状态管理、错误处理和并发控制等难题。本文提出单子上下文工程(MCE),这一新型架构范式利用函子、应用函子与单子的代数结构,为智能体设计奠定形式化基础。MCE将智能体工作流视为计算上下文,其横切关注点(如状态传播、短路错误处理和异步执行)通过抽象代数的内在属性进行管理。我们论证了单子如何实现稳健的顺序组合,应用函子如何为并行执行提供原则性结构,并重点阐明单子变换器如何实现这些能力的系统化组合。这种分层架构使开发者能够从简单且可独立验证的组件出发,构建复杂、鲁棒且高效的人工智能体。我们进一步扩展该框架提出元智能体概念,其通过元编程技术利用MCE实现生成式编排,动态创建并管理子智能体工作流。项目页面:https://github.com/yifanzhang-pro/monadic-context-engineering。
English
The proliferation of Large Language Models (LLMs) has catalyzed a shift towards autonomous agents capable of complex reasoning and tool use. However, current agent architectures are frequently constructed using imperative, ad hoc patterns. This results in brittle systems plagued by difficulties in state management, error handling, and concurrency. This paper introduces Monadic Context Engineering (MCE), a novel architectural paradigm leveraging the algebraic structures of Functors, Applicative Functors, and Monads to provide a formal foundation for agent design. MCE treats agent workflows as computational contexts where cross-cutting concerns, such as state propagation, short-circuiting error handling, and asynchronous execution, are managed intrinsically by the algebraic properties of the abstraction. We demonstrate how Monads enable robust sequential composition, how Applicatives provide a principled structure for parallel execution, and crucially, how Monad Transformers allow for the systematic composition of these capabilities. This layered approach enables developers to construct complex, resilient, and efficient AI agents from simple, independently verifiable components. We further extend this framework to describe Meta-Agents, which leverage MCE for generative orchestration, dynamically creating and managing sub-agent workflows through metaprogramming. Project Page: https://github.com/yifanzhang-pro/monadic-context-engineering.
PDF70December 31, 2025