agentic-context-engine
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAgentic Context Engine (ACE)
Agentic Context Engine(ACE)
Skill by ara.so — AI Agent Skills collection.
ACE is a framework that adds persistent learning capabilities to AI agents. Unlike traditional agents that forget everything between sessions, ACE maintains a Skillbook — a living collection of strategies extracted from execution traces. The framework uses a Recursive Reflector that writes and executes Python code to analyze traces and extract actionable patterns.
由ara.so提供的Skill——AI Agent技能合集。
ACE是一个为AI Agent添加持久学习能力的框架。与会话间会遗忘所有信息的传统Agent不同,ACE维护着一个Skillbook——从执行轨迹中提取的策略集合,是一个动态更新的知识库。该框架使用Recursive Reflector编写并执行Python代码,分析轨迹并提取可落地的模式。
Installation
安装
bash
undefinedbash
undefinedBasic installation
基础安装
uv add ace-framework
uv add ace-framework
With optional integrations
带可选集成
uv add 'ace-framework[browser-use]' # Browser automation
uv add 'ace-framework[langchain]' # LangChain integration
uv add 'ace-framework[logfire]' # Observability
uv add 'ace-framework[mcp]' # MCP server for IDE
uv add 'ace-framework[deduplication]' # Embedding-based deduplication
undefineduv add 'ace-framework[browser-use]' # 浏览器自动化
uv add 'ace-framework[langchain]' # LangChain集成
uv add 'ace-framework[logfire]' # 可观测性
uv add 'ace-framework[mcp]' # IDE用MCP服务器
uv add 'ace-framework[deduplication]' # 基于嵌入的去重
undefinedConfiguration
配置
Interactive setup (recommended):
bash
ace setupOr set environment variables manually:
bash
export OPENAI_API_KEY="your-key-here"交互式设置(推荐):
bash
ace setup或手动设置环境变量:
bash
export OPENAI_API_KEY="你的密钥"OR
或
export ANTHROPIC_API_KEY="your-key-here"
export ANTHROPIC_API_KEY="你的密钥"
Supports 100+ providers via LiteLLM
通过LiteLLM支持100+提供商
undefinedundefinedCore Concepts
核心概念
Skillbook: Persistent collection of learned strategies
Agent: Executes tasks enhanced with Skillbook strategies
Reflector: Analyzes execution traces to extract insights
SkillManager: Curates the Skillbook (adds, refines, removes strategies)
Agent: Executes tasks enhanced with Skillbook strategies
Reflector: Analyzes execution traces to extract insights
SkillManager: Curates the Skillbook (adds, refines, removes strategies)
Skillbook:持久化的已学习策略集合
Agent:结合Skillbook策略执行任务
Reflector:分析执行轨迹提取洞察
SkillManager:管理Skillbook(添加、优化、移除策略)
Agent:结合Skillbook策略执行任务
Reflector:分析执行轨迹提取洞察
SkillManager:管理Skillbook(添加、优化、移除策略)
Quick Start: LiteLLM Runner
快速入门:LiteLLM Runner
The simplest way to add learning to any LLM:
python
from ace import ACELiteLLM为任意LLM添加学习能力的最简方式:
python
from ace import ACELiteLLMInitialize with any LiteLLM model
使用任意LiteLLM模型初始化
agent = ACELiteLLM(model="gpt-4o-mini")
agent = ACELiteLLM(model="gpt-4o-mini")
First attempt - may hallucinate
首次尝试——可能产生幻觉
answer = agent.ask("Is there a seahorse emoji?")
print(answer) # May incorrectly say yes
answer = agent.ask("有没有海马表情?")
print(answer) # 可能错误地回答有
Provide corrective feedback
提供纠正反馈
agent.learn_from_feedback("There is no seahorse emoji in Unicode.")
agent.learn_from_feedback("Unicode中没有海马表情。")
Second attempt - benefits from learned strategy
第二次尝试——受益于已学习策略
answer = agent.ask("Is there a seahorse emoji?")
print(answer) # Now correctly says no
answer = agent.ask("有没有海马表情?")
print(answer) # 现在会正确回答没有
Inspect what was learned
查看已学习内容
strategies = agent.get_strategies()
for strategy in strategies:
print(f"Strategy: {strategy.name}")
print(f"Content: {strategy.content}")
strategies = agent.get_strategies()
for strategy in strategies:
print(f"策略: {strategy.name}")
print(f"内容: {strategy.content}")
Save skillbook for later
保存skillbook供后续使用
agent.save("my_skillbook.json")
agent.save("my_skillbook.json")
Load skillbook in new session
在新会话中加载skillbook
agent = ACELiteLLM(model="gpt-4o-mini", skillbook_path="my_skillbook.json")
undefinedagent = ACELiteLLM(model="gpt-4o-mini", skillbook_path="my_skillbook.json")
undefinedLearning from Existing Traces
从已有轨迹中学习
Extract strategies from pre-recorded execution traces:
python
from ace import ACELiteLLM
agent = ACELiteLLM(model="gpt-4o-mini")从预录制的执行轨迹中提取策略:
python
from ace import ACELiteLLM
agent = ACELiteLLM(model="gpt-4o-mini")Your existing traces (list of conversation histories)
你的已有轨迹(对话历史列表)
traces = [
[
{"role": "user", "content": "What's 2+2?"},
{"role": "assistant", "content": "4"},
],
[
{"role": "user", "content": "What's 3+3?"},
{"role": "assistant", "content": "The answer is 6"},
]
]
traces = [
[
{"role": "user", "content": "2+2等于多少?"},
{"role": "assistant", "content": "4"},
],
[
{"role": "user", "content": "3+3等于多少?"},
{"role": "assistant", "content": "答案是6"},
]
]
Learn from traces without re-running tasks
无需重新运行任务,直接从轨迹中学习
agent.learn_from_traces(traces)
agent.learn_from_traces(traces)
View extracted strategies
查看提取的策略
print(agent.get_strategies())
undefinedprint(agent.get_strategies())
undefinedCore Runner: Full Learning Loop
核心Runner:完整学习循环
For complete control with batch epochs and evaluation:
python
from ace import ACE, Skillbook
from pydantic_ai.models.openai import OpenAIModel用于批量训练周期和评估的全控制模式:
python
from ace import ACE, Skillbook
from pydantic_ai.models.openai import OpenAIModelCreate skillbook and agent
创建skillbook和agent
skillbook = Skillbook()
ace = ACE(
model=OpenAIModel("gpt-4o-mini"),
skillbook=skillbook,
environment=your_env, # Custom environment
max_attempts=3
)
skillbook = Skillbook()
ace = ACE(
model=OpenAIModel("gpt-4o-mini"),
skillbook=skillbook,
environment=your_env, # 自定义环境
max_attempts=3
)
Define your task
定义你的任务
async def my_task():
return "What is the capital of France?"
async def my_task():
return "法国的首都是什么?"
Run learning epoch
运行学习周期
result = await ace.run_epoch(
task=my_task,
task_id="geography_001",
num_iterations=5
)
print(f"Success rate: {result.success_rate}")
print(f"Strategies learned: {len(skillbook.get_all_strategies())}")
undefinedresult = await ace.run_epoch(
task=my_task,
task_id="geography_001",
num_iterations=5
)
print(f"成功率: {result.success_rate}")
print(f"已学习策略数量: {len(skillbook.get_all_strategies())}")
undefinedCustom Agent Integration
自定义Agent集成
Wrap your existing agent with ACE learning:
python
from ace import ACE, Skillbook
from pydantic_ai import Agent为已有Agent添加ACE学习能力:
python
from ace import ACE, Skillbook
from pydantic_ai import AgentYour existing PydanticAI agent
你已有的PydanticAI agent
my_agent = Agent(
model="openai:gpt-4o",
system_prompt="You are a helpful assistant."
)
my_agent = Agent(
model="openai:gpt-4o",
system_prompt="你是一个乐于助人的助手。"
)
Wrap with ACE
用ACE包装
skillbook = Skillbook()
ace_agent = ACE(
agent=my_agent,
skillbook=skillbook,
environment=your_env
)
skillbook = Skillbook()
ace_agent = ACE(
agent=my_agent,
skillbook=skillbook,
environment=your_env
)
Agent now learns from execution
Agent现在会从执行过程中学习
result = await ace_agent.run_epoch(task=your_task)
undefinedresult = await ace_agent.run_epoch(task=your_task)
undefinedBrowser Automation with Learning
带学习能力的浏览器自动化
ACE integrates with browser-use for self-improving browser automation:
python
from ace.runners.browser_use import BrowserUse
from browser_use import Agent as BrowserAgentACE与browser-use集成,实现自我优化的浏览器自动化:
python
from ace.runners.browser_use import BrowserUse
from browser_use import Agent as BrowserAgentCreate browser agent with learning
创建带学习能力的浏览器agent
browser_ace = BrowserUse(
agent=BrowserAgent(
task="Find flights from NYC to LAX",
llm=your_llm
),
skillbook_path="browser_skills.json"
)
browser_ace = BrowserUse(
agent=BrowserAgent(
task="查找从纽约到洛杉矶的航班",
llm=your_llm
),
skillbook_path="browser_skills.json"
)
Run with learning enabled
启用学习后运行
result = await browser_ace.run()
result = await browser_ace.run()
Each run improves the agent
每次运行都会提升agent能力
Strategies are saved to browser_skills.json
策略会保存到browser_skills.json
undefinedundefinedLangChain Integration
LangChain集成
Add learning to any LangChain chain or agent:
python
from ace.runners.langchain import LangChain
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate为任意LangChain链或Agent添加学习能力:
python
from ace.runners.langchain import LangChain
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplateYour existing LangChain setup
你已有的LangChain配置
prompt = PromptTemplate.from_template("Translate {text} to {language}")
chain = LLMChain(llm=your_llm, prompt=prompt)
prompt = PromptTemplate.from_template("将{text}翻译成{language}")
chain = LLMChain(llm=your_llm, prompt=prompt)
Wrap with ACE
用ACE包装
ace_chain = LangChain(
chain=chain,
skillbook_path="translation_skills.json"
)
ace_chain = LangChain(
chain=chain,
skillbook_path="translation_skills.json"
)
Run with learning
启用学习后运行
result = await ace_chain.run(
text="Hello world",
language="Spanish"
)
undefinedresult = await ace_chain.run(
text="Hello world",
language="Spanish"
)
undefinedTrace Analysis
轨迹分析
Analyze traces without re-running tasks:
python
from ace.runners.trace_analyser import TraceAnalyser
analyzer = TraceAnalyser(
model="gpt-4o-mini",
skillbook_path="analyzed_skills.json"
)无需重新运行任务即可分析轨迹:
python
from ace.runners.trace_analyser import TraceAnalyser
analyzer = TraceAnalyser(
model="gpt-4o-mini",
skillbook_path="analyzed_skills.json"
)Analyze a batch of traces
分析一批轨迹
traces = load_your_traces() # List of execution traces
strategies = await analyzer.analyze(traces)
print(f"Extracted {len(strategies)} strategies")
for s in strategies:
print(f"- {s.name}: {s.content}")
undefinedtraces = load_your_traces() # 执行轨迹列表
strategies = await analyzer.analyze(traces)
print(f"提取到{len(strategies)}个策略")
for s in strategies:
print(f"- {s.name}: {s.content}")
undefinedCLI Commands
CLI命令
bash
undefinedbash
undefinedInteractive setup
交互式设置
ace setup
ace setup
Search available models
搜索可用模型
ace models gpt
ace models --provider anthropic
ace models gpt
ace models --provider anthropic
Validate model connection
验证模型连接
ace validate gpt-4o-mini
ace validate claude-3-5-sonnet-20241022
ace validate gpt-4o-mini
ace validate claude-3-5-sonnet-20241022
Show configuration
显示配置
ace config
ace config
Hosted API (requires account at kayba.ai)
托管API(需在kayba.ai注册账号)
kayba login
kayba upload-traces traces.json
kayba fetch-insights
kayba install-prompt my-skill
undefinedkayba login
kayba upload-traces traces.json
kayba fetch-insights
kayba install-prompt my-skill
undefinedCustom Pipeline
自定义流水线
Build custom learning pipelines with composable steps:
python
from ace import Pipeline, AgentStep, EvaluateStep, learning_tail
from ace.core.reflector import Reflector
from ace.core.skill_manager import SkillManager通过可组合步骤构建自定义学习流水线:
python
from ace import Pipeline, AgentStep, EvaluateStep, learning_tail
from ace.core.reflector import Reflector
from ace.core.skill_manager import SkillManagerCreate pipeline components
创建流水线组件
agent_step = AgentStep(agent, skillbook)
eval_step = EvaluateStep(environment)
agent_step = AgentStep(agent, skillbook)
eval_step = EvaluateStep(environment)
Add standard learning tail (reflect + update + deduplicate)
添加标准学习收尾步骤(反思+更新+去重)
reflector = Reflector(model="gpt-4o")
skill_manager = SkillManager(model="gpt-4o")
steps = [
agent_step,
eval_step
] + learning_tail(reflector, skill_manager, skillbook)
reflector = Reflector(model="gpt-4o")
skill_manager = SkillManager(model="gpt-4o-mini")
steps = [
agent_step,
eval_step
] + learning_tail(reflector, skill_manager, skillbook)
Create and run pipeline
创建并运行流水线
pipeline = Pipeline(steps)
context = await pipeline.run({"task": your_task})
print(context.get("strategies_learned"))
undefinedpipeline = Pipeline(steps)
context = await pipeline.run({"task": your_task})
print(context.get("strategies_learned"))
undefinedConfiguration Options
配置选项
Model Selection
模型选择
ACE supports 100+ providers via LiteLLM:
python
undefinedACE通过LiteLLM支持100+提供商:
python
undefinedOpenAI
OpenAI
ACELiteLLM(model="gpt-4o-mini")
ACELiteLLM(model="gpt-4o")
ACELiteLLM(model="gpt-4o-mini")
ACELiteLLM(model="gpt-4o")
Anthropic
Anthropic
ACELiteLLM(model="claude-3-5-sonnet-20241022")
ACELiteLLM(model="claude-3-5-haiku-20241022")
ACELiteLLM(model="claude-3-5-sonnet-20241022")
ACELiteLLM(model="claude-3-5-haiku-20241022")
ACELiteLLM(model="gemini/gemini-2.0-flash-exp")
ACELiteLLM(model="gemini/gemini-2.0-flash-exp")
Local models
本地模型
ACELiteLLM(model="ollama/llama3")
ACELiteLLM(model="ollama/llama3")
Any LiteLLM supported model
任意LiteLLM支持的模型
ACELiteLLM(model="bedrock/anthropic.claude-v2")
undefinedACELiteLLM(model="bedrock/anthropic.claude-v2")
undefinedSkillbook Persistence
Skillbook持久化
python
undefinedpython
undefinedSave skillbook
保存skillbook
agent.save("path/to/skillbook.json")
agent.save("path/to/skillbook.json")
Load skillbook
加载skillbook
agent = ACELiteLLM(
model="gpt-4o-mini",
skillbook_path="path/to/skillbook.json"
)
agent = ACELiteLLM(
model="gpt-4o-mini",
skillbook_path="path/to/skillbook.json"
)
Programmatic access
程序化访问
skillbook = Skillbook()
skillbook.load_from_file("skillbook.json")
strategies = skillbook.get_all_strategies()
skillbook.add_strategy(new_strategy)
skillbook.save_to_file("updated.json")
undefinedskillbook = Skillbook()
skillbook.load_from_file("skillbook.json")
strategies = skillbook.get_all_strategies()
skillbook.add_strategy(new_strategy)
skillbook.save_to_file("updated.json")
undefinedCommon Patterns
常见模式
Pattern 1: Iterative Improvement
模式1:迭代优化
python
from ace import ACELiteLLM
agent = ACELiteLLM(model="gpt-4o-mini")python
from ace import ACELiteLLM
agent = ACELiteLLM(model="gpt-4o-mini")Run task multiple times with feedback
多次运行任务并提供反馈
for attempt in range(5):
result = agent.ask("Complex reasoning task")
# Provide feedback on errors
if not validate(result):
agent.learn_from_feedback(f"Error: {get_error(result)}")
print(f"Attempt {attempt + 1}: {result}")for attempt in range(5):
result = agent.ask("复杂推理任务")
# 针对错误提供反馈
if not validate(result):
agent.learn_from_feedback(f"错误:{get_error(result)}")
print(f"第{attempt + 1}次尝试:{result}")Save learned strategies
保存已学习策略
agent.save("improved_agent.json")
undefinedagent.save("improved_agent.json")
undefinedPattern 2: Multi-Task Learning
模式2:多任务学习
python
from ace import ACELiteLLM
agent = ACELiteLLM(model="gpt-4o-mini")
tasks = [
"Task 1: Data analysis",
"Task 2: Code generation",
"Task 3: Writing"
]
for task in tasks:
result = agent.ask(task)
# Agent accumulates strategies across taskspython
from ace import ACELiteLLM
agent = ACELiteLLM(model="gpt-4o-mini")
tasks = [
"任务1:数据分析",
"任务2:代码生成",
"任务3:写作"
]
for task in tasks:
result = agent.ask(task)
# Agent会跨任务积累策略Single skillbook learns from diverse tasks
单个skillbook从多样化任务中学习
agent.save("multi_task_skills.json")
undefinedagent.save("multi_task_skills.json")
undefinedPattern 3: Batch Trace Analysis
模式3:批量轨迹分析
python
from ace import TraceAnalyserpython
from ace import TraceAnalyserLoad historical traces
加载历史轨迹
traces = load_traces_from_database()
analyzer = TraceAnalyser(model="gpt-4o")
traces = load_traces_from_database()
analyzer = TraceAnalyser(model="gpt-4o")
Extract all strategies at once
一次性提取所有策略
strategies = await analyzer.analyze(traces)
strategies = await analyzer.analyze(traces)
Use in new agent
在新agent中使用
agent = ACELiteLLM(
model="gpt-4o-mini",
skillbook=analyzer.skillbook
)
undefinedagent = ACELiteLLM(
model="gpt-4o-mini",
skillbook=analyzer.skillbook
)
undefinedTroubleshooting
故障排查
API Key Issues
API密钥问题
python
undefinedpython
undefinedVerify configuration
验证配置
import subprocess
result = subprocess.run(["ace", "config"], capture_output=True, text=True)
print(result.stdout)
import subprocess
result = subprocess.run(["ace", "config"], capture_output=True, text=True)
print(result.stdout)
Test connection
测试连接
subprocess.run(["ace", "validate", "gpt-4o-mini"])
undefinedsubprocess.run(["ace", "validate", "gpt-4o-mini"])
undefinedEmpty Skillbook
Skillbook为空
If no strategies are learned:
python
undefined如果没有学习到策略:
python
undefinedCheck if reflector is enabled
检查是否启用了reflector
agent = ACELiteLLM(
model="gpt-4o-mini",
enable_reflection=True # Ensure this is True
)
agent = ACELiteLLM(
model="gpt-4o-mini",
enable_reflection=True # 确保此项为True
)
Provide explicit feedback
提供明确反馈
agent.learn_from_feedback("Specific error description")
agent.learn_from_feedback("具体错误描述")
Verify strategies were added
验证策略是否已添加
print(len(agent.get_strategies()))
undefinedprint(len(agent.get_strategies()))
undefinedPerformance Issues
性能问题
python
undefinedpython
undefinedUse cheaper models for reflection
使用更便宜的模型进行反思
from ace import ACE, Skillbook
from pydantic_ai.models.openai import OpenAIModel
ace = ACE(
model=OpenAIModel("gpt-4o"), # Expensive for main task
reflector_model=OpenAIModel("gpt-4o-mini"), # Cheap for reflection
skillbook=Skillbook()
)
undefinedfrom ace import ACE, Skillbook
from pydantic_ai.models.openai import OpenAIModel
ace = ACE(
model=OpenAIModel("gpt-4o"), # 主任务用昂贵模型
reflector_model=OpenAIModel("gpt-4o-mini"), # 反思用便宜模型
skillbook=Skillbook()
)
undefinedTrace Format Issues
轨迹格式问题
Traces must be in chat format:
python
undefined轨迹必须为聊天格式:
python
undefinedCorrect format
正确格式
valid_trace = [
{"role": "user", "content": "Question"},
{"role": "assistant", "content": "Answer"}
]
valid_trace = [
{"role": "user", "content": "问题"},
{"role": "assistant", "content": "回答"}
]
Learn from properly formatted traces
从格式正确的轨迹中学习
agent.learn_from_traces([valid_trace])
undefinedagent.learn_from_traces([valid_trace])
undefinedAdvanced: Custom Reflector
进阶:自定义Reflector
Customize the reflection process:
python
from ace.core.reflector import Reflector
from ace.core.skill_manager import SkillManager
from ace import Skillbook自定义反思流程:
python
from ace.core.reflector import Reflector
from ace.core.skill_manager import SkillManager
from ace import SkillbookCustom reflector with specific system prompt
带特定系统提示的自定义reflector
reflector = Reflector(
model="gpt-4o",
system_prompt="Focus on error patterns and edge cases"
)
skill_manager = SkillManager(model="gpt-4o-mini")
skillbook = Skillbook()
reflector = Reflector(
model="gpt-4o",
system_prompt="聚焦错误模式和边缘情况"
)
skill_manager = SkillManager(model="gpt-4o-mini")
skillbook = Skillbook()
Use in custom pipeline
在自定义流水线中使用
from ace import Pipeline, learning_tail
pipeline = Pipeline(
learning_tail(reflector, skill_manager, skillbook)
)
undefinedfrom ace import Pipeline, learning_tail
pipeline = Pipeline(
learning_tail(reflector, skill_manager, skillbook)
)
undefinedEnvironment Variables
环境变量
bash
undefinedbash
undefinedRequired (one of):
必填(二选一):
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-ant-...
export GOOGLE_API_KEY=...
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-ant-...
export GOOGLE_API_KEY=...
Optional:
可选:
export ACE_DEFAULT_MODEL=gpt-4o-mini
export ACE_SKILLBOOK_PATH=/path/to/default.json
export ACE_LOG_LEVEL=INFO
export ACE_DEFAULT_MODEL=gpt-4o-mini
export ACE_SKILLBOOK_PATH=/path/to/default.json
export ACE_LOG_LEVEL=INFO
Hosted API (kayba.ai):
托管API(kayba.ai):
export KAYBA_API_KEY=kb-...
undefinedexport KAYBA_API_KEY=kb-...
undefinedResources
资源
- Documentation: https://kayba-ai.github.io/agentic-context-engine/latest/
- Repository: https://github.com/kayba-ai/agentic-context-engine
- Hosted Solution: https://kayba.ai
- Discord: https://discord.gg/mqCqH7sTyK