@cogitator-ai/ 自我修改
自修剂为相克. 在运行时间进化的代理人——产生出新的工具,调整推理策略,优化自己的架构.
安装
pnpm add @cogitator-ai/self-modifying @cogitator-ai/core
软件包只取决于 @cogitator-ai/types; 代理和 LLM 后端来自 @cogitator-ai/core。网站文件: 自修代理人。 。 。 .
快速启动
import { Agent, OllamaBackend } from '@cogitator-ai/core';
import { SelfModifyingAgent } from '@cogitator-ai/self-modifying';
const llm = new OllamaBackend({ baseUrl: 'http://localhost:11434' });
const agent = new Agent({
name: 'adaptive-assistant',
model: 'ollama/llama3.2',
instructions: 'Solve problems adaptively.',
});
const selfModifying = new SelfModifyingAgent({
agent,
llm,
config: {
toolGeneration: { enabled: true, autoGenerate: true },
metaReasoning: { enabled: true },
architectureEvolution: { enabled: true },
constraints: { enabled: true, autoRollback: true },
},
});
const result = await selfModifying.run('Analyze this CSV and visualize trends');
console.log('Output:', result.output);
console.log('Tools generated:', result.toolsGenerated.length);
console.log('Adaptations made:', result.adaptationsMade.length);
匹配后端的提供者前缀( S)ollama/ 页:1 OllamaBackend)在每次通话前被从代理模型中剥去. 代理商必须设置一个模型. 自行使用的部件(GapAnalyzer, (中文(简体) ), ToolGenerator, (中文(简体) ), ParameterOptimizer,以及 ToolValidator 编号 : CapabilityAnalyzer 当他们调用 LLM 时,将后端预期的模型名称取为 model。所有嵌入式配置段都是部分的——省略字段回到默认值.
代理选项
| 选项 | 说明 |
|---|---|
agent | 要运行的代理(模型、指令、工具、, temperature, (中文(简体) ), maxTokens, (中文(简体) ), maxIterations(中文(简体) ) |
llm | 用于代理和自修改步骤的 LLM 后端 |
config | 部分 SelfModifyingConfig, (中文(简体) ), enabled: false 将包装器变成简单的工具调用代理 |
modificationConstraints | 额外的安全/能力/资源/自定义约束与默认合并 |
availableModels | 模型架构进化可能会切换到,没有它,模型永远不会被改变 |
toolInvoker | 运行工具呼叫像 Cogitator 运行( 批准 , 守护 , 沙盒 , 超时) , 例如您的 Cogitator |
onApproval | 决定需要批准的工具电话,没有人批准的电话被拒绝 |
config.maxInternalTokens 将每个内部LLM调用(gap分析,工具生成和审查,架构演化)的输出符号绑定. 未设置离开后端默认值 。 它不让推理模型 花几分钟在这些步骤上。 梅塔理性有自己的约束, metaReasoning.maxMetaTokens独自使用, GapAnalyzer, (中文(简体) ), ToolGenerator, (中文(简体) ), ToolValidator, (中文(简体) ), CapabilityAnalyzer 财务报告和审定财务报表 ParameterOptimizer 使用与 maxTokens。 。 。 .
运行语义
- 运行序列化:同时进行
run()一次又一次执行. - 经纪人自己的
temperature财务报告和审定财务报表maxTokens构成基线配置. - 工具调用通过
toolInvoker(默认:代理商本人的勾结者,由close())),因此对工具的Zod或JSON schema进行论证,requiresApproval请求通过onApproval(因为援引者guardrails.onToolApproval,否则该呼叫被拒绝,因为自修跑跑不能暂停,护栏应用,沙箱工具运行在沙箱和tool.timeout别动.toolStrategy: 'parallel'(或'adaptive'与不同的工具同时运行. reflectionDepth > 0加上自我审查通过的最后答案.- 当模型返回一个没有被截断的非空的答案时,一个步骤是完整的. Meta 推理只干预(该步骤经过重审,直至
maxAdaptations当一个步骤不完整时.
特征
- 工具自定义 ——检测能力缺失,运行时综合新工具
- Meta- 重构 监测各种模式之间的推理过程和开关(分析、创造性、系统)
- 结构演变 ——利用多武装强盗优化模式,温度,工具策略
- 约束验证 - 安全检查防止不安全的修改
- 回滚系统 ——变更前的检查站,对性能下降进行自动回放
- 事件系统 · 订阅所有可观察性自修改事件
工具自定义
当代理遇到需要它没有能力的任务时,它可以在运行时生成出新的工具.
如何运作
- 差距分析 - LLM 将用户意图和代理指令与可用工具(包括先前生成的工具)进行比较,找出缺失的能力
- 代码合成 - 生成一个简单的Java脚本
execute(params)执行情况、对工具所作所为的说明以及一些实例投入 - 验证 - 静态安全扫描、沙盒中的测试病例、可选LLM审查(见 验证(中文(简体) )
- 约束检查 - 工具必须传递修改限制(沙箱、大小、深度)
- 登记 - 接受的工具被存储为
active,在当前运行中使用,并加载到每次后运行(getGeneratedTools()(列入清单)
配置
const selfModifying = new SelfModifyingAgent({
agent,
llm,
config: {
toolGeneration: {
enabled: true,
autoGenerate: true, // Auto-create tools when gaps detected
maxToolsPerSession: 3, // Limit tools per run
minConfidenceForGeneration: 0.7, // Threshold for generating
maxIterationsPerTool: 3, // Max refinement attempts
requireLLMValidation: true, // LLM validates generated code
sandboxConfig: {
enabled: true,
maxExecutionTime: 5000, // 5s timeout
maxMemory: 50 * 1024 * 1024, // 50MB limit
allowedModules: [], // No external modules
isolationLevel: 'strict',
},
},
},
});
手动工具生成
import { GapAnalyzer, ToolGenerator } from '@cogitator-ai/self-modifying';
const gapAnalyzer = new GapAnalyzer({ llm, config: toolGenConfig, model: 'llama3.2' });
const toolGenerator = new ToolGenerator({ llm, config: toolGenConfig, model: 'llama3.2' });
// Analyze what's missing
const analysis = await gapAnalyzer.analyze(
'Calculate compound interest over 10 years',
existingTools,
{ instructions: agent.instructions }
);
console.log('Gaps found:', analysis.gaps.length);
// Generate tool for each gap
for (const gap of analysis.gaps) {
const result = await toolGenerator.generate(gap, existingTools);
if (result.success && result.tool) {
console.log('Generated:', result.tool.name);
}
}
gapAnalyzer.analyze(input, tools, { instructions }) 显示代理给分析器的指令,所以一个任务需要一个工具来计算(从不计算你自己的校验和)作为一个漏洞. SelfModifyingAgent 传递其代理人的指示.
生成的工具 description 是模型写的关于工具。 当它是空的或只重复空白文本时,空白就是 requiredCapability 被取而代之,因此以后的漏洞分析会发现工具的用途并重新使用. tool.metadata.capability 保持它生成的能力.
验证
ToolValidator.validate(tool, testCases?) 按此顺序分级工具 :
- 静态检查 具有权威性:安全规则被击中(
eval, (中文(简体) ),require, (中文(简体) ),process.,原型技巧, shell 或文件系统访问,没有execute),使工具以0分的分数无效,不管评论怎么说. - 沙盒测试 也具有权威性 : 任何失败的大小写都会使工具无效 。 无
testCases,工具运行在它以(b)项生成的示例输入上metadata.examples符合其参数体系的条目,必须成功)和从体系中合成的输入。 合成输入只证明工具运行,因此接受描述性错误,同时保留需要的参数必须丢出. - LLM 审评 (单位:千美元)
requireLLMValidation)遵循审查员的判决. 与isValid: true财务报告和审定财务报表recommendation: 'approve'(或无)保持该工具的有效性,其安全和逻辑说明保存在suggestions作为Review note (...)条目。 建议的审查revise或者说reject使工具无效,其结果成为securityIssues编号 :logicIssues接下来的重复修正.
overallScore 质量等级: 封存问题降低, 边缘案例和批准的审查笔记降低0.05 , 沙盒通过率为40% .
生成工具存储
import { InMemoryGeneratedToolStore } from '@cogitator-ai/self-modifying';
const store = new InMemoryGeneratedToolStore();
// Save generated tool
await store.save(generatedTool);
// Record usage for learning
await store.recordUsage({
toolId: tool.id,
timestamp: new Date(),
success: true,
executionTime: 150,
});
// List active tools
const tools = await store.list({ status: 'active' });
// Find similar tools
const similar = await store.findSimilar('calculate interest');
沙盒
生成代码运行于 a worker_threads 新鲜的工人 vm 没有主机对象的上下文:否 process, (中文(简体) ), require、定时器或主机构造器,以及字符串代码生成(eval, (中文(简体) ), Function)为已禁用。 参数和结果越出边界,因为JSON,工人有一个空旷的环境,执行的界限是: maxExecutionTime 财务报告和审定财务报表 maxMemory。 。 。 .
import { ToolSandbox } from '@cogitator-ai/self-modifying';
const sandbox = new ToolSandbox({ maxExecutionTime: 2000 });
const result = await sandbox.execute(tool, { a: 1, b: 2 });
const report = await sandbox.testWithCases(tool, [
{ input: { a: 1, b: 2 }, expectedOutput: 3 },
{ input: {}, shouldThrow: true },
{ input: { a: 0, b: 0 }, allowThrow: true },
]);
shouldThrow 只有在工具本身投掷时才能通过; allowThrow 接受结果或抛出的错误,但绝不是超时或崩溃.
快速生成
const tool = await toolGenerator.generateQuick('Double a number', 'double_number', {
value: { type: 'number' },
});
参数在生成时和验证时执行; null 当无法生成有效工具时返回.
Meta- 重构
元推理层监测代理的推理过程并进行战略调整.
原因模式
| 模式 | 温度 | 使用大小写 |
|---|---|---|
analytical | 0.3 (韩语) | 逻辑分析, 调试 |
creative | 0.9 (中文(简体) ) | 集思广益、思想 |
systematic | 0.2 (韩语) | 逐步程序 |
intuitive | 0.6 (中文(简体) ) | 快速决定,休克 |
reflective | 0.4 (中文(简体) ) | 自我评估、学习 |
exploratory | 0.7 (简体中文) | 不限成员名额的勘探 |
配置
import { SelfModifyingAgent } from '@cogitator-ai/self-modifying';
const selfModifying = new SelfModifyingAgent({
agent,
llm,
config: {
metaReasoning: {
enabled: true,
defaultMode: 'analytical',
allowedModes: [
'analytical',
'creative',
'systematic',
'intuitive',
'reflective',
'exploratory',
],
modeProfiles: {
analytical: { temperature: 0.2, depth: 4 }, // other modes and fields keep their defaults
creative: { temperature: 1.0 },
},
maxMetaAssessments: 5, // Max assessments per run
maxAdaptations: 3, // Max mode switches per run
metaAssessmentCooldown: 10000, // 10s between assessments
adaptationCooldown: 15000, // 15s between adaptations
triggers: ['on_failure', 'on_low_confidence', 'periodic'],
triggerAfterIterations: 3, // Assess every 3 iterations
triggerOnConfidenceDrop: 0.3, // Assess if confidence < 30%
triggerOnProgressStall: 2, // Assess after 2 stalled iterations
minConfidenceToAdapt: 0.6, // Min confidence to apply change
enableRollback: true,
rollbackWindow: 30000, // 30s rollback window
rollbackOnDecline: true, // Auto-rollback if metrics decline
},
},
});
modeProfiles 每个模式和每个字段合并 DEFAULT_MODE_PROFILES (对 MetaReasoner是因为 config) (中文(简体) ). mergeModeProfiles(base, overrides) 将您自己的配置文件合并;其覆盖被键入 ModeProfileOverrides。 。 。 .
Meta- Reasoning 进程
- 意见 ——经过不完全的一步后,收集衡量标准(工具成功,信心,符号,时间)
- 触发 - 仅列出触发器
triggers开火(confidence_drop≙on_low_confidence, (中文(简体) ),progress_stall≙on_stagnation, (中文(简体) ),tool_call_failed≙on_failure;明确请求总是如此 - 评估 ——LLM分析推理是否在轨;它的JSON被验证并被丢弃无效值
- 适应 ——切换模式,调整
temperature编号 :depth,或注入额外的上下文;下一次尝试使用它 - 回滚 - 已经
rollbackOnDecline,在下次尝试中没有改进的修改被恢复
直接元 Reasoner 用法
import { MetaReasoner } from '@cogitator-ai/self-modifying';
const metaReasoner = new MetaReasoner({
llm,
model: 'gpt-6.1-sol',
config: metaReasoningConfig,
});
// Initialize run
const modeConfig = metaReasoner.initializeRun(runId);
// Observe current state
const observation = metaReasoner.observe(
{
runId,
iteration: 3,
goal: 'Analyze data',
currentMode: 'analytical',
tokensUsed: 1500,
timeElapsed: 5000,
iterationsRemaining: 7,
budgetRemaining: 0.85, // fraction of the budget left
},
insights
);
// Assess if on-track
const assessment = await metaReasoner.assess(observation);
console.log('On track:', assessment.onTrack);
console.log('Issues:', assessment.issues);
console.log('Recommendation:', assessment.recommendation);
// Apply adaptation if needed
if (assessment.requiresAdaptation) {
const adaptation = await metaReasoner.adapt(runId, assessment);
console.log('Switched to:', adaptation?.after?.mode);
}
// Rollback if needed
const rollback = metaReasoner.rollback(runId);
结构演变
优化代理参数(温度、最大符号、工具策略、反射深度和——何时) availableModels 采用多臂强盗算法。 每跑会记录其实际使用的配置结果(成功,后行,符号,回答自信),因此匪徒会学习横跑. 拟议的LLM候选人被消毒(被夹住的范围被丢弃,型号不明),高风险的LLM标记候选人被丢弃.
战略
| 战略 | 说明 |
|---|---|
ucb | 高信任线——均衡勘探 |
thompson_sampling | 汤普森抽样——概率选择 |
epsilon_greedy | Epsilon-Greedy——随机勘探 |
配置
const selfModifying = new SelfModifyingAgent({
agent,
llm,
config: {
architectureEvolution: {
enabled: true,
strategy: {
type: 'ucb',
explorationConstant: 2, // Higher = more exploration
},
// Or Thompson sampling:
// strategy: { type: 'thompson_sampling' },
// Or epsilon-greedy:
// strategy: { type: 'epsilon_greedy', epsilon: 0.1 },
maxCandidates: 10, // Max configs to track
evaluationWindow: 10, // Evaluations per generation and for convergence metrics
minEvaluationsBeforeEvolution: 3, // Min evaluations per candidate before evolving
adaptationThreshold: 0.1, // Max score gap to the best candidate that is still adopted
},
},
});
参数优化器
import { ParameterOptimizer } from '@cogitator-ai/self-modifying';
const optimizer = new ParameterOptimizer({
llm,
model: 'llama3.2',
config: evolutionConfig,
baseConfig: {
model: 'llama3.2',
temperature: 0.7,
maxTokens: 4096,
toolStrategy: 'sequential',
reflectionDepth: 0,
},
availableModels: ['llama3.2', 'qwen3:8b'],
});
// Optimize for a task
const result = await optimizer.optimize('Complex reasoning task');
console.log('Should adopt:', result.shouldAdopt);
console.log('Confidence:', result.confidence); // mean reward of the candidate, 0.5 if unexplored
console.log('Recommended config:', result.recommendedConfig);
console.log('Task profile:', result.taskProfile);
// Record outcome for learning
await optimizer.recordOutcome(result.candidate!.id, result.taskProfile, {
successRate: 1,
latency: 1200,
tokenUsage: 850,
qualityScore: 0.9,
});
能力分析器
import { CapabilityAnalyzer } from '@cogitator-ai/self-modifying';
const analyzer = new CapabilityAnalyzer({
llm,
enableLLMAnalysis: true,
model: 'llama3.2',
});
const profile = await analyzer.analyzeTask('Build a REST API with authentication');
console.log('Complexity:', profile.complexity); // 'complex'
console.log('Domain:', profile.domain); // 'coding'
console.log('Tool intensity:', profile.toolIntensity); // 'heavy'
console.log('Reasoning depth:', profile.reasoningDepth); // 'deep'
console.log('Estimated tokens:', profile.estimatedTokens);
限制和安全
在适用之前,所有自我修改都经过安全限制的验证.
默认限制
import {
DEFAULT_SAFETY_CONSTRAINTS,
DEFAULT_CAPABILITY_CONSTRAINTS,
DEFAULT_RESOURCE_CONSTRAINTS,
} from '@cogitator-ai/self-modifying';
// Safety (tool_generation / tool_creation requests only, via `appliesTo`):
// - no_arbitrary_code: sandboxExecution = true
// - max_tool_complexity: linesOfCode < 100
// - no_self_modification_loop: modificationDepth < 3
// Capability (tool requests):
// - allowed_tool_categories: math, text, utility, data allowed; system, network, file forbidden; complexity <= 100
// Resource:
// - default_resource_limits: maxTokensPerRun 100000, maxCostPerRun 1.0, maxToolsActive 20
安全规则是对请求的表达 payload (单位:千美元)=, (中文(简体) ), !=, (中文(简体) ), <, (中文(简体) ), <=, (中文(简体) ), >, (中文(简体) ), >=, (中文(简体) ), AND, (中文(简体) ), OR数字, true编号 :false编号 :null 和引用的字符串。 设定 appliesTo 将限制限制限于具体的修改类型;没有限制则适用于每一项请求.
修改验证器
import { ModificationValidator } from '@cogitator-ai/self-modifying';
const validator = new ModificationValidator({
constraints: {
safety: DEFAULT_SAFETY_CONSTRAINTS,
capability: DEFAULT_CAPABILITY_CONSTRAINTS,
resource: DEFAULT_RESOURCE_CONSTRAINTS,
custom: [
{
id: 'no-external-apis',
name: 'No External APIs',
description: 'External API calls not allowed',
predicate: (request) => !JSON.stringify(request.changes).includes('fetch'),
},
],
},
});
const result = await validator.validate({
type: 'tool_creation',
target: 'tools',
changes: { name: 'new-tool', code: '...' },
reason: 'User requested capability',
});
console.log('Valid:', result.valid);
console.log('Warnings:', result.warnings);
console.log('Errors:', result.errors);
回滚管理器
import { RollbackManager } from '@cogitator-ai/self-modifying';
const rollbackManager = new RollbackManager({
maxCheckpoints: 10,
});
// Create checkpoint before modification
const checkpoint = await rollbackManager.createCheckpoint(
agentName,
agentConfig,
currentTools,
modifications
);
console.log('Checkpoint:', checkpoint.id);
// Rollback if something goes wrong
const restored = await rollbackManager.rollbackTo(checkpoint.id);
if (restored) {
console.log('Restored config:', restored.agentConfig);
console.log('Restored tools:', restored.tools.length);
}
// List checkpoints
const checkpoints = await rollbackManager.listCheckpoints(agentName);
活动
订阅自修事件可观察. 每个事件都会打出手牌(SelfModifyingEventDataMap和 on() 返回未订阅的函数.
const selfModifying = new SelfModifyingAgent({ agent, llm, config });
// Tool generation events
selfModifying.on('tool_generation_started', (e) => {
console.log('Generating tool for gap:', e.data.gap.suggestedToolName);
});
selfModifying.on('tool_generation_completed', (e) => {
console.log('Tool created:', e.data.name, 'success:', e.data.success);
});
// Meta-reasoning events
selfModifying.on('meta_assessment', (e) => {
console.log('Assessment:', e.data.assessment.onTrack ? 'on-track' : 'off-track');
});
selfModifying.on('strategy_changed', (e) => {
console.log(`Mode: ${e.data.previousMode} → ${e.data.newMode}`);
});
// Architecture events
selfModifying.on('architecture_evolved', (e) => {
console.log('New config:', e.data.changes);
});
// Checkpoint events
selfModifying.on('checkpoint_created', (e) => {
console.log('Checkpoint:', e.data.checkpointId);
});
selfModifying.on('rollback_performed', (e) => {
console.log('Rolled back to:', e.data.checkpointId);
});
// Run lifecycle
selfModifying.on('run_started', (e) => {
console.log('Run started:', e.runId);
});
const unsubscribe = selfModifying.on('run_completed', (e) => {
console.log('Run completed:', e.data.success);
});
unsubscribe();
事件类型
| 活动 | 说明 |
|---|---|
run_started | 自修改运行已启动 |
run_completed | 运行完成( 成功/ 失败) |
tool_generation_started | 开始生成新工具 |
tool_generation_completed | 工具生成完成 |
meta_assessment | 进行了元理由评估 |
strategy_changed | 更改了原因模式 |
architecture_evolved | 结构配置已更改 |
checkpoint_created | 创建回滚检查站 |
rollback_performed | 滚回检查站 |
公用事业
摘录 Json
从字符串中取出第一个有效的 JSON 对象。 用于解析包含JSON嵌入自然语言的LLM响应.
import { extractJson } from '@cogitator-ai/self-modifying';
const raw = 'Here is my analysis: {"onTrack": true, "confidence": 0.9} end.';
const json = extractJson(raw); // '{"onTrack": true, "confidence": 0.9}'
战斗
使 LLM 后端呼叫正常化的适配器 – 使用 complete() 如果可以的话,请回到 chat()。 。 。 .
import { llmChat } from '@cogitator-ai/self-modifying';
const response = await llmChat(llm, [{ role: 'user', content: 'Analyze this data' }], {
model: 'gpt-6.1-sol',
});
约束合并
合并限制数组, 并用 ID 进行分解 :
import {
mergeSafetyConstraints,
mergeCapabilityConstraints,
mergeResourceConstraints,
mergeCustomConstraints,
} from '@cogitator-ai/self-modifying';
const merged = mergeSafetyConstraints(baseConstraints, overrideConstraints);
检查点倒转( R)
设立检查站,返回安全州.
const selfModifying = new SelfModifyingAgent({ agent, llm, config });
// Run with checkpointing
const result = await selfModifying.run('Complex task...');
// Manual checkpoint during run
selfModifying.on('strategy_changed', async () => {
const checkpoint = await selfModifying.createCheckpoint();
console.log('Saved state:', checkpoint?.id);
});
// Rollback to previous state
const success = await selfModifying.rollbackToCheckpoint(checkpointId);
console.log('Rollback success:', success);
// Get generated tools
const tools = await selfModifying.getGeneratedTools();
console.log('Active tools:', tools.length);
// Record tool usage for learning
await selfModifying.recordToolUsage(toolId, true, 150);
类型参考
核心类型
import type {
SelfModifyingConfig,
ToolSelfGenerationConfig,
MetaReasoningConfig,
ArchitectureEvolutionConfig,
} from '@cogitator-ai/types';
工具生成类型
import type {
CapabilityGap,
GapAnalysisResult,
GeneratedTool,
ToolValidationResult,
ToolSandboxConfig,
ToolSandboxResult,
} from '@cogitator-ai/types';
Meta- Reasoning 类型
import type {
ReasoningMode,
ReasoningModeConfig,
MetaObservation,
MetaAssessment,
MetaAdaptation,
MetaTrigger,
} from '@cogitator-ai/types';
结构进化类型
import type {
TaskProfile,
ArchitectureConfig,
EvolutionCandidate,
EvolutionStrategy,
} from '@cogitator-ai/types';
约束类型
import type {
SafetyConstraint,
CapabilityConstraint,
ResourceConstraint,
ModificationConstraints,
ModificationValidationResult,
ModificationCheckpoint,
} from '@cogitator-ai/types';
事件类型
import type {
SelfModifyingEvent,
SelfModifyingEventType,
SelfModifyingEventHandler,
} from '@cogitator-ai/types';
import type {
SelfModifyingAgentConfig,
SelfModifyingEventDataMap,
TypedSelfModifyingEvent,
} from '@cogitator-ai/self-modifying';
实例
适应性数据分析员
const analyst = new Agent({
name: 'data-analyst',
model: 'ollama/llama3.2',
instructions: 'Analyze data and create visualizations.',
tools: [readFile],
});
const selfModifying = new SelfModifyingAgent({
agent: analyst,
llm,
config: {
toolGeneration: {
enabled: true,
autoGenerate: true,
maxToolsPerSession: 5,
},
metaReasoning: {
enabled: true,
defaultMode: 'analytical',
triggers: ['on_failure', 'periodic'],
},
},
});
// Will auto-generate CSV parser, statistics calculator, chart generator as needed
const result = await selfModifying.run(
'Load sales.csv, calculate monthly trends, and create a bar chart'
);
console.log(
'Generated tools:',
result.toolsGenerated.map((t) => t.name)
);
// ['csv_parser', 'trend_calculator', 'bar_chart_generator']
创意问题解决方案
const solver = new Agent({
name: 'problem-solver',
model: 'ollama/llama3.2',
instructions: 'Find creative solutions to complex problems.',
});
const selfModifying = new SelfModifyingAgent({
agent: solver,
llm,
config: {
metaReasoning: {
enabled: true,
defaultMode: 'systematic',
allowedModes: ['systematic', 'creative', 'analytical'],
triggerOnProgressStall: 2,
},
architectureEvolution: {
enabled: true,
strategy: { type: 'thompson_sampling' },
},
},
});
// Will switch from systematic → creative if stuck
const result = await selfModifying.run(
'Design a novel approach to reduce carbon emissions in cities'
);
console.log('Adaptations:', result.adaptationsMade.length);
console.log('Final config:', result.finalConfig); // temperature, toolStrategy, reflectionDepth, ...
安全码生成器
const coder = new Agent({
name: 'code-generator',
model: 'ollama/llama3.2',
instructions: 'Generate safe, tested code.',
});
const selfModifying = new SelfModifyingAgent({
agent: coder,
llm,
config: {
toolGeneration: {
enabled: true,
sandboxConfig: {
enabled: true,
maxExecutionTime: 3000,
isolationLevel: 'strict',
allowedModules: [],
},
},
constraints: {
enabled: true,
autoRollback: true,
maxModificationsPerRun: 5,
},
},
});
// All generated tools are sandboxed and validated
selfModifying.on('tool_generation_completed', (e) => {
if (!e.data.success) {
console.log('Tool rejected:', e.data.error);
}
});
const result = await selfModifying.run('Create a utility to parse JSON safely');
许可证
麻省理工学院