Chapter 9: Learning and Adaptation

第 9 章:学习和适应

Learning and adaptation are pivotal for enhancing the capabilities of artificial intelligence agents. These processes enable agents to evolve beyond predefined parameters, allowing them to improve autonomously through experience and environmental interaction. By learning and adapting, agents can effectively manage novel situations and optimize their performance without constant manual intervention. This chapter explores the principles and mechanisms underpinning agent learning and adaptation in detail. 学习和适应能力对于提升人工智能智能体的能力至关重要。这些过程让智能体能够突破预设参数的限制,通过经验和环境交互实现自主提升。借助学习和适应,智能体无需持续的人工干预,就能有效应对新情况并优化自身表现。本章将深入探讨支撑智能体学习和适应的原理与机制。

The big picture

全局视野

Agents learn and adapt by changing their thinking, actions, or knowledge based on new experiences and data. This allows agents to evolve from simply following instructions to becoming smarter over time. 智能体通过基于新经验和数据改变思维方式、行动或知识来实现学习和适应。这让智能体从单纯遵循指令,逐步演变为随时间推移变得更加智能的系统。

Fig.1: SICA’s self-improvement, learning and adapting based on its past versions 图 1:SICA 的自我改进过程,基于其过去版本进行学习和适应 SICA underwent significant self-improvement, leading to advancements in code editing and navigation. Initially, SICA utilized a basic file-overwriting approach for code changes. It subsequently developed a “Smart Editor” capable of more intelligent and contextual edits. This evolved into a “Diff-Enhanced Smart Editor,” incorporating diffs for targeted modifications and pattern-based editing, and a “Quick Overwrite Tool” to reduce processing demands. SICA 经历了显著的自我改进,在代码编辑和导航方面取得了重要进展。最初,SICA 使用基本的文件覆盖方法进行代码更改。随后,它开发了能够进行更智能和上下文相关编辑的”智能编辑器”。这进一步演变为”差异增强智能编辑器”,结合差异进行有针对性的修改和基于模式的编辑,以及”快速覆盖工具”以减少处理需求。 SICA further implemented “Minimal Diff Output Optimization” and “Context-Sensitive Diff Minimization,” using Abstract Syntax Tree (AST) parsing for efficiency. Additionally, a “SmartEditor Input Normalizer” was added. In terms of navigation, SICA independently created an “AST Symbol Locator,” using the code’s structural map (AST) to identify definitions within the codebase. Later, a “Hybrid Symbol Locator” was developed, combining a quick search with AST checking. This was further optimized via “Optimized AST Parsing in Hybrid Symbol Locator” to focus on relevant code sections, improving search speed.(see Fig. 2) SICA 进一步实现了”最小差异输出优化”和”上下文敏感差异最小化”,使用抽象语法树(AST)解析来提高效率。此外,还添加了”智能编辑器输入规范化器”。在导航方面,SICA 独立创建了”AST 符号定位器”,使用代码的结构图(AST)来识别代码库中的定义。后来,开发了”混合符号定位器”,将快速搜索与 AST 检查相结合。这通过”混合符号定位器中的优化 AST 解析”进一步优化,专注于相关代码部分,提高搜索速度(见图2)。

Fig.2 : Performance across iterations. Key improvements are annotated with their corresponding tool or agent modifications. (courtesy of Maxime Robeyns , Martin Szummer , Laurence Aitchison) 图 2:跨迭代的性能表现。关键改进用其相应的工具或智能体修改进行标注。(由 Maxime Robeyns、Martin Szummer、Laurence Aitchison 提供) SICA’s architecture comprises a foundational toolkit for basic file operations, command execution, and arithmetic calculations. It includes mechanisms for result submission and the invocation of specialized sub-agents (coding, problem-solving, and reasoning). These sub-agents decompose complex tasks and manage the LLM’s context length, especially during extended improvement cycles. SICA 的架构包括用于基本文件操作、命令执行和算术计算的基础工具包。它包含结果提交机制和调用专门子智能体(编码、问题解决和推理)的功能。这些子智能体负责分解复杂任务并管理 LLM 的上下文长度,特别是在扩展改进周期期间。 An asynchronous overseer, another LLM, monitors SICA’s behavior, identifying potential issues such as loops or stagnation. It communicates with SICA and can intervene to halt execution if necessary. The overseer receives a detailed report of SICA’s actions, including a callgraph and a log of messages and tool actions, to identify patterns and inefficiencies. 一个异步监督者(另一个 LLM)监控 SICA 的行为,识别潜在问题,如循环或停滞。它与 SICA 进行通信,必要时可以介入以停止执行。监督者接收 SICA 行动的详细报告,包括调用图和消息及工具操作日志,以识别模式和低效率。 SICA’s LLM organizes information within its context window, its short-term memory, in a structured manner crucial to its operation. This structure includes a System Prompt defining agent goals, tool and sub-agent documentation, and system instructions. A Core Prompt contains the problem statement or instruction, content of open files, and a directory map. Assistant Messages record the agent’s step-by-step reasoning, tool and sub-agent call records and results, and overseer communications. This organization facilitates efficient information flow, enhancing LLM operation and reducing processing time and costs. Initially, file changes were recorded as diffs, showing only modifications and periodically consolidated. SICA 的 LLM 在其上下文窗口(其短期记忆)中以对其操作至关重要的结构化方式组织信息。此结构包括定义智能体目标的系统提示词、工具和子智能体文档以及系统指令。核心提示词包含问题陈述或指令、打开文件的内容和目录映射。助手消息记录智能体的逐步推理、工具和子智能体调用记录及结果以及监督者通信。这种组织方式促进了高效的信息流动,增强了 LLM 操作并减少了处理时间和成本。最初,文件更改记录为差异,仅显示修改内容并定期合并。 SICA: A Look at the Code: Delving deeper into SICA’s implementation reveals several key design choices that underpin its capabilities. As discussed, the system is built with a modular architecture, incorporating several sub-agents, such as a coding agent, a problem-solver agent, and a reasoning agent. These sub-agents are invoked by the main agent, much like tool calls, serving to decompose complex tasks and efficiently manage context length, especially during those extended meta-improvement iterations. SICA:代码深度解析: 深入研究 SICA 的实现揭示了支撑其能力的几个关键设计选择。如前所述,该系统采用模块化架构构建,包含多个子智能体,如编码智能体、问题解决智能体和推理智能体。这些子智能体由主智能体调用,类似于工具调用,用于分解复杂任务并有效管理上下文长度,特别是在这些扩展的元改进迭代期间。 The project is actively developed and aims to provide a robust framework for those interested in post-training LLMs on tool use and other agentic tasks, with the full code available for further exploration and contribution at the https://github.com/MaximeRobeyns/self_improving_coding_agent/ GitHub repository. 该项目正在积极开发中,旨在为对 LLM 工具使用及其他智能体任务进行后训练感兴趣的人提供一个强大框架,完整代码可在 GitHub 存储库 进一步探索和贡献。 For security, the project strongly emphasizes Docker containerization, meaning the agent runs within a dedicated Docker container. This is a crucial measure, as it provides isolation from the host machine, mitigating risks like inadvertent file system manipulation given the agent’s ability to execute shell commands. 出于安全考虑,该项目强烈强调 Docker 容器化,这意味着智能体在专用 Docker 容器内运行。这是一个关键措施,因为它提供了与主机的隔离,鉴于智能体执行 shell 命令的能力,这减轻了意外文件系统操作等风险。 To ensure transparency and control, the system features robust observability through an interactive webpage that visualizes events on the event bus and the agent’s callgraph. This offers comprehensive insights into the agent’s actions, allowing users to inspect individual events, read overseer messages, and collapse sub-agent traces for clearer understanding. 为确保透明度和控制,系统通过可视化事件总线上的事件和智能体调用图的交互式网页提供强大的可观察性。这提供了对智能体行动的全面洞察,允许用户检查单个事件、阅读监督者消息并折叠子智能体跟踪以获得更清晰的理解。 In terms of its core intelligence, the agent framework supports LLM integration from various providers, enabling experimentation with different models to find the best fit for specific tasks. Finally, a critical component is the asynchronous overseer, an LLM that runs concurrently with the main agent. This overseer periodically assesses the agent’s behavior for pathological deviations or stagnation and can intervene by sending notifications or even cancelling the agent’s execution if necessary. It receives a detailed textual representation of the system’s state, including a callgraph and an event stream of LLM messages, tool calls, and responses, which allows it to detect inefficient patterns or repeated work. 就其核心智能而言,智能体框架支持来自各种提供商的 LLM 集成,使用户能够尝试不同的模型以找到特定任务的最佳匹配。最后,一个关键组件是异步监督者,这是一个与主智能体并发运行的 LLM。此监督者定期评估智能体的行为是否存在病理性偏差或停滞,必要时可以通过发送通知甚至取消智能体的执行来介入。它接收系统状态的详细文本表示,包括调用图和 LLM 消息、工具调用和响应的事件流,这使它能够检测低效模式或重复工作。 A notable challenge in the initial SICA implementation was prompting the LLM-based agent to independently propose novel, innovative, feasible, and engaging modifications during each meta-improvement iteration. This limitation, particularly in fostering open-ended learning and authentic creativity in LLM agents, remains a key area of investigation in current research. 初始 SICA 实现中的一个显著挑战是提示基于 LLM 的智能体在每次元改进迭代期间独立提出新颖、创新、可行且引人入胜的修改。这一限制,特别是在培养 LLM 智能体的开放式学习和真正创造力方面,仍然是当前研究的关键领域。

AlphaEvolve and OpenEvolve

AlphaEvolve 和 OpenEvolve

AlphaEvolve is an AI agent developed by Google designed to discover and optimize algorithms. It utilizes a combination of LLMs, specifically Gemini models (Flash and Pro), automated evaluation systems, and an evolutionary algorithm framework. This system aims to advance both theoretical mathematics and practical computing applications. AlphaEvolve 是 Google 开发的一个 AI 智能体,旨在发现和优化算法。它利用 LLM 的组合,特别是 Gemini 模型(Flash 和 Pro)、自动化评估系统和进化算法框架。该系统旨在推动理论数学和实际计算应用的发展。 AlphaEvolve employs an ensemble of Gemini models. Flash is used for generating a wide range of initial algorithm proposals, while Pro provides more in-depth analysis and refinement. Proposed algorithms are then automatically evaluated and scored based on predefined criteria. This evaluation provides feedback that is used to iteratively improve the solutions, leading to optimized and novel algorithms. AlphaEvolve 采用 Gemini 模型的集合。Flash 用于生成广泛的初始算法提案,而 Pro 提供更深入的分析和改进。然后根据预定义标准自动评估和评分提出的算法。此评估提供用于迭代改进解决方案的反馈,从而产生优化和新颖的算法。 In practical computing, AlphaEvolve has been deployed within Google’s infrastructure. It has demonstrated improvements in data center scheduling, resulting in a 0.7% reduction in global compute resource usage. It has also contributed to hardware design by suggesting optimizations for Verilog code in upcoming Tensor Processing Units (TPUs). Furthermore, AlphaEvolve has accelerated AI performance, including a 23% speed improvement in a core kernel of the Gemini architecture and up to 32.5% optimization of low-level GPU instructions for FlashAttention. 在实际计算中,AlphaEvolve 已部署在 Google 的基础设施中。它在数据中心调度方面展示了改进,导致全球计算资源使用减少 0.7%。它还通过为即将推出的张量处理单元(TPU)的 Verilog 代码提出优化建议来促进硬件设计。此外,AlphaEvolve 加速了 AI 性能,包括 Gemini 架构核心内核的 23% 速度提升以及 FlashAttention 的低级 GPU 指令的最高 32.5% 优化。 In the realm of fundamental research, AlphaEvolve has contributed to the discovery of new algorithms for matrix multiplication, including a method for 4x4 complex-valued matrices that uses 48 scalar multiplications, surpassing previously known solutions. In broader mathematical research, it has rediscovered existing state-of-the-art solutions to over 50 open problems in 75% of cases and improved upon existing solutions in 20% of cases, with examples including advancements in the kissing number problem. 在基础研究领域,AlphaEvolve 为矩阵乘法新算法的发现做出了贡献,包括使用 48 次标量乘法的 4x4 复数值矩阵方法,超过了先前已知的解决方案。在更广泛的数学研究中,它在 75% 的情况下重新发现了超过 50 个开放问题的现有最先进解决方案,并在 20% 的情况下改进了现有解决方案,例子包括接吻数问题的进步。 OpenEvolve is an evolutionary coding agent that leverages LLMs (see Fig.3) to iteratively optimize code. It orchestrates a pipeline of LLM-driven code generation, evaluation, and selection to continuously enhance programs for a wide range of tasks. A key aspect of OpenEvolve is its capability to evolve entire code files, rather than being limited to single functions. The agent is designed for versatility, offering support for multiple programming languages and compatibility with OpenAI-compatible APIs for any LLM. Furthermore, it incorporates multi-objective optimization, allows for flexible prompt engineering, and is capable of distributed evaluation to efficiently handle complex coding challenges. OpenEvolve 是一个利用大语言模型(见图3)迭代优化代码的进化编码智能体。它编排 LLM 驱动的代码生成、评估和选择流水线,持续为广泛任务增强程序。OpenEvolve 的一个关键方面是它能够进化完整代码文件,而不仅限于单个函数。该智能体设计为多功能,支持多种编程语言,并与任何 LLM 的 OpenAI 兼容 API 兼容。此外,它整合了多目标优化,允许灵活的提示工程,并能够进行分布式评估以高效处理复杂的编码挑战。

Fig. 3: The OpenEvolve internal architecture is managed by a controller. This controller orchestrates several key components: the program sampler, Program Database, Evaluator Pool, and LLM Ensembles. Its primary function is to facilitate their learning and adaptation processes to enhance code quality. 图 3:OpenEvolve 内部架构由控制器管理。该控制器编排几个关键组件:程序采样器、程序数据库、评估器池和 LLM 集合。其主要功能是促进它们的学习和适应过程以提高代码质量 This code snippet uses the OpenEvolve library to perform evolutionary optimization on a program. It initializes the OpenEvolve system with paths to an initial program, an evaluation file, and a configuration file. The evolve.run(iterations=1000) line starts the evolutionary process, running for 1000 iterations to find an improved version of the program. Finally, it prints the metrics of the best program found during the evolution, formatted to four decimal places. 此代码片段使用 OpenEvolve 库对程序执行进化优化。它使用初始程序、评估文件和配置文件的路径初始化 OpenEvolve 系统。evolve.run(iterations=1000) 行启动进化过程,运行 1000 次迭代以找到程序的改进版本。最后,它打印在进化过程中找到的最佳程序的指标,格式化为四位小数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from openevolve import OpenEvolve

## Initialize the system
evolve = OpenEvolve(
   initial_program_path="path/to/initial_program.py",
   evaluation_file="path/to/evaluator.py",
   config_path="path/to/config.yaml"
)

## Run the evolution
best_program = await evolve.run(iterations=1000)
print(f"Best program metrics:")
for name, value in best_program.metrics.items():
   print(f"  {name}: {value:.4f}")

At a Glance

概览

What: AI agents often operate in dynamic and unpredictable environments where pre-programmed logic is insufficient. Their performance can degrade when faced with novel situations not anticipated during their initial design. Without the ability to learn from experience, agents cannot optimize their strategies or personalize their interactions over time. This rigidity limits their effectiveness and prevents them from achieving true autonomy in complex, real-world scenarios. 是什么: AI 智能体通常在动态且不可预测的环境中运行,在这些环境中预编程逻辑是不够的。当面对初始设计期间未预料到的新情况时,它们的性能可能会下降。没有从经验中学习的能力,智能体无法随时间优化其策略或个性化其交互。这种刚性限制了它们的有效性,并阻止它们在复杂的现实世界场景中实现真正的自主性。 Why: The standardized solution is to integrate learning and adaptation mechanisms, transforming static agents into dynamic, evolving systems. This allows an agent to autonomously refine its knowledge and behaviors based on new data and interactions. Agentic systems can use various methods, from reinforcement learning to more advanced techniques like self-modification, as seen in the Self-Improving Coding Agent (SICA). Advanced systems like Google’s AlphaEvolve leverage LLMs and evolutionary algorithms to discover entirely new and more efficient solutions to complex problems. By continuously learning, agents can master new tasks, enhance their performance, and adapt to changing conditions without requiring constant manual reprogramming. 为什么: 标准化解决方案是集成学习和适应机制,将静态智能体转变为动态的、演化的系统。这使智能体能够基于新数据和交互自主改进其知识和行为。智能体系统可以使用各种方法,从强化学习到更高级的技术,如自我改进编码智能体(SICA)中所见的自我修改。像 Google 的 AlphaEvolve 这样的高级系统利用 LLM 和进化算法来发现全新的、更高效的复杂问题解决方案。通过持续学习,智能体可以掌握新任务、增强其性能并适应变化的条件,而无需持续的手动重新编程。 Rule of thumb: Use this pattern when building agents that must operate in dynamic, uncertain, or evolving environments. It is essential for applications requiring personalization, continuous performance improvement, and the ability to handle novel situations autonomously. 经验法则: 在构建必须在动态、不确定或演化环境中运行的智能体时使用此模式。它对于需要个性化、持续性能改进以及自主处理新情况的能力的应用至关重要。 Visual summary 可视化摘要

Fig.4: Learning and adapting pattern 图 4:学习和适应模式

Key Takeaways

关键要点