Repository files navigation

Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models

arXivSlackDiscordAsk DeepWikiFeedback & Interest Form

ACE Framework

🎯 Overview

ACE (Agentic Context Engineering) is a framework that enables large language models to self-improve by treating contexts as evolving playbooks that accumulate, refine, and organize strategies through a modular process of generation, reflection, and curation. Unlike traditional approaches that suffer from brevity bias and context collapse, ACE introduces structured, incremental updates guided by a grow-and-refine principle, preserving detailed, domain-specific knowledge while remaining comprehensive and scalable throughout adaptation.

Latest News

  • 2025 Nov: ACE Paper and Repo says "Hello World"!

Key Features

  • 🔄 Three-Role Agentic Architecture: Generator, Reflector, and Curator work together to continuously improve contexts
  • 📈 Incremental Delta Updates: Localized edits that preserve prior knowledge while accumulating new insights
  • 🎓 Self-Supervised Learning: Adapts effectively without labeled supervision by leveraging natural execution feedback
  • 🚀 High Efficiency: 86.9% lower adaptation latency on average compared to existing adaptive methods
  • 💰 Cost Effective: Significantly fewer rollouts and lower dollar costs while achieving higher accuracy

Tutorials

  • 📚 Adding Dataset for EvaluationLink
  • Extending ACE for Tool Calling (Coming Soon)

📊 Performance

ACE consistently outperforms strong baselines, achieving average gains of +10.6% on agent tasks and +8.6% on domain-specific benchmarks, across both offline and online adaptation settings.

Benchmarks

Task CategoryDatasetImprovementDetails
Agent TasksAppWorld+10.6%Matches top-ranked production-level agent (GPT-4.1) on average and surpasses it on harder test-challenge split, using smaller open-source model
FinanceFiNER + XBRL Formula+8.6%Domain-specific reasoning with structured information extraction

Efficiency Improvements

  • Offline (AppWorld): -82.3% latency and -75.1% rollouts vs GEPA
  • Online (FiNER): -91.5% latency and -83.6% token cost vs Dynamic Cheatsheet

How It Works

  1. Generator produces reasoning trajectories for new queries, surfacing both effective strategies and recurring pitfalls
  2. Reflector separates evaluation and insight extraction from curation, improving context quality
  3. Curator converts lessons into structured delta updates with helpful/harmful counters, using deterministic merging with de-duplication and pruning

This design prevents the context collapse problem where iterative rewriting erodes details over time.

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/ace-agent/ace.git
cd ace
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install ACE and core dependencies
uv sync
# Set up API keys
cp .env.example .env
# Edit .env and set the API key(s) you need

Basic Usage

fromaceimportACEfromutilsimportinitialize_clients# Initialize API clientsapi_provider="sambanova"# or "together", "openai", "commonstack"# Initialize ACE systemace_system=ACE(
api_provider=api_provider,
generator_model="DeepSeek-V3.1",
reflector_model="DeepSeek-V3.1",
curator_model="DeepSeek-V3.1",
max_tokens=4096
)
# Prepare configurationconfig= {
'num_epochs': 1,
'max_num_rounds': 3,
'curator_frequency': 1,
'eval_steps': 100,
'online_eval_frequency': 15,
'save_steps': 50,
'playbook_token_budget': 80000,
'task_name': 'your_task',
'json_mode': False,
'no_ground_truth': False,
'save_dir': './results',
'test_workers': 20,
'use_bulletpoint_analyzer': false,
'api_provider': api_provider
}
# Offline adaptationresults=ace_system.run(
mode='offline',
train_samples=train_data,
val_samples=val_data,
test_samples=test_data, # Optionaldata_processor=processor,
config=config
)
# Online adaptationresults=ace_system.run(
mode='online',
test_samples=test_data,
data_processor=processor,
config=config
)
# Evaluation onlyresults=ace_system.run(
mode='eval_only',
test_samples=test_data,
data_processor=processor,
config=config
)

💼 Finance Domain Example

Training Script Usage

The finance/run.py script provides a unified interface for training and evaluation on financial analysis tasks.

# Offline training (with automatic initial and final testing)
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results
# Online training and testing
uv run python -m eval.finance.run \
--task_name finer \
--mode online \
--save_path results
# Run evaluation on the test split only. Provide a pre-trained playbook or leave initial_playbook_path empty to evaluate an uninitialized playbook.
uv run python -m eval.finance.run \
--task_name finer \
--mode eval_only \
--initial_playbook_path results/ace_run_TIMESTAMP_finer_offline/best_playbook.txt \
--save_path test_results
# Training with custom configuration
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results \
--num_epochs 3 \
--eval_steps 100 \
--max_tokens 4096

Available Arguments

Click here to see available arguments
ArgumentDescriptionDefault
--task_nameTask to train on (e.g., finer, formula)Required
--save_pathDirectory to save resultsRequired
--initial_playbook_pathPath to initial playbookOptional
--modeRun mode: 'offline' for offline training with validation, 'online' for online training and testing on test split, 'eval_only' for evaluation onlyoffline
--api_providerAPI provider for LLM calls. Choose from ['sambanova', 'together', 'openai', 'commonstack']sambanova
--num_epochsNumber of training epochs1
--max_num_roundsMax reflection rounds for incorrect answers3
--curator_frequencyRun curator every N steps1
--eval_stepsEvaluate every N steps100
--online_eval_frequencyUpdate playbook every N samples for evaluation in online mode15
--save_stepsSave intermediate playbooks every N steps50
--max_tokensMaximum tokens for LLM responses4096
--playbook_token_budgetTotal token budget for playbook80000
--test_workersNumber of parallel workers for testing20
--generator_modelModel for generatorDeepSeek-V3.1
--reflector_modelModel for reflectorDeepSeek-V3.1
--curator_modelModel for curatorDeepSeek-V3.1
--json_modeEnable JSON mode for structured outputFalse
--no_ground_truthDon't use ground truth in reflectionFalse
--use_bulletpoint_analyzerEnable bulletpoint analyzer for playbook deduplication and mergingFalse
--bulletpoint_analyzer_thresholdSimilarity threshold for bulletpoint analyzer (0-1)0.9

📈 Results and Outputs

Using offline training as an example, after training, ACE generates:

results/
└── ace_run_TIMESTAMP_finer_offline/
├── run_config.json # Training configuration
├── final_results.json # Consolidated results from all stages
├── initial_test_results.json # Initial test results with empty playbook (baseline)
├── final_test_results.json # Final test results with best playbook
├── train_results.json # Training results
├── val_results.json # Validation results and error logs
├── pre_train_post_train_results.json # Detailed pre-train and post-train generator output for each training sample
├── final_playbook.txt # Final evolved context
├── best_playbook.txt # Best performing context (only for offline training)
├── bullet_usage_log.jsonl # Bullet usage tracking
├── curator_operations_diff.jsonl # Curator operation tracking
├── detailed_llm_logs/ # Detailed LLM call logs
└── intermediate_playbooks/ # Intermediate playbooks 

Understanding Playbook Format

The evolved context (playbook) follows this structure:

## STRATEGIES & INSIGHTS
[str-00001] helpful=5 harmful=0 :: Always verify data types before processing
[str-00002] helpful=3 harmful=1 :: Consider edge cases in financial data
## FORMULAS & CALCULATIONS
[cal-00003] helpful=8 harmful=0 :: NPV = Σ(Cash Flow / (1+r)^t)
## COMMON MISTAKES TO AVOID
[mis-00004] helpful=6 harmful=0 :: Don't forget timezone conversions

Each bullet has:

  • ID: [section_slug-00000] for tracking
  • Counts: helpful=X harmful=Y updated by Reflector
  • Content: :: actual advice or strategy

📬 Supported Tasks

Agent Tasks

  • AppWorld: Simulated digital environment with app interactions

Domain-Specific Tasks

  • FiNER: Financial information extraction
  • XBRL Formula: Structured financial data processing

🛠️ Extending ACE

ACE is designed to be easily extended to new tasks and domains. To add your own task:

  1. Prepare your data: Create JSONL files with train/val/test splits
  2. Implement DataProcessor: Only 3 methods needed - process_task_data(), answer_is_correct(), evaluate_accuracy()
  3. Create training script: Initialize ACE and run training using the run() method
  4. Customize prompts (optional): Adapt prompts to your domain

The evaluation orchestration (parallel test execution, result aggregation) is handled by reusable utilities in utils.py, so you only need to focus on task-specific logic.

Quick Example

classDataProcessor:
defprocess_task_data(self, raw_data):
# Convert your data format to standardized formatreturn [{"context": ..., "question": ..., "target": ..., "others": {...}}]
defanswer_is_correct(self, predicted, ground_truth):
# Your comparison logicreturnpredicted.strip() ==ground_truth.strip()
defevaluate_accuracy(self, predictions, ground_truths):
# Calculate accuracyreturnsum(self.answer_is_correct(p, g) forp, ginzip(predictions, ground_truths)) /len(predictions)

📖 Read the full extension guide →

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Additional Resources

🙏 Acknowledgments

This work builds upon insights from Dynamic Cheatsheet and incorporates ideas from the broader LLM agent and context optimization research community.

📧 Contact

For questions and feedback:


📝 Citation

If you use ACE in your research, please cite our paper:

@misc{zhang2025agenticcontextengineeringevolving,
title={Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models}, author={Qizheng Zhang and Changran Hu and Shubhangi Upasani and Boyuan Ma and Fenglu Hong and Vamsidhar Kamanuru and Jay Rainton and Chen Wu and Mengmeng Ji and Hanchen Li and Urmish Thakker and James Zou and Kunle Olukotun},
year={2025},
eprint={2510.04618},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2510.04618}, }

⭐ Star us on GitHub if ACE helps your research!

Made with ❤️ by the ACE team

About

Evolve your language agent with Agentic Context Engineering (ACE)

Resources

Stars

1.3k stars

Watchers

12 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models

arXivSlackDiscordAsk DeepWikiFeedback & Interest Form

ACE Framework

🎯 Overview

ACE (Agentic Context Engineering) is a framework that enables large language models to self-improve by treating contexts as evolving playbooks that accumulate, refine, and organize strategies through a modular process of generation, reflection, and curation. Unlike traditional approaches that suffer from brevity bias and context collapse, ACE introduces structured, incremental updates guided by a grow-and-refine principle, preserving detailed, domain-specific knowledge while remaining comprehensive and scalable throughout adaptation.

Latest News

  • 2025 Nov: ACE Paper and Repo says "Hello World"!

Key Features

  • 🔄 Three-Role Agentic Architecture: Generator, Reflector, and Curator work together to continuously improve contexts
  • 📈 Incremental Delta Updates: Localized edits that preserve prior knowledge while accumulating new insights
  • 🎓 Self-Supervised Learning: Adapts effectively without labeled supervision by leveraging natural execution feedback
  • 🚀 High Efficiency: 86.9% lower adaptation latency on average compared to existing adaptive methods
  • 💰 Cost Effective: Significantly fewer rollouts and lower dollar costs while achieving higher accuracy

Tutorials

  • 📚 Adding Dataset for EvaluationLink
  • Extending ACE for Tool Calling (Coming Soon)

📊 Performance

ACE consistently outperforms strong baselines, achieving average gains of +10.6% on agent tasks and +8.6% on domain-specific benchmarks, across both offline and online adaptation settings.

Benchmarks

Task CategoryDatasetImprovementDetails
Agent TasksAppWorld+10.6%Matches top-ranked production-level agent (GPT-4.1) on average and surpasses it on harder test-challenge split, using smaller open-source model
FinanceFiNER + XBRL Formula+8.6%Domain-specific reasoning with structured information extraction

Efficiency Improvements

  • Offline (AppWorld): -82.3% latency and -75.1% rollouts vs GEPA
  • Online (FiNER): -91.5% latency and -83.6% token cost vs Dynamic Cheatsheet

How It Works

  1. Generator produces reasoning trajectories for new queries, surfacing both effective strategies and recurring pitfalls
  2. Reflector separates evaluation and insight extraction from curation, improving context quality
  3. Curator converts lessons into structured delta updates with helpful/harmful counters, using deterministic merging with de-duplication and pruning

This design prevents the context collapse problem where iterative rewriting erodes details over time.

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/ace-agent/ace.git
cd ace
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install ACE and core dependencies
uv sync
# Set up API keys
cp .env.example .env
# Edit .env and set the API key(s) you need

Basic Usage

fromaceimportACEfromutilsimportinitialize_clients# Initialize API clientsapi_provider="sambanova"# or "together", "openai", "commonstack"# Initialize ACE systemace_system=ACE(
api_provider=api_provider,
generator_model="DeepSeek-V3.1",
reflector_model="DeepSeek-V3.1",
curator_model="DeepSeek-V3.1",
max_tokens=4096
)
# Prepare configurationconfig= {
'num_epochs': 1,
'max_num_rounds': 3,
'curator_frequency': 1,
'eval_steps': 100,
'online_eval_frequency': 15,
'save_steps': 50,
'playbook_token_budget': 80000,
'task_name': 'your_task',
'json_mode': False,
'no_ground_truth': False,
'save_dir': './results',
'test_workers': 20,
'use_bulletpoint_analyzer': false,
'api_provider': api_provider
}
# Offline adaptationresults=ace_system.run(
mode='offline',
train_samples=train_data,
val_samples=val_data,
test_samples=test_data, # Optionaldata_processor=processor,
config=config
)
# Online adaptationresults=ace_system.run(
mode='online',
test_samples=test_data,
data_processor=processor,
config=config
)
# Evaluation onlyresults=ace_system.run(
mode='eval_only',
test_samples=test_data,
data_processor=processor,
config=config
)

💼 Finance Domain Example

Training Script Usage

The finance/run.py script provides a unified interface for training and evaluation on financial analysis tasks.

# Offline training (with automatic initial and final testing)
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results
# Online training and testing
uv run python -m eval.finance.run \
--task_name finer \
--mode online \
--save_path results
# Run evaluation on the test split only. Provide a pre-trained playbook or leave initial_playbook_path empty to evaluate an uninitialized playbook.
uv run python -m eval.finance.run \
--task_name finer \
--mode eval_only \
--initial_playbook_path results/ace_run_TIMESTAMP_finer_offline/best_playbook.txt \
--save_path test_results
# Training with custom configuration
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results \
--num_epochs 3 \
--eval_steps 100 \
--max_tokens 4096

Available Arguments

Click here to see available arguments
ArgumentDescriptionDefault
--task_nameTask to train on (e.g., finer, formula)Required
--save_pathDirectory to save resultsRequired
--initial_playbook_pathPath to initial playbookOptional
--modeRun mode: 'offline' for offline training with validation, 'online' for online training and testing on test split, 'eval_only' for evaluation onlyoffline
--api_providerAPI provider for LLM calls. Choose from ['sambanova', 'together', 'openai', 'commonstack']sambanova
--num_epochsNumber of training epochs1
--max_num_roundsMax reflection rounds for incorrect answers3
--curator_frequencyRun curator every N steps1
--eval_stepsEvaluate every N steps100
--online_eval_frequencyUpdate playbook every N samples for evaluation in online mode15
--save_stepsSave intermediate playbooks every N steps50
--max_tokensMaximum tokens for LLM responses4096
--playbook_token_budgetTotal token budget for playbook80000
--test_workersNumber of parallel workers for testing20
--generator_modelModel for generatorDeepSeek-V3.1
--reflector_modelModel for reflectorDeepSeek-V3.1
--curator_modelModel for curatorDeepSeek-V3.1
--json_modeEnable JSON mode for structured outputFalse
--no_ground_truthDon't use ground truth in reflectionFalse
--use_bulletpoint_analyzerEnable bulletpoint analyzer for playbook deduplication and mergingFalse
--bulletpoint_analyzer_thresholdSimilarity threshold for bulletpoint analyzer (0-1)0.9

📈 Results and Outputs

Using offline training as an example, after training, ACE generates:

results/
└── ace_run_TIMESTAMP_finer_offline/
├── run_config.json # Training configuration
├── final_results.json # Consolidated results from all stages
├── initial_test_results.json # Initial test results with empty playbook (baseline)
├── final_test_results.json # Final test results with best playbook
├── train_results.json # Training results
├── val_results.json # Validation results and error logs
├── pre_train_post_train_results.json # Detailed pre-train and post-train generator output for each training sample
├── final_playbook.txt # Final evolved context
├── best_playbook.txt # Best performing context (only for offline training)
├── bullet_usage_log.jsonl # Bullet usage tracking
├── curator_operations_diff.jsonl # Curator operation tracking
├── detailed_llm_logs/ # Detailed LLM call logs
└── intermediate_playbooks/ # Intermediate playbooks 

Understanding Playbook Format

The evolved context (playbook) follows this structure:

## STRATEGIES & INSIGHTS
[str-00001] helpful=5 harmful=0 :: Always verify data types before processing
[str-00002] helpful=3 harmful=1 :: Consider edge cases in financial data
## FORMULAS & CALCULATIONS
[cal-00003] helpful=8 harmful=0 :: NPV = Σ(Cash Flow / (1+r)^t)
## COMMON MISTAKES TO AVOID
[mis-00004] helpful=6 harmful=0 :: Don't forget timezone conversions

Each bullet has:

  • ID: [section_slug-00000] for tracking
  • Counts: helpful=X harmful=Y updated by Reflector
  • Content: :: actual advice or strategy

📬 Supported Tasks

Agent Tasks

  • AppWorld: Simulated digital environment with app interactions

Domain-Specific Tasks

  • FiNER: Financial information extraction
  • XBRL Formula: Structured financial data processing

🛠️ Extending ACE

ACE is designed to be easily extended to new tasks and domains. To add your own task:

  1. Prepare your data: Create JSONL files with train/val/test splits
  2. Implement DataProcessor: Only 3 methods needed - process_task_data(), answer_is_correct(), evaluate_accuracy()
  3. Create training script: Initialize ACE and run training using the run() method
  4. Customize prompts (optional): Adapt prompts to your domain

The evaluation orchestration (parallel test execution, result aggregation) is handled by reusable utilities in utils.py, so you only need to focus on task-specific logic.

Quick Example

classDataProcessor:
defprocess_task_data(self, raw_data):
# Convert your data format to standardized formatreturn [{"context": ..., "question": ..., "target": ..., "others": {...}}]
defanswer_is_correct(self, predicted, ground_truth):
# Your comparison logicreturnpredicted.strip() ==ground_truth.strip()
defevaluate_accuracy(self, predictions, ground_truths):
# Calculate accuracyreturnsum(self.answer_is_correct(p, g) forp, ginzip(predictions, ground_truths)) /len(predictions)

📖 Read the full extension guide →

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Additional Resources

🙏 Acknowledgments

This work builds upon insights from Dynamic Cheatsheet and incorporates ideas from the broader LLM agent and context optimization research community.

📧 Contact

For questions and feedback:


📝 Citation

If you use ACE in your research, please cite our paper:

@misc{zhang2025agenticcontextengineeringevolving,
title={Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models}, author={Qizheng Zhang and Changran Hu and Shubhangi Upasani and Boyuan Ma and Fenglu Hong and Vamsidhar Kamanuru and Jay Rainton and Chen Wu and Mengmeng Ji and Hanchen Li and Urmish Thakker and James Zou and Kunle Olukotun},
year={2025},
eprint={2510.04618},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2510.04618}, }

⭐ Star us on GitHub if ACE helps your research!

Made with ❤️ by the ACE team

About

Evolve your language agent with Agentic Context Engineering (ACE)

Resources

Stars

1.3k stars

Watchers

12 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models

arXivSlackDiscordAsk DeepWikiFeedback & Interest Form

ACE Framework

🎯 Overview

ACE (Agentic Context Engineering) is a framework that enables large language models to self-improve by treating contexts as evolving playbooks that accumulate, refine, and organize strategies through a modular process of generation, reflection, and curation. Unlike traditional approaches that suffer from brevity bias and context collapse, ACE introduces structured, incremental updates guided by a grow-and-refine principle, preserving detailed, domain-specific knowledge while remaining comprehensive and scalable throughout adaptation.

Latest News

  • 2025 Nov: ACE Paper and Repo says "Hello World"!

Key Features

  • 🔄 Three-Role Agentic Architecture: Generator, Reflector, and Curator work together to continuously improve contexts
  • 📈 Incremental Delta Updates: Localized edits that preserve prior knowledge while accumulating new insights
  • 🎓 Self-Supervised Learning: Adapts effectively without labeled supervision by leveraging natural execution feedback
  • 🚀 High Efficiency: 86.9% lower adaptation latency on average compared to existing adaptive methods
  • 💰 Cost Effective: Significantly fewer rollouts and lower dollar costs while achieving higher accuracy

Tutorials

  • 📚 Adding Dataset for EvaluationLink
  • Extending ACE for Tool Calling (Coming Soon)

📊 Performance

ACE consistently outperforms strong baselines, achieving average gains of +10.6% on agent tasks and +8.6% on domain-specific benchmarks, across both offline and online adaptation settings.

Benchmarks

Task CategoryDatasetImprovementDetails
Agent TasksAppWorld+10.6%Matches top-ranked production-level agent (GPT-4.1) on average and surpasses it on harder test-challenge split, using smaller open-source model
FinanceFiNER + XBRL Formula+8.6%Domain-specific reasoning with structured information extraction

Efficiency Improvements

  • Offline (AppWorld): -82.3% latency and -75.1% rollouts vs GEPA
  • Online (FiNER): -91.5% latency and -83.6% token cost vs Dynamic Cheatsheet

How It Works

  1. Generator produces reasoning trajectories for new queries, surfacing both effective strategies and recurring pitfalls
  2. Reflector separates evaluation and insight extraction from curation, improving context quality
  3. Curator converts lessons into structured delta updates with helpful/harmful counters, using deterministic merging with de-duplication and pruning

This design prevents the context collapse problem where iterative rewriting erodes details over time.

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/ace-agent/ace.git
cd ace
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install ACE and core dependencies
uv sync
# Set up API keys
cp .env.example .env
# Edit .env and set the API key(s) you need

Basic Usage

fromaceimportACEfromutilsimportinitialize_clients# Initialize API clientsapi_provider="sambanova"# or "together", "openai", "commonstack"# Initialize ACE systemace_system=ACE(
api_provider=api_provider,
generator_model="DeepSeek-V3.1",
reflector_model="DeepSeek-V3.1",
curator_model="DeepSeek-V3.1",
max_tokens=4096
)
# Prepare configurationconfig= {
'num_epochs': 1,
'max_num_rounds': 3,
'curator_frequency': 1,
'eval_steps': 100,
'online_eval_frequency': 15,
'save_steps': 50,
'playbook_token_budget': 80000,
'task_name': 'your_task',
'json_mode': False,
'no_ground_truth': False,
'save_dir': './results',
'test_workers': 20,
'use_bulletpoint_analyzer': false,
'api_provider': api_provider
}
# Offline adaptationresults=ace_system.run(
mode='offline',
train_samples=train_data,
val_samples=val_data,
test_samples=test_data, # Optionaldata_processor=processor,
config=config
)
# Online adaptationresults=ace_system.run(
mode='online',
test_samples=test_data,
data_processor=processor,
config=config
)
# Evaluation onlyresults=ace_system.run(
mode='eval_only',
test_samples=test_data,
data_processor=processor,
config=config
)

💼 Finance Domain Example

Training Script Usage

The finance/run.py script provides a unified interface for training and evaluation on financial analysis tasks.

# Offline training (with automatic initial and final testing)
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results
# Online training and testing
uv run python -m eval.finance.run \
--task_name finer \
--mode online \
--save_path results
# Run evaluation on the test split only. Provide a pre-trained playbook or leave initial_playbook_path empty to evaluate an uninitialized playbook.
uv run python -m eval.finance.run \
--task_name finer \
--mode eval_only \
--initial_playbook_path results/ace_run_TIMESTAMP_finer_offline/best_playbook.txt \
--save_path test_results
# Training with custom configuration
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results \
--num_epochs 3 \
--eval_steps 100 \
--max_tokens 4096

Available Arguments

Click here to see available arguments
ArgumentDescriptionDefault
--task_nameTask to train on (e.g., finer, formula)Required
--save_pathDirectory to save resultsRequired
--initial_playbook_pathPath to initial playbookOptional
--modeRun mode: 'offline' for offline training with validation, 'online' for online training and testing on test split, 'eval_only' for evaluation onlyoffline
--api_providerAPI provider for LLM calls. Choose from ['sambanova', 'together', 'openai', 'commonstack']sambanova
--num_epochsNumber of training epochs1
--max_num_roundsMax reflection rounds for incorrect answers3
--curator_frequencyRun curator every N steps1
--eval_stepsEvaluate every N steps100
--online_eval_frequencyUpdate playbook every N samples for evaluation in online mode15
--save_stepsSave intermediate playbooks every N steps50
--max_tokensMaximum tokens for LLM responses4096
--playbook_token_budgetTotal token budget for playbook80000
--test_workersNumber of parallel workers for testing20
--generator_modelModel for generatorDeepSeek-V3.1
--reflector_modelModel for reflectorDeepSeek-V3.1
--curator_modelModel for curatorDeepSeek-V3.1
--json_modeEnable JSON mode for structured outputFalse
--no_ground_truthDon't use ground truth in reflectionFalse
--use_bulletpoint_analyzerEnable bulletpoint analyzer for playbook deduplication and mergingFalse
--bulletpoint_analyzer_thresholdSimilarity threshold for bulletpoint analyzer (0-1)0.9

📈 Results and Outputs

Using offline training as an example, after training, ACE generates:

results/
└── ace_run_TIMESTAMP_finer_offline/
├── run_config.json # Training configuration
├── final_results.json # Consolidated results from all stages
├── initial_test_results.json # Initial test results with empty playbook (baseline)
├── final_test_results.json # Final test results with best playbook
├── train_results.json # Training results
├── val_results.json # Validation results and error logs
├── pre_train_post_train_results.json # Detailed pre-train and post-train generator output for each training sample
├── final_playbook.txt # Final evolved context
├── best_playbook.txt # Best performing context (only for offline training)
├── bullet_usage_log.jsonl # Bullet usage tracking
├── curator_operations_diff.jsonl # Curator operation tracking
├── detailed_llm_logs/ # Detailed LLM call logs
└── intermediate_playbooks/ # Intermediate playbooks 

Understanding Playbook Format

The evolved context (playbook) follows this structure:

## STRATEGIES & INSIGHTS
[str-00001] helpful=5 harmful=0 :: Always verify data types before processing
[str-00002] helpful=3 harmful=1 :: Consider edge cases in financial data
## FORMULAS & CALCULATIONS
[cal-00003] helpful=8 harmful=0 :: NPV = Σ(Cash Flow / (1+r)^t)
## COMMON MISTAKES TO AVOID
[mis-00004] helpful=6 harmful=0 :: Don't forget timezone conversions

Each bullet has:

  • ID: [section_slug-00000] for tracking
  • Counts: helpful=X harmful=Y updated by Reflector
  • Content: :: actual advice or strategy

📬 Supported Tasks

Agent Tasks

  • AppWorld: Simulated digital environment with app interactions

Domain-Specific Tasks

  • FiNER: Financial information extraction
  • XBRL Formula: Structured financial data processing

🛠️ Extending ACE

ACE is designed to be easily extended to new tasks and domains. To add your own task:

  1. Prepare your data: Create JSONL files with train/val/test splits
  2. Implement DataProcessor: Only 3 methods needed - process_task_data(), answer_is_correct(), evaluate_accuracy()
  3. Create training script: Initialize ACE and run training using the run() method
  4. Customize prompts (optional): Adapt prompts to your domain

The evaluation orchestration (parallel test execution, result aggregation) is handled by reusable utilities in utils.py, so you only need to focus on task-specific logic.

Quick Example

classDataProcessor:
defprocess_task_data(self, raw_data):
# Convert your data format to standardized formatreturn [{"context": ..., "question": ..., "target": ..., "others": {...}}]
defanswer_is_correct(self, predicted, ground_truth):
# Your comparison logicreturnpredicted.strip() ==ground_truth.strip()
defevaluate_accuracy(self, predictions, ground_truths):
# Calculate accuracyreturnsum(self.answer_is_correct(p, g) forp, ginzip(predictions, ground_truths)) /len(predictions)

📖 Read the full extension guide →

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Additional Resources

🙏 Acknowledgments

This work builds upon insights from Dynamic Cheatsheet and incorporates ideas from the broader LLM agent and context optimization research community.

📧 Contact

For questions and feedback:


📝 Citation

If you use ACE in your research, please cite our paper:

@misc{zhang2025agenticcontextengineeringevolving,
title={Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models}, author={Qizheng Zhang and Changran Hu and Shubhangi Upasani and Boyuan Ma and Fenglu Hong and Vamsidhar Kamanuru and Jay Rainton and Chen Wu and Mengmeng Ji and Hanchen Li and Urmish Thakker and James Zou and Kunle Olukotun},
year={2025},
eprint={2510.04618},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2510.04618}, }

⭐ Star us on GitHub if ACE helps your research!

Made with ❤️ by the ACE team

About

Evolve your language agent with Agentic Context Engineering (ACE)

Resources

Stars

1.3k stars

Watchers

12 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models

arXivSlackDiscordAsk DeepWikiFeedback & Interest Form

ACE Framework

🎯 Overview

ACE (Agentic Context Engineering) is a framework that enables large language models to self-improve by treating contexts as evolving playbooks that accumulate, refine, and organize strategies through a modular process of generation, reflection, and curation. Unlike traditional approaches that suffer from brevity bias and context collapse, ACE introduces structured, incremental updates guided by a grow-and-refine principle, preserving detailed, domain-specific knowledge while remaining comprehensive and scalable throughout adaptation.

Latest News

  • 2025 Nov: ACE Paper and Repo says "Hello World"!

Key Features

  • 🔄 Three-Role Agentic Architecture: Generator, Reflector, and Curator work together to continuously improve contexts
  • 📈 Incremental Delta Updates: Localized edits that preserve prior knowledge while accumulating new insights
  • 🎓 Self-Supervised Learning: Adapts effectively without labeled supervision by leveraging natural execution feedback
  • 🚀 High Efficiency: 86.9% lower adaptation latency on average compared to existing adaptive methods
  • 💰 Cost Effective: Significantly fewer rollouts and lower dollar costs while achieving higher accuracy

Tutorials

  • 📚 Adding Dataset for EvaluationLink
  • Extending ACE for Tool Calling (Coming Soon)

📊 Performance

ACE consistently outperforms strong baselines, achieving average gains of +10.6% on agent tasks and +8.6% on domain-specific benchmarks, across both offline and online adaptation settings.

Benchmarks

Task CategoryDatasetImprovementDetails
Agent TasksAppWorld+10.6%Matches top-ranked production-level agent (GPT-4.1) on average and surpasses it on harder test-challenge split, using smaller open-source model
FinanceFiNER + XBRL Formula+8.6%Domain-specific reasoning with structured information extraction

Efficiency Improvements

  • Offline (AppWorld): -82.3% latency and -75.1% rollouts vs GEPA
  • Online (FiNER): -91.5% latency and -83.6% token cost vs Dynamic Cheatsheet

How It Works

  1. Generator produces reasoning trajectories for new queries, surfacing both effective strategies and recurring pitfalls
  2. Reflector separates evaluation and insight extraction from curation, improving context quality
  3. Curator converts lessons into structured delta updates with helpful/harmful counters, using deterministic merging with de-duplication and pruning

This design prevents the context collapse problem where iterative rewriting erodes details over time.

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/ace-agent/ace.git
cd ace
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install ACE and core dependencies
uv sync
# Set up API keys
cp .env.example .env
# Edit .env and set the API key(s) you need

Basic Usage

fromaceimportACEfromutilsimportinitialize_clients# Initialize API clientsapi_provider="sambanova"# or "together", "openai", "commonstack"# Initialize ACE systemace_system=ACE(
api_provider=api_provider,
generator_model="DeepSeek-V3.1",
reflector_model="DeepSeek-V3.1",
curator_model="DeepSeek-V3.1",
max_tokens=4096
)
# Prepare configurationconfig= {
'num_epochs': 1,
'max_num_rounds': 3,
'curator_frequency': 1,
'eval_steps': 100,
'online_eval_frequency': 15,
'save_steps': 50,
'playbook_token_budget': 80000,
'task_name': 'your_task',
'json_mode': False,
'no_ground_truth': False,
'save_dir': './results',
'test_workers': 20,
'use_bulletpoint_analyzer': false,
'api_provider': api_provider
}
# Offline adaptationresults=ace_system.run(
mode='offline',
train_samples=train_data,
val_samples=val_data,
test_samples=test_data, # Optionaldata_processor=processor,
config=config
)
# Online adaptationresults=ace_system.run(
mode='online',
test_samples=test_data,
data_processor=processor,
config=config
)
# Evaluation onlyresults=ace_system.run(
mode='eval_only',
test_samples=test_data,
data_processor=processor,
config=config
)

💼 Finance Domain Example

Training Script Usage

The finance/run.py script provides a unified interface for training and evaluation on financial analysis tasks.

# Offline training (with automatic initial and final testing)
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results
# Online training and testing
uv run python -m eval.finance.run \
--task_name finer \
--mode online \
--save_path results
# Run evaluation on the test split only. Provide a pre-trained playbook or leave initial_playbook_path empty to evaluate an uninitialized playbook.
uv run python -m eval.finance.run \
--task_name finer \
--mode eval_only \
--initial_playbook_path results/ace_run_TIMESTAMP_finer_offline/best_playbook.txt \
--save_path test_results
# Training with custom configuration
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results \
--num_epochs 3 \
--eval_steps 100 \
--max_tokens 4096

Available Arguments

Click here to see available arguments
ArgumentDescriptionDefault
--task_nameTask to train on (e.g., finer, formula)Required
--save_pathDirectory to save resultsRequired
--initial_playbook_pathPath to initial playbookOptional
--modeRun mode: 'offline' for offline training with validation, 'online' for online training and testing on test split, 'eval_only' for evaluation onlyoffline
--api_providerAPI provider for LLM calls. Choose from ['sambanova', 'together', 'openai', 'commonstack']sambanova
--num_epochsNumber of training epochs1
--max_num_roundsMax reflection rounds for incorrect answers3
--curator_frequencyRun curator every N steps1
--eval_stepsEvaluate every N steps100
--online_eval_frequencyUpdate playbook every N samples for evaluation in online mode15
--save_stepsSave intermediate playbooks every N steps50
--max_tokensMaximum tokens for LLM responses4096
--playbook_token_budgetTotal token budget for playbook80000
--test_workersNumber of parallel workers for testing20
--generator_modelModel for generatorDeepSeek-V3.1
--reflector_modelModel for reflectorDeepSeek-V3.1
--curator_modelModel for curatorDeepSeek-V3.1
--json_modeEnable JSON mode for structured outputFalse
--no_ground_truthDon't use ground truth in reflectionFalse
--use_bulletpoint_analyzerEnable bulletpoint analyzer for playbook deduplication and mergingFalse
--bulletpoint_analyzer_thresholdSimilarity threshold for bulletpoint analyzer (0-1)0.9

📈 Results and Outputs

Using offline training as an example, after training, ACE generates:

results/
└── ace_run_TIMESTAMP_finer_offline/
├── run_config.json # Training configuration
├── final_results.json # Consolidated results from all stages
├── initial_test_results.json # Initial test results with empty playbook (baseline)
├── final_test_results.json # Final test results with best playbook
├── train_results.json # Training results
├── val_results.json # Validation results and error logs
├── pre_train_post_train_results.json # Detailed pre-train and post-train generator output for each training sample
├── final_playbook.txt # Final evolved context
├── best_playbook.txt # Best performing context (only for offline training)
├── bullet_usage_log.jsonl # Bullet usage tracking
├── curator_operations_diff.jsonl # Curator operation tracking
├── detailed_llm_logs/ # Detailed LLM call logs
└── intermediate_playbooks/ # Intermediate playbooks 

Understanding Playbook Format

The evolved context (playbook) follows this structure:

## STRATEGIES & INSIGHTS
[str-00001] helpful=5 harmful=0 :: Always verify data types before processing
[str-00002] helpful=3 harmful=1 :: Consider edge cases in financial data
## FORMULAS & CALCULATIONS
[cal-00003] helpful=8 harmful=0 :: NPV = Σ(Cash Flow / (1+r)^t)
## COMMON MISTAKES TO AVOID
[mis-00004] helpful=6 harmful=0 :: Don't forget timezone conversions

Each bullet has:

  • ID: [section_slug-00000] for tracking
  • Counts: helpful=X harmful=Y updated by Reflector
  • Content: :: actual advice or strategy

📬 Supported Tasks

Agent Tasks

  • AppWorld: Simulated digital environment with app interactions

Domain-Specific Tasks

  • FiNER: Financial information extraction
  • XBRL Formula: Structured financial data processing

🛠️ Extending ACE

ACE is designed to be easily extended to new tasks and domains. To add your own task:

  1. Prepare your data: Create JSONL files with train/val/test splits
  2. Implement DataProcessor: Only 3 methods needed - process_task_data(), answer_is_correct(), evaluate_accuracy()
  3. Create training script: Initialize ACE and run training using the run() method
  4. Customize prompts (optional): Adapt prompts to your domain

The evaluation orchestration (parallel test execution, result aggregation) is handled by reusable utilities in utils.py, so you only need to focus on task-specific logic.

Quick Example

classDataProcessor:
defprocess_task_data(self, raw_data):
# Convert your data format to standardized formatreturn [{"context": ..., "question": ..., "target": ..., "others": {...}}]
defanswer_is_correct(self, predicted, ground_truth):
# Your comparison logicreturnpredicted.strip() ==ground_truth.strip()
defevaluate_accuracy(self, predictions, ground_truths):
# Calculate accuracyreturnsum(self.answer_is_correct(p, g) forp, ginzip(predictions, ground_truths)) /len(predictions)

📖 Read the full extension guide →

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Additional Resources

🙏 Acknowledgments

This work builds upon insights from Dynamic Cheatsheet and incorporates ideas from the broader LLM agent and context optimization research community.

📧 Contact

For questions and feedback:


📝 Citation

If you use ACE in your research, please cite our paper:

@misc{zhang2025agenticcontextengineeringevolving,
title={Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models}, author={Qizheng Zhang and Changran Hu and Shubhangi Upasani and Boyuan Ma and Fenglu Hong and Vamsidhar Kamanuru and Jay Rainton and Chen Wu and Mengmeng Ji and Hanchen Li and Urmish Thakker and James Zou and Kunle Olukotun},
year={2025},
eprint={2510.04618},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2510.04618}, }

⭐ Star us on GitHub if ACE helps your research!

Made with ❤️ by the ACE team

About

Evolve your language agent with Agentic Context Engineering (ACE)

Resources

Stars

1.3k stars

Watchers

12 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models

arXivSlackDiscordAsk DeepWikiFeedback & Interest Form

ACE Framework

🎯 Overview

ACE (Agentic Context Engineering) is a framework that enables large language models to self-improve by treating contexts as evolving playbooks that accumulate, refine, and organize strategies through a modular process of generation, reflection, and curation. Unlike traditional approaches that suffer from brevity bias and context collapse, ACE introduces structured, incremental updates guided by a grow-and-refine principle, preserving detailed, domain-specific knowledge while remaining comprehensive and scalable throughout adaptation.

Latest News

  • 2025 Nov: ACE Paper and Repo says "Hello World"!

Key Features

  • 🔄 Three-Role Agentic Architecture: Generator, Reflector, and Curator work together to continuously improve contexts
  • 📈 Incremental Delta Updates: Localized edits that preserve prior knowledge while accumulating new insights
  • 🎓 Self-Supervised Learning: Adapts effectively without labeled supervision by leveraging natural execution feedback
  • 🚀 High Efficiency: 86.9% lower adaptation latency on average compared to existing adaptive methods
  • 💰 Cost Effective: Significantly fewer rollouts and lower dollar costs while achieving higher accuracy

Tutorials

  • 📚 Adding Dataset for EvaluationLink
  • Extending ACE for Tool Calling (Coming Soon)

📊 Performance

ACE consistently outperforms strong baselines, achieving average gains of +10.6% on agent tasks and +8.6% on domain-specific benchmarks, across both offline and online adaptation settings.

Benchmarks

Task CategoryDatasetImprovementDetails
Agent TasksAppWorld+10.6%Matches top-ranked production-level agent (GPT-4.1) on average and surpasses it on harder test-challenge split, using smaller open-source model
FinanceFiNER + XBRL Formula+8.6%Domain-specific reasoning with structured information extraction

Efficiency Improvements

  • Offline (AppWorld): -82.3% latency and -75.1% rollouts vs GEPA
  • Online (FiNER): -91.5% latency and -83.6% token cost vs Dynamic Cheatsheet

How It Works

  1. Generator produces reasoning trajectories for new queries, surfacing both effective strategies and recurring pitfalls
  2. Reflector separates evaluation and insight extraction from curation, improving context quality
  3. Curator converts lessons into structured delta updates with helpful/harmful counters, using deterministic merging with de-duplication and pruning

This design prevents the context collapse problem where iterative rewriting erodes details over time.

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/ace-agent/ace.git
cd ace
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install ACE and core dependencies
uv sync
# Set up API keys
cp .env.example .env
# Edit .env and set the API key(s) you need

Basic Usage

fromaceimportACEfromutilsimportinitialize_clients# Initialize API clientsapi_provider="sambanova"# or "together", "openai", "commonstack"# Initialize ACE systemace_system=ACE(
api_provider=api_provider,
generator_model="DeepSeek-V3.1",
reflector_model="DeepSeek-V3.1",
curator_model="DeepSeek-V3.1",
max_tokens=4096
)
# Prepare configurationconfig= {
'num_epochs': 1,
'max_num_rounds': 3,
'curator_frequency': 1,
'eval_steps': 100,
'online_eval_frequency': 15,
'save_steps': 50,
'playbook_token_budget': 80000,
'task_name': 'your_task',
'json_mode': False,
'no_ground_truth': False,
'save_dir': './results',
'test_workers': 20,
'use_bulletpoint_analyzer': false,
'api_provider': api_provider
}
# Offline adaptationresults=ace_system.run(
mode='offline',
train_samples=train_data,
val_samples=val_data,
test_samples=test_data, # Optionaldata_processor=processor,
config=config
)
# Online adaptationresults=ace_system.run(
mode='online',
test_samples=test_data,
data_processor=processor,
config=config
)
# Evaluation onlyresults=ace_system.run(
mode='eval_only',
test_samples=test_data,
data_processor=processor,
config=config
)

💼 Finance Domain Example

Training Script Usage

The finance/run.py script provides a unified interface for training and evaluation on financial analysis tasks.

# Offline training (with automatic initial and final testing)
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results
# Online training and testing
uv run python -m eval.finance.run \
--task_name finer \
--mode online \
--save_path results
# Run evaluation on the test split only. Provide a pre-trained playbook or leave initial_playbook_path empty to evaluate an uninitialized playbook.
uv run python -m eval.finance.run \
--task_name finer \
--mode eval_only \
--initial_playbook_path results/ace_run_TIMESTAMP_finer_offline/best_playbook.txt \
--save_path test_results
# Training with custom configuration
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results \
--num_epochs 3 \
--eval_steps 100 \
--max_tokens 4096

Available Arguments

Click here to see available arguments
ArgumentDescriptionDefault
--task_nameTask to train on (e.g., finer, formula)Required
--save_pathDirectory to save resultsRequired
--initial_playbook_pathPath to initial playbookOptional
--modeRun mode: 'offline' for offline training with validation, 'online' for online training and testing on test split, 'eval_only' for evaluation onlyoffline
--api_providerAPI provider for LLM calls. Choose from ['sambanova', 'together', 'openai', 'commonstack']sambanova
--num_epochsNumber of training epochs1
--max_num_roundsMax reflection rounds for incorrect answers3
--curator_frequencyRun curator every N steps1
--eval_stepsEvaluate every N steps100
--online_eval_frequencyUpdate playbook every N samples for evaluation in online mode15
--save_stepsSave intermediate playbooks every N steps50
--max_tokensMaximum tokens for LLM responses4096
--playbook_token_budgetTotal token budget for playbook80000
--test_workersNumber of parallel workers for testing20
--generator_modelModel for generatorDeepSeek-V3.1
--reflector_modelModel for reflectorDeepSeek-V3.1
--curator_modelModel for curatorDeepSeek-V3.1
--json_modeEnable JSON mode for structured outputFalse
--no_ground_truthDon't use ground truth in reflectionFalse
--use_bulletpoint_analyzerEnable bulletpoint analyzer for playbook deduplication and mergingFalse
--bulletpoint_analyzer_thresholdSimilarity threshold for bulletpoint analyzer (0-1)0.9

📈 Results and Outputs

Using offline training as an example, after training, ACE generates:

results/
└── ace_run_TIMESTAMP_finer_offline/
├── run_config.json # Training configuration
├── final_results.json # Consolidated results from all stages
├── initial_test_results.json # Initial test results with empty playbook (baseline)
├── final_test_results.json # Final test results with best playbook
├── train_results.json # Training results
├── val_results.json # Validation results and error logs
├── pre_train_post_train_results.json # Detailed pre-train and post-train generator output for each training sample
├── final_playbook.txt # Final evolved context
├── best_playbook.txt # Best performing context (only for offline training)
├── bullet_usage_log.jsonl # Bullet usage tracking
├── curator_operations_diff.jsonl # Curator operation tracking
├── detailed_llm_logs/ # Detailed LLM call logs
└── intermediate_playbooks/ # Intermediate playbooks 

Understanding Playbook Format

The evolved context (playbook) follows this structure:

## STRATEGIES & INSIGHTS
[str-00001] helpful=5 harmful=0 :: Always verify data types before processing
[str-00002] helpful=3 harmful=1 :: Consider edge cases in financial data
## FORMULAS & CALCULATIONS
[cal-00003] helpful=8 harmful=0 :: NPV = Σ(Cash Flow / (1+r)^t)
## COMMON MISTAKES TO AVOID
[mis-00004] helpful=6 harmful=0 :: Don't forget timezone conversions

Each bullet has:

  • ID: [section_slug-00000] for tracking
  • Counts: helpful=X harmful=Y updated by Reflector
  • Content: :: actual advice or strategy

📬 Supported Tasks

Agent Tasks

  • AppWorld: Simulated digital environment with app interactions

Domain-Specific Tasks

  • FiNER: Financial information extraction
  • XBRL Formula: Structured financial data processing

🛠️ Extending ACE

ACE is designed to be easily extended to new tasks and domains. To add your own task:

  1. Prepare your data: Create JSONL files with train/val/test splits
  2. Implement DataProcessor: Only 3 methods needed - process_task_data(), answer_is_correct(), evaluate_accuracy()
  3. Create training script: Initialize ACE and run training using the run() method
  4. Customize prompts (optional): Adapt prompts to your domain

The evaluation orchestration (parallel test execution, result aggregation) is handled by reusable utilities in utils.py, so you only need to focus on task-specific logic.

Quick Example

classDataProcessor:
defprocess_task_data(self, raw_data):
# Convert your data format to standardized formatreturn [{"context": ..., "question": ..., "target": ..., "others": {...}}]
defanswer_is_correct(self, predicted, ground_truth):
# Your comparison logicreturnpredicted.strip() ==ground_truth.strip()
defevaluate_accuracy(self, predictions, ground_truths):
# Calculate accuracyreturnsum(self.answer_is_correct(p, g) forp, ginzip(predictions, ground_truths)) /len(predictions)

📖 Read the full extension guide →

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Additional Resources

🙏 Acknowledgments

This work builds upon insights from Dynamic Cheatsheet and incorporates ideas from the broader LLM agent and context optimization research community.

📧 Contact

For questions and feedback:


📝 Citation

If you use ACE in your research, please cite our paper:

@misc{zhang2025agenticcontextengineeringevolving,
title={Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models}, author={Qizheng Zhang and Changran Hu and Shubhangi Upasani and Boyuan Ma and Fenglu Hong and Vamsidhar Kamanuru and Jay Rainton and Chen Wu and Mengmeng Ji and Hanchen Li and Urmish Thakker and James Zou and Kunle Olukotun},
year={2025},
eprint={2510.04618},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2510.04618}, }

⭐ Star us on GitHub if ACE helps your research!

Made with ❤️ by the ACE team

About

Evolve your language agent with Agentic Context Engineering (ACE)

Resources

Stars

1.3k stars

Watchers

12 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models

arXivSlackDiscordAsk DeepWikiFeedback & Interest Form

ACE Framework

🎯 Overview

ACE (Agentic Context Engineering) is a framework that enables large language models to self-improve by treating contexts as evolving playbooks that accumulate, refine, and organize strategies through a modular process of generation, reflection, and curation. Unlike traditional approaches that suffer from brevity bias and context collapse, ACE introduces structured, incremental updates guided by a grow-and-refine principle, preserving detailed, domain-specific knowledge while remaining comprehensive and scalable throughout adaptation.

Latest News

  • 2025 Nov: ACE Paper and Repo says "Hello World"!

Key Features

  • 🔄 Three-Role Agentic Architecture: Generator, Reflector, and Curator work together to continuously improve contexts
  • 📈 Incremental Delta Updates: Localized edits that preserve prior knowledge while accumulating new insights
  • 🎓 Self-Supervised Learning: Adapts effectively without labeled supervision by leveraging natural execution feedback
  • 🚀 High Efficiency: 86.9% lower adaptation latency on average compared to existing adaptive methods
  • 💰 Cost Effective: Significantly fewer rollouts and lower dollar costs while achieving higher accuracy

Tutorials

  • 📚 Adding Dataset for EvaluationLink
  • Extending ACE for Tool Calling (Coming Soon)

📊 Performance

ACE consistently outperforms strong baselines, achieving average gains of +10.6% on agent tasks and +8.6% on domain-specific benchmarks, across both offline and online adaptation settings.

Benchmarks

Task CategoryDatasetImprovementDetails
Agent TasksAppWorld+10.6%Matches top-ranked production-level agent (GPT-4.1) on average and surpasses it on harder test-challenge split, using smaller open-source model
FinanceFiNER + XBRL Formula+8.6%Domain-specific reasoning with structured information extraction

Efficiency Improvements

  • Offline (AppWorld): -82.3% latency and -75.1% rollouts vs GEPA
  • Online (FiNER): -91.5% latency and -83.6% token cost vs Dynamic Cheatsheet

How It Works

  1. Generator produces reasoning trajectories for new queries, surfacing both effective strategies and recurring pitfalls
  2. Reflector separates evaluation and insight extraction from curation, improving context quality
  3. Curator converts lessons into structured delta updates with helpful/harmful counters, using deterministic merging with de-duplication and pruning

This design prevents the context collapse problem where iterative rewriting erodes details over time.

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/ace-agent/ace.git
cd ace
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install ACE and core dependencies
uv sync
# Set up API keys
cp .env.example .env
# Edit .env and set the API key(s) you need

Basic Usage

fromaceimportACEfromutilsimportinitialize_clients# Initialize API clientsapi_provider="sambanova"# or "together", "openai", "commonstack"# Initialize ACE systemace_system=ACE(
api_provider=api_provider,
generator_model="DeepSeek-V3.1",
reflector_model="DeepSeek-V3.1",
curator_model="DeepSeek-V3.1",
max_tokens=4096
)
# Prepare configurationconfig= {
'num_epochs': 1,
'max_num_rounds': 3,
'curator_frequency': 1,
'eval_steps': 100,
'online_eval_frequency': 15,
'save_steps': 50,
'playbook_token_budget': 80000,
'task_name': 'your_task',
'json_mode': False,
'no_ground_truth': False,
'save_dir': './results',
'test_workers': 20,
'use_bulletpoint_analyzer': false,
'api_provider': api_provider
}
# Offline adaptationresults=ace_system.run(
mode='offline',
train_samples=train_data,
val_samples=val_data,
test_samples=test_data, # Optionaldata_processor=processor,
config=config
)
# Online adaptationresults=ace_system.run(
mode='online',
test_samples=test_data,
data_processor=processor,
config=config
)
# Evaluation onlyresults=ace_system.run(
mode='eval_only',
test_samples=test_data,
data_processor=processor,
config=config
)

💼 Finance Domain Example

Training Script Usage

The finance/run.py script provides a unified interface for training and evaluation on financial analysis tasks.

# Offline training (with automatic initial and final testing)
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results
# Online training and testing
uv run python -m eval.finance.run \
--task_name finer \
--mode online \
--save_path results
# Run evaluation on the test split only. Provide a pre-trained playbook or leave initial_playbook_path empty to evaluate an uninitialized playbook.
uv run python -m eval.finance.run \
--task_name finer \
--mode eval_only \
--initial_playbook_path results/ace_run_TIMESTAMP_finer_offline/best_playbook.txt \
--save_path test_results
# Training with custom configuration
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results \
--num_epochs 3 \
--eval_steps 100 \
--max_tokens 4096

Available Arguments

Click here to see available arguments
ArgumentDescriptionDefault
--task_nameTask to train on (e.g., finer, formula)Required
--save_pathDirectory to save resultsRequired
--initial_playbook_pathPath to initial playbookOptional
--modeRun mode: 'offline' for offline training with validation, 'online' for online training and testing on test split, 'eval_only' for evaluation onlyoffline
--api_providerAPI provider for LLM calls. Choose from ['sambanova', 'together', 'openai', 'commonstack']sambanova
--num_epochsNumber of training epochs1
--max_num_roundsMax reflection rounds for incorrect answers3
--curator_frequencyRun curator every N steps1
--eval_stepsEvaluate every N steps100
--online_eval_frequencyUpdate playbook every N samples for evaluation in online mode15
--save_stepsSave intermediate playbooks every N steps50
--max_tokensMaximum tokens for LLM responses4096
--playbook_token_budgetTotal token budget for playbook80000
--test_workersNumber of parallel workers for testing20
--generator_modelModel for generatorDeepSeek-V3.1
--reflector_modelModel for reflectorDeepSeek-V3.1
--curator_modelModel for curatorDeepSeek-V3.1
--json_modeEnable JSON mode for structured outputFalse
--no_ground_truthDon't use ground truth in reflectionFalse
--use_bulletpoint_analyzerEnable bulletpoint analyzer for playbook deduplication and mergingFalse
--bulletpoint_analyzer_thresholdSimilarity threshold for bulletpoint analyzer (0-1)0.9

📈 Results and Outputs

Using offline training as an example, after training, ACE generates:

results/
└── ace_run_TIMESTAMP_finer_offline/
├── run_config.json # Training configuration
├── final_results.json # Consolidated results from all stages
├── initial_test_results.json # Initial test results with empty playbook (baseline)
├── final_test_results.json # Final test results with best playbook
├── train_results.json # Training results
├── val_results.json # Validation results and error logs
├── pre_train_post_train_results.json # Detailed pre-train and post-train generator output for each training sample
├── final_playbook.txt # Final evolved context
├── best_playbook.txt # Best performing context (only for offline training)
├── bullet_usage_log.jsonl # Bullet usage tracking
├── curator_operations_diff.jsonl # Curator operation tracking
├── detailed_llm_logs/ # Detailed LLM call logs
└── intermediate_playbooks/ # Intermediate playbooks 

Understanding Playbook Format

The evolved context (playbook) follows this structure:

## STRATEGIES & INSIGHTS
[str-00001] helpful=5 harmful=0 :: Always verify data types before processing
[str-00002] helpful=3 harmful=1 :: Consider edge cases in financial data
## FORMULAS & CALCULATIONS
[cal-00003] helpful=8 harmful=0 :: NPV = Σ(Cash Flow / (1+r)^t)
## COMMON MISTAKES TO AVOID
[mis-00004] helpful=6 harmful=0 :: Don't forget timezone conversions

Each bullet has:

  • ID: [section_slug-00000] for tracking
  • Counts: helpful=X harmful=Y updated by Reflector
  • Content: :: actual advice or strategy

📬 Supported Tasks

Agent Tasks

  • AppWorld: Simulated digital environment with app interactions

Domain-Specific Tasks

  • FiNER: Financial information extraction
  • XBRL Formula: Structured financial data processing

🛠️ Extending ACE

ACE is designed to be easily extended to new tasks and domains. To add your own task:

  1. Prepare your data: Create JSONL files with train/val/test splits
  2. Implement DataProcessor: Only 3 methods needed - process_task_data(), answer_is_correct(), evaluate_accuracy()
  3. Create training script: Initialize ACE and run training using the run() method
  4. Customize prompts (optional): Adapt prompts to your domain

The evaluation orchestration (parallel test execution, result aggregation) is handled by reusable utilities in utils.py, so you only need to focus on task-specific logic.

Quick Example

classDataProcessor:
defprocess_task_data(self, raw_data):
# Convert your data format to standardized formatreturn [{"context": ..., "question": ..., "target": ..., "others": {...}}]
defanswer_is_correct(self, predicted, ground_truth):
# Your comparison logicreturnpredicted.strip() ==ground_truth.strip()
defevaluate_accuracy(self, predictions, ground_truths):
# Calculate accuracyreturnsum(self.answer_is_correct(p, g) forp, ginzip(predictions, ground_truths)) /len(predictions)

📖 Read the full extension guide →

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Additional Resources

🙏 Acknowledgments

This work builds upon insights from Dynamic Cheatsheet and incorporates ideas from the broader LLM agent and context optimization research community.

📧 Contact

For questions and feedback:


📝 Citation

If you use ACE in your research, please cite our paper:

@misc{zhang2025agenticcontextengineeringevolving,
title={Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models}, author={Qizheng Zhang and Changran Hu and Shubhangi Upasani and Boyuan Ma and Fenglu Hong and Vamsidhar Kamanuru and Jay Rainton and Chen Wu and Mengmeng Ji and Hanchen Li and Urmish Thakker and James Zou and Kunle Olukotun},
year={2025},
eprint={2510.04618},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2510.04618}, }

⭐ Star us on GitHub if ACE helps your research!

Made with ❤️ by the ACE team

About

Evolve your language agent with Agentic Context Engineering (ACE)

Resources

Stars

1.3k stars

Watchers

12 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models

arXivSlackDiscordAsk DeepWikiFeedback & Interest Form

ACE Framework

🎯 Overview

ACE (Agentic Context Engineering) is a framework that enables large language models to self-improve by treating contexts as evolving playbooks that accumulate, refine, and organize strategies through a modular process of generation, reflection, and curation. Unlike traditional approaches that suffer from brevity bias and context collapse, ACE introduces structured, incremental updates guided by a grow-and-refine principle, preserving detailed, domain-specific knowledge while remaining comprehensive and scalable throughout adaptation.

Latest News

  • 2025 Nov: ACE Paper and Repo says "Hello World"!

Key Features

  • 🔄 Three-Role Agentic Architecture: Generator, Reflector, and Curator work together to continuously improve contexts
  • 📈 Incremental Delta Updates: Localized edits that preserve prior knowledge while accumulating new insights
  • 🎓 Self-Supervised Learning: Adapts effectively without labeled supervision by leveraging natural execution feedback
  • 🚀 High Efficiency: 86.9% lower adaptation latency on average compared to existing adaptive methods
  • 💰 Cost Effective: Significantly fewer rollouts and lower dollar costs while achieving higher accuracy

Tutorials

  • 📚 Adding Dataset for EvaluationLink
  • Extending ACE for Tool Calling (Coming Soon)

📊 Performance

ACE consistently outperforms strong baselines, achieving average gains of +10.6% on agent tasks and +8.6% on domain-specific benchmarks, across both offline and online adaptation settings.

Benchmarks

Task CategoryDatasetImprovementDetails
Agent TasksAppWorld+10.6%Matches top-ranked production-level agent (GPT-4.1) on average and surpasses it on harder test-challenge split, using smaller open-source model
FinanceFiNER + XBRL Formula+8.6%Domain-specific reasoning with structured information extraction

Efficiency Improvements

  • Offline (AppWorld): -82.3% latency and -75.1% rollouts vs GEPA
  • Online (FiNER): -91.5% latency and -83.6% token cost vs Dynamic Cheatsheet

How It Works

  1. Generator produces reasoning trajectories for new queries, surfacing both effective strategies and recurring pitfalls
  2. Reflector separates evaluation and insight extraction from curation, improving context quality
  3. Curator converts lessons into structured delta updates with helpful/harmful counters, using deterministic merging with de-duplication and pruning

This design prevents the context collapse problem where iterative rewriting erodes details over time.

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/ace-agent/ace.git
cd ace
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install ACE and core dependencies
uv sync
# Set up API keys
cp .env.example .env
# Edit .env and set the API key(s) you need

Basic Usage

fromaceimportACEfromutilsimportinitialize_clients# Initialize API clientsapi_provider="sambanova"# or "together", "openai", "commonstack"# Initialize ACE systemace_system=ACE(
api_provider=api_provider,
generator_model="DeepSeek-V3.1",
reflector_model="DeepSeek-V3.1",
curator_model="DeepSeek-V3.1",
max_tokens=4096
)
# Prepare configurationconfig= {
'num_epochs': 1,
'max_num_rounds': 3,
'curator_frequency': 1,
'eval_steps': 100,
'online_eval_frequency': 15,
'save_steps': 50,
'playbook_token_budget': 80000,
'task_name': 'your_task',
'json_mode': False,
'no_ground_truth': False,
'save_dir': './results',
'test_workers': 20,
'use_bulletpoint_analyzer': false,
'api_provider': api_provider
}
# Offline adaptationresults=ace_system.run(
mode='offline',
train_samples=train_data,
val_samples=val_data,
test_samples=test_data, # Optionaldata_processor=processor,
config=config
)
# Online adaptationresults=ace_system.run(
mode='online',
test_samples=test_data,
data_processor=processor,
config=config
)
# Evaluation onlyresults=ace_system.run(
mode='eval_only',
test_samples=test_data,
data_processor=processor,
config=config
)

💼 Finance Domain Example

Training Script Usage

The finance/run.py script provides a unified interface for training and evaluation on financial analysis tasks.

# Offline training (with automatic initial and final testing)
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results
# Online training and testing
uv run python -m eval.finance.run \
--task_name finer \
--mode online \
--save_path results
# Run evaluation on the test split only. Provide a pre-trained playbook or leave initial_playbook_path empty to evaluate an uninitialized playbook.
uv run python -m eval.finance.run \
--task_name finer \
--mode eval_only \
--initial_playbook_path results/ace_run_TIMESTAMP_finer_offline/best_playbook.txt \
--save_path test_results
# Training with custom configuration
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results \
--num_epochs 3 \
--eval_steps 100 \
--max_tokens 4096

Available Arguments

Click here to see available arguments
ArgumentDescriptionDefault
--task_nameTask to train on (e.g., finer, formula)Required
--save_pathDirectory to save resultsRequired
--initial_playbook_pathPath to initial playbookOptional
--modeRun mode: 'offline' for offline training with validation, 'online' for online training and testing on test split, 'eval_only' for evaluation onlyoffline
--api_providerAPI provider for LLM calls. Choose from ['sambanova', 'together', 'openai', 'commonstack']sambanova
--num_epochsNumber of training epochs1
--max_num_roundsMax reflection rounds for incorrect answers3
--curator_frequencyRun curator every N steps1
--eval_stepsEvaluate every N steps100
--online_eval_frequencyUpdate playbook every N samples for evaluation in online mode15
--save_stepsSave intermediate playbooks every N steps50
--max_tokensMaximum tokens for LLM responses4096
--playbook_token_budgetTotal token budget for playbook80000
--test_workersNumber of parallel workers for testing20
--generator_modelModel for generatorDeepSeek-V3.1
--reflector_modelModel for reflectorDeepSeek-V3.1
--curator_modelModel for curatorDeepSeek-V3.1
--json_modeEnable JSON mode for structured outputFalse
--no_ground_truthDon't use ground truth in reflectionFalse
--use_bulletpoint_analyzerEnable bulletpoint analyzer for playbook deduplication and mergingFalse
--bulletpoint_analyzer_thresholdSimilarity threshold for bulletpoint analyzer (0-1)0.9

📈 Results and Outputs

Using offline training as an example, after training, ACE generates:

results/
└── ace_run_TIMESTAMP_finer_offline/
├── run_config.json # Training configuration
├── final_results.json # Consolidated results from all stages
├── initial_test_results.json # Initial test results with empty playbook (baseline)
├── final_test_results.json # Final test results with best playbook
├── train_results.json # Training results
├── val_results.json # Validation results and error logs
├── pre_train_post_train_results.json # Detailed pre-train and post-train generator output for each training sample
├── final_playbook.txt # Final evolved context
├── best_playbook.txt # Best performing context (only for offline training)
├── bullet_usage_log.jsonl # Bullet usage tracking
├── curator_operations_diff.jsonl # Curator operation tracking
├── detailed_llm_logs/ # Detailed LLM call logs
└── intermediate_playbooks/ # Intermediate playbooks 

Understanding Playbook Format

The evolved context (playbook) follows this structure:

## STRATEGIES & INSIGHTS
[str-00001] helpful=5 harmful=0 :: Always verify data types before processing
[str-00002] helpful=3 harmful=1 :: Consider edge cases in financial data
## FORMULAS & CALCULATIONS
[cal-00003] helpful=8 harmful=0 :: NPV = Σ(Cash Flow / (1+r)^t)
## COMMON MISTAKES TO AVOID
[mis-00004] helpful=6 harmful=0 :: Don't forget timezone conversions

Each bullet has:

  • ID: [section_slug-00000] for tracking
  • Counts: helpful=X harmful=Y updated by Reflector
  • Content: :: actual advice or strategy

📬 Supported Tasks

Agent Tasks

  • AppWorld: Simulated digital environment with app interactions

Domain-Specific Tasks

  • FiNER: Financial information extraction
  • XBRL Formula: Structured financial data processing

🛠️ Extending ACE

ACE is designed to be easily extended to new tasks and domains. To add your own task:

  1. Prepare your data: Create JSONL files with train/val/test splits
  2. Implement DataProcessor: Only 3 methods needed - process_task_data(), answer_is_correct(), evaluate_accuracy()
  3. Create training script: Initialize ACE and run training using the run() method
  4. Customize prompts (optional): Adapt prompts to your domain

The evaluation orchestration (parallel test execution, result aggregation) is handled by reusable utilities in utils.py, so you only need to focus on task-specific logic.

Quick Example

classDataProcessor:
defprocess_task_data(self, raw_data):
# Convert your data format to standardized formatreturn [{"context": ..., "question": ..., "target": ..., "others": {...}}]
defanswer_is_correct(self, predicted, ground_truth):
# Your comparison logicreturnpredicted.strip() ==ground_truth.strip()
defevaluate_accuracy(self, predictions, ground_truths):
# Calculate accuracyreturnsum(self.answer_is_correct(p, g) forp, ginzip(predictions, ground_truths)) /len(predictions)

📖 Read the full extension guide →

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Additional Resources

🙏 Acknowledgments

This work builds upon insights from Dynamic Cheatsheet and incorporates ideas from the broader LLM agent and context optimization research community.

📧 Contact

For questions and feedback:


📝 Citation

If you use ACE in your research, please cite our paper:

@misc{zhang2025agenticcontextengineeringevolving,
title={Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models}, author={Qizheng Zhang and Changran Hu and Shubhangi Upasani and Boyuan Ma and Fenglu Hong and Vamsidhar Kamanuru and Jay Rainton and Chen Wu and Mengmeng Ji and Hanchen Li and Urmish Thakker and James Zou and Kunle Olukotun},
year={2025},
eprint={2510.04618},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2510.04618}, }

⭐ Star us on GitHub if ACE helps your research!

Made with ❤️ by the ACE team

About

Evolve your language agent with Agentic Context Engineering (ACE)

Resources

Stars

1.3k stars

Watchers

12 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models

arXivSlackDiscordAsk DeepWikiFeedback & Interest Form

ACE Framework

🎯 Overview

ACE (Agentic Context Engineering) is a framework that enables large language models to self-improve by treating contexts as evolving playbooks that accumulate, refine, and organize strategies through a modular process of generation, reflection, and curation. Unlike traditional approaches that suffer from brevity bias and context collapse, ACE introduces structured, incremental updates guided by a grow-and-refine principle, preserving detailed, domain-specific knowledge while remaining comprehensive and scalable throughout adaptation.

Latest News

  • 2025 Nov: ACE Paper and Repo says "Hello World"!

Key Features

  • 🔄 Three-Role Agentic Architecture: Generator, Reflector, and Curator work together to continuously improve contexts
  • 📈 Incremental Delta Updates: Localized edits that preserve prior knowledge while accumulating new insights
  • 🎓 Self-Supervised Learning: Adapts effectively without labeled supervision by leveraging natural execution feedback
  • 🚀 High Efficiency: 86.9% lower adaptation latency on average compared to existing adaptive methods
  • 💰 Cost Effective: Significantly fewer rollouts and lower dollar costs while achieving higher accuracy

Tutorials

  • 📚 Adding Dataset for EvaluationLink
  • Extending ACE for Tool Calling (Coming Soon)

📊 Performance

ACE consistently outperforms strong baselines, achieving average gains of +10.6% on agent tasks and +8.6% on domain-specific benchmarks, across both offline and online adaptation settings.

Benchmarks

Task CategoryDatasetImprovementDetails
Agent TasksAppWorld+10.6%Matches top-ranked production-level agent (GPT-4.1) on average and surpasses it on harder test-challenge split, using smaller open-source model
FinanceFiNER + XBRL Formula+8.6%Domain-specific reasoning with structured information extraction

Efficiency Improvements

  • Offline (AppWorld): -82.3% latency and -75.1% rollouts vs GEPA
  • Online (FiNER): -91.5% latency and -83.6% token cost vs Dynamic Cheatsheet

How It Works

  1. Generator produces reasoning trajectories for new queries, surfacing both effective strategies and recurring pitfalls
  2. Reflector separates evaluation and insight extraction from curation, improving context quality
  3. Curator converts lessons into structured delta updates with helpful/harmful counters, using deterministic merging with de-duplication and pruning

This design prevents the context collapse problem where iterative rewriting erodes details over time.

🚀 Quick Start

Installation

# Clone the repository
git clone https://github.com/ace-agent/ace.git
cd ace
# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install ACE and core dependencies
uv sync
# Set up API keys
cp .env.example .env
# Edit .env and set the API key(s) you need

Basic Usage

fromaceimportACEfromutilsimportinitialize_clients# Initialize API clientsapi_provider="sambanova"# or "together", "openai", "commonstack"# Initialize ACE systemace_system=ACE(
api_provider=api_provider,
generator_model="DeepSeek-V3.1",
reflector_model="DeepSeek-V3.1",
curator_model="DeepSeek-V3.1",
max_tokens=4096
)
# Prepare configurationconfig= {
'num_epochs': 1,
'max_num_rounds': 3,
'curator_frequency': 1,
'eval_steps': 100,
'online_eval_frequency': 15,
'save_steps': 50,
'playbook_token_budget': 80000,
'task_name': 'your_task',
'json_mode': False,
'no_ground_truth': False,
'save_dir': './results',
'test_workers': 20,
'use_bulletpoint_analyzer': false,
'api_provider': api_provider
}
# Offline adaptationresults=ace_system.run(
mode='offline',
train_samples=train_data,
val_samples=val_data,
test_samples=test_data, # Optionaldata_processor=processor,
config=config
)
# Online adaptationresults=ace_system.run(
mode='online',
test_samples=test_data,
data_processor=processor,
config=config
)
# Evaluation onlyresults=ace_system.run(
mode='eval_only',
test_samples=test_data,
data_processor=processor,
config=config
)

💼 Finance Domain Example

Training Script Usage

The finance/run.py script provides a unified interface for training and evaluation on financial analysis tasks.

# Offline training (with automatic initial and final testing)
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results
# Online training and testing
uv run python -m eval.finance.run \
--task_name finer \
--mode online \
--save_path results
# Run evaluation on the test split only. Provide a pre-trained playbook or leave initial_playbook_path empty to evaluate an uninitialized playbook.
uv run python -m eval.finance.run \
--task_name finer \
--mode eval_only \
--initial_playbook_path results/ace_run_TIMESTAMP_finer_offline/best_playbook.txt \
--save_path test_results
# Training with custom configuration
uv run python -m eval.finance.run \
--task_name finer \
--mode offline \
--save_path results \
--num_epochs 3 \
--eval_steps 100 \
--max_tokens 4096

Available Arguments

Click here to see available arguments
ArgumentDescriptionDefault
--task_nameTask to train on (e.g., finer, formula)Required
--save_pathDirectory to save resultsRequired
--initial_playbook_pathPath to initial playbookOptional
--modeRun mode: 'offline' for offline training with validation, 'online' for online training and testing on test split, 'eval_only' for evaluation onlyoffline
--api_providerAPI provider for LLM calls. Choose from ['sambanova', 'together', 'openai', 'commonstack']sambanova
--num_epochsNumber of training epochs1
--max_num_roundsMax reflection rounds for incorrect answers3
--curator_frequencyRun curator every N steps1
--eval_stepsEvaluate every N steps100
--online_eval_frequencyUpdate playbook every N samples for evaluation in online mode15
--save_stepsSave intermediate playbooks every N steps50
--max_tokensMaximum tokens for LLM responses4096
--playbook_token_budgetTotal token budget for playbook80000
--test_workersNumber of parallel workers for testing20
--generator_modelModel for generatorDeepSeek-V3.1
--reflector_modelModel for reflectorDeepSeek-V3.1
--curator_modelModel for curatorDeepSeek-V3.1
--json_modeEnable JSON mode for structured outputFalse
--no_ground_truthDon't use ground truth in reflectionFalse
--use_bulletpoint_analyzerEnable bulletpoint analyzer for playbook deduplication and mergingFalse
--bulletpoint_analyzer_thresholdSimilarity threshold for bulletpoint analyzer (0-1)0.9

📈 Results and Outputs

Using offline training as an example, after training, ACE generates:

results/
└── ace_run_TIMESTAMP_finer_offline/
├── run_config.json # Training configuration
├── final_results.json # Consolidated results from all stages
├── initial_test_results.json # Initial test results with empty playbook (baseline)
├── final_test_results.json # Final test results with best playbook
├── train_results.json # Training results
├── val_results.json # Validation results and error logs
├── pre_train_post_train_results.json # Detailed pre-train and post-train generator output for each training sample
├── final_playbook.txt # Final evolved context
├── best_playbook.txt # Best performing context (only for offline training)
├── bullet_usage_log.jsonl # Bullet usage tracking
├── curator_operations_diff.jsonl # Curator operation tracking
├── detailed_llm_logs/ # Detailed LLM call logs
└── intermediate_playbooks/ # Intermediate playbooks 

Understanding Playbook Format

The evolved context (playbook) follows this structure:

## STRATEGIES & INSIGHTS
[str-00001] helpful=5 harmful=0 :: Always verify data types before processing
[str-00002] helpful=3 harmful=1 :: Consider edge cases in financial data
## FORMULAS & CALCULATIONS
[cal-00003] helpful=8 harmful=0 :: NPV = Σ(Cash Flow / (1+r)^t)
## COMMON MISTAKES TO AVOID
[mis-00004] helpful=6 harmful=0 :: Don't forget timezone conversions

Each bullet has:

  • ID: [section_slug-00000] for tracking
  • Counts: helpful=X harmful=Y updated by Reflector
  • Content: :: actual advice or strategy

📬 Supported Tasks

Agent Tasks

  • AppWorld: Simulated digital environment with app interactions

Domain-Specific Tasks

  • FiNER: Financial information extraction
  • XBRL Formula: Structured financial data processing

🛠️ Extending ACE

ACE is designed to be easily extended to new tasks and domains. To add your own task:

  1. Prepare your data: Create JSONL files with train/val/test splits
  2. Implement DataProcessor: Only 3 methods needed - process_task_data(), answer_is_correct(), evaluate_accuracy()
  3. Create training script: Initialize ACE and run training using the run() method
  4. Customize prompts (optional): Adapt prompts to your domain

The evaluation orchestration (parallel test execution, result aggregation) is handled by reusable utilities in utils.py, so you only need to focus on task-specific logic.

Quick Example

classDataProcessor:
defprocess_task_data(self, raw_data):
# Convert your data format to standardized formatreturn [{"context": ..., "question": ..., "target": ..., "others": {...}}]
defanswer_is_correct(self, predicted, ground_truth):
# Your comparison logicreturnpredicted.strip() ==ground_truth.strip()
defevaluate_accuracy(self, predictions, ground_truths):
# Calculate accuracyreturnsum(self.answer_is_correct(p, g) forp, ginzip(predictions, ground_truths)) /len(predictions)

📖 Read the full extension guide →

🤝 Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📚 Additional Resources

🙏 Acknowledgments

This work builds upon insights from Dynamic Cheatsheet and incorporates ideas from the broader LLM agent and context optimization research community.

📧 Contact

For questions and feedback:


📝 Citation

If you use ACE in your research, please cite our paper:

@misc{zhang2025agenticcontextengineeringevolving,
title={Agentic Context Engineering: Evolving Contexts for Self-Improving Language Models}, author={Qizheng Zhang and Changran Hu and Shubhangi Upasani and Boyuan Ma and Fenglu Hong and Vamsidhar Kamanuru and Jay Rainton and Chen Wu and Mengmeng Ji and Hanchen Li and Urmish Thakker and James Zou and Kunle Olukotun},
year={2025},
eprint={2510.04618},
archivePrefix={arXiv},
primaryClass={cs.LG},
url={https://arxiv.org/abs/2510.04618}, }

⭐ Star us on GitHub if ACE helps your research!

Made with ❤️ by the ACE team

About

Evolve your language agent with Agentic Context Engineering (ACE)

Resources

Stars

1.3k stars

Watchers

12 watching

Forks

Releases

Packages

Contributors

Languages