__init__.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. """
  2. lambdagent — 基于 Lambda 演算的 Agent DSL
  3. 每个 Agent 是一个 Lambda 项。组合 Agent 就是组合函数。
  4. 11 个核心构造,严格对应 Lambda 演算:
  5. Lambda 演算 DSL 构造
  6. ────────── ────────
  7. 1. λ 抽象 λx.body Lam(name, prompt)
  8. 2. 函数应用 (f x) agent(input)
  9. 3. 函数组合 λx.g(f(x)) f >> g
  10. 4. Church 条件 IF c t e If(cond, then_, else_)
  11. 5. Y 组合子 Loop(body, condition)
  12. 6. Church 对 PAIR Pair(f, g)
  13. 7. 投影 FST / SND Fst() / Snd()
  14. 8. 原语 / Oracle Tool(name, fn)
  15. 9. 广义 Church 布尔 CASE Route(classifier, routes)
  16. 10. 依赖类型 {x:T|P(x)} Guard(agent, validator)
  17. 11. 环境扩展 Γ' = Γ ∪ s Memory(agent, store)
  18. 多智能体扩展(π-演算 + 并发):
  19. 进程演算 DSL 构造
  20. ──────── ────────
  21. 12. π-calculus 通道 c!(v)/c? Channel + Send + Receive
  22. 13. 共享环境 Γ_shared SharedMemory
  23. 14. 多Agent群组对话 GroupChat (= Loop + Route 组合)
  24. 15. 动态路由 (动态 CASE) Handoff
  25. 16. 并发 β-规约 AsyncPar
  26. 辅助设施(非构造):
  27. - Context 求值环境 Γ + β-规约追踪(元层级)
  28. - Dataset Lam 的便利构造器(D.to_lam() = Lam(prompt=encode(D)))
  29. - from_config YAML → Lambda 编译器
  30. """
  31. from .core import Term, Context, TraceEntry
  32. from .core import LambdagentError, UnboundVariable, RouteError, ValidationError
  33. from .trace import (
  34. TraceStore, TraceEntry as EnhancedTraceEntry, Anomaly,
  35. colorize_timeline, detect_anomalies, format_anomalies,
  36. generate_flamegraph_html, save_flamegraph,
  37. replay, diff_traces,
  38. )
  39. from .primitives import Lam, Compose, If, Loop, Pair, Fst, Snd, Tool
  40. from .extensions import Par, Route, Memory, Guard
  41. from .sandbox import (
  42. SandboxedTool, SandboxPolicy, SecureExecutor,
  43. SandboxViolation, TimeoutViolation, MemoryViolation, OutputViolation,
  44. ResourceLimiter, sandboxed,
  45. )
  46. from .dataset import Dataset
  47. from .multiagent import (
  48. Channel, Send, Receive,
  49. SharedMemory,
  50. GroupChat,
  51. Handoff,
  52. AsyncPar,
  53. ChannelClosed, HandoffError, GroupChatError,
  54. )
  55. from .skills import (
  56. Skill, SkillSignature, SkillPack,
  57. SkillRegistry, SkillAgent, skill,
  58. )
  59. from .mcp_client import (
  60. MCPServer, MCPTool, MCPToolInfo,
  61. MCPError, MCPConnectionError, MCPToolError,
  62. mcp_tools, mcp_tool,
  63. )
  64. from .checkpoint import (
  65. Checkpoint, CheckpointManager,
  66. save_context, load_context,
  67. CheckpointError,
  68. )
  69. from .a2a import (
  70. AgentCard, A2AServer, A2AClient, A2ATask,
  71. skill_to_agent_card, registry_to_agent_card,
  72. )
  73. from .rag import (
  74. RAGTool, AgenticRAG, SimpleVectorStore, Document, SearchResult,
  75. create_rag,
  76. )
  77. # Paper III: Type & Effect System
  78. from .types import (
  79. LamType, TypeTag, AgentType, AgentTypeError,
  80. T_ANY, T_NONE, T_STR, T_INT, T_FLOAT, T_BOOL, T_JSON, T_TUPLE, T_UNION,
  81. is_subtype, check_compose_types, parse_type_annotation, infer_type_from_value,
  82. )
  83. from .effects import (
  84. Effect, EffectKind, ComposedEffect,
  85. PURE, IO, LLM, STATE,
  86. serial, parallel, iterate,
  87. effect_leq, max_effect,
  88. parse_effect_annotation, infer_effect_for_term,
  89. )
  90. # Paper II: Store Independence Analysis
  91. from .store_analysis import StoreConflictError
  92. # Paper III §6: Algebraic Effect Handlers
  93. from .handlers import (
  94. EffectHandler, ProductionHandler, TestHandler, TraceHandler,
  95. get_current_handler, set_current_handler, with_handler,
  96. )
  97. # Paper III §4.3: Graded Cost Prediction
  98. from .cost_grade import (
  99. CostGrade, estimate_cost, format_cost_estimate,
  100. grade_serial, grade_parallel, grade_iterate, grade_guard,
  101. )
  102. # Paper II Theorems 36-41: Algebraic Law Rewrite Rules
  103. from .rewrite import optimize as optimize_agent, RewriteLog, RewriteEntry
  104. # Paper II: CEK Machine upgrades
  105. from .cek_machine import AgentCEKMachine, CostVector, CostMonotonicityViolation
  106. # Phase 1: P0 Engineering Improvements
  107. from .cancellation import CancellationToken, CancelledError, NullCancellationToken
  108. from .retry import RetryPolicy, CircuitBreaker, CircuitOpenError, with_retry, with_retry_sync
  109. from .isolation import IsolationLevel, IsolatedWorkspace, WorkspaceManager
  110. import lambdagent.async_core # patches aapply() onto all Term types
  111. # fromconfig (v2)
  112. from .fromconfig import from_config, build_agent, describe_config
  113. from .fromconfig import from_config as from_config_v2 # backwards compat alias
  114. from .fromconfig import lint_config, to_lambda_expr
  115. # Phase 6.5: Dual engine — FIX-07: export engine classes
  116. from .agentruntime.engine import EngineMode, EngineResult, UnifiedTraceRecord
  117. from .agentruntime.recursive_engine import RecursiveEngine
  118. from .agentruntime.cek_engine import CEKEngine
  119. from .agentruntime.runtime import Runtime, RuntimeResult
  120. __all__ = [
  121. # 元层级
  122. "Term", "Context", "TraceEntry",
  123. # Enhanced trace system
  124. "TraceStore", "EnhancedTraceEntry", "Anomaly",
  125. "colorize_timeline", "detect_anomalies", "format_anomalies",
  126. "generate_flamegraph_html", "save_flamegraph",
  127. "replay", "diff_traces",
  128. # 异常
  129. "LambdagentError", "UnboundVariable", "RouteError", "ValidationError",
  130. # 11 个核心构造
  131. "Lam", # 1. λ 抽象
  132. "Compose", # 3. 函数组合 (>> 操作符)
  133. "If", # 4. Church 条件
  134. "Loop", # 5. Y 组合子
  135. "Pair", # 6. Church 对
  136. "Fst", "Snd", # 7. 投影
  137. "Tool", # 8. 原语 / Oracle
  138. "Route", # 9. 广义 Church 布尔
  139. "Guard", # 10. 依赖类型
  140. # 安全沙盒 (Phase 8)
  141. "SandboxedTool", # Tool + 进程隔离
  142. "SandboxPolicy", # 安全策略
  143. "SecureExecutor", # 沙盒感知求值器
  144. "sandboxed", # @sandboxed 装饰器
  145. "SandboxViolation", "TimeoutViolation", "MemoryViolation", "OutputViolation",
  146. "ResourceLimiter",
  147. "Memory", # 11. 环境扩展
  148. # 并行执行(Pair 的语法糖,| 操作符)
  149. "Par",
  150. # 多智能体扩展 (π-演算 + 并发)
  151. "Channel", # 12. π-calculus 通道
  152. "Send", # 通道发送 c!(v)
  153. "Receive", # 通道接收 c?(x)
  154. "SharedMemory", # 13. 共享环境 Γ_shared
  155. "GroupChat", # 14. 多Agent群组对话
  156. "Handoff", # 15. 动态委派(运行时 Route)
  157. "AsyncPar", # 16. 真并行执行
  158. # 多智能体异常
  159. "ChannelClosed", "HandoffError", "GroupChatError",
  160. # Skill 系统
  161. "Skill", # 命名的可复用 Lambda 项
  162. "SkillSignature", # 技能类型签名
  163. "SkillPack", # 技能集合
  164. "SkillRegistry", # 全局技能注册表
  165. "SkillAgent", # 自动发现技能的 Agent
  166. "skill", # @skill 装饰器
  167. # MCP Client
  168. "MCPServer", # MCP 服务器连接
  169. "MCPTool", # MCP 工具 → lambdagent Term
  170. "mcp_tools", # 便利: 一行获取所有 MCP 工具
  171. "mcp_tool", # 便利: 一行获取单个 MCP 工具
  172. "MCPError", "MCPConnectionError", "MCPToolError",
  173. # Checkpoint
  174. "Checkpoint", # 状态快照
  175. "CheckpointManager", # 多 checkpoint 管理
  176. "save_context", # 保存 Context
  177. "load_context", # 恢复 Context
  178. "CheckpointError",
  179. # A2A Protocol
  180. "AgentCard", # A2A Agent 能力描述
  181. "A2AServer", # 发布 Agent 为 A2A 服务
  182. "A2AClient", # 调用远程 A2A Agent
  183. "skill_to_agent_card", "registry_to_agent_card",
  184. # RAG
  185. "RAGTool", # 检索增强工具
  186. "AgenticRAG", # Agent 自主决定是否检索
  187. "SimpleVectorStore", # 零依赖向量存储
  188. "create_rag", # 一行创建 RAG
  189. # Paper III: 类型系统
  190. "LamType", "TypeTag", "AgentType", "AgentTypeError",
  191. "T_ANY", "T_NONE", "T_STR", "T_INT", "T_FLOAT", "T_BOOL",
  192. "T_JSON", "T_TUPLE", "T_UNION",
  193. "is_subtype", "check_compose_types", "parse_type_annotation", "infer_type_from_value",
  194. # Paper III: 效果系统
  195. "Effect", "EffectKind", "ComposedEffect",
  196. "PURE", "IO", "LLM", "STATE",
  197. "serial", "parallel", "iterate",
  198. "effect_leq", "max_effect",
  199. "parse_effect_annotation", "infer_effect_for_term",
  200. # Paper II: 存储独立性分析
  201. "StoreConflictError",
  202. # Paper III §6: 代数效果处理器
  203. "EffectHandler", "ProductionHandler", "TestHandler", "TraceHandler",
  204. "get_current_handler", "set_current_handler", "with_handler",
  205. # Paper III §4.3: 分级成本预测
  206. "CostGrade", "estimate_cost", "format_cost_estimate",
  207. "grade_serial", "grade_parallel", "grade_iterate", "grade_guard",
  208. # Paper II: 代数定律重写
  209. "optimize_agent", "RewriteLog", "RewriteEntry",
  210. # Paper II: CEK 机器
  211. "AgentCEKMachine", "CostVector", "CostMonotonicityViolation",
  212. # 辅助设施
  213. "Dataset",
  214. "from_config", "build_agent", "describe_config",
  215. "from_config_v2", # backwards compat alias
  216. "lint_config", "to_lambda_expr",
  217. # Phase 1: P0 Engineering
  218. "CancellationToken", "CancelledError", "NullCancellationToken",
  219. "RetryPolicy", "CircuitBreaker", "CircuitOpenError",
  220. "with_retry", "with_retry_sync",
  221. "IsolationLevel", "IsolatedWorkspace", "WorkspaceManager",
  222. # Phase 6.5: Dual engine (FIX-07)
  223. "EngineMode", "EngineResult", "UnifiedTraceRecord",
  224. "RecursiveEngine", "CEKEngine", "Runtime", "RuntimeResult",
  225. ]