| name | optimization-workflow |
| description | Full code optimization workflow - from analyzing code to running optimization and reviewing results |
| version | 2.0.0 |
| author | kai-agent |
| metadata | {"kai":{"tags":["kai","optimization","code-quality","performance"]}} |
Code Optimization Workflow
End-to-end workflow for running AI-powered code optimization through Kai.
Prerequisites
- Kai MCP tools available (load kai-platform skill first)
- Repository added to a workspace
- Active agent subscription on the workspace
Workflow
1. Understand the optimization goal
Ask the user or infer from context:
- What to optimize: performance, memory, gas (Solidity), algorithm efficiency
- Target files/functions: specific code sections or let Kai analyze
- Success metric: "2x faster", "50% less memory", "lower gas cost"
2. Analyze the repository
browse_repository_files(workspaceId, repoId) → understand structure
read_repository_files(workspaceId, repoId, paths) → read target code
Identify optimization candidates:
- Hot loops, recursive functions, data structure choices
- Algorithmic complexity (O(n^2) that could be O(n log n))
- Memory allocation patterns
- Framework-specific inefficiencies
3. Check for active optimizations
Before starting, verify no optimization is already running on the same file:
list_code_optimizations(workspaceId, repoId)
If there's an active run on the same scope, do NOT start another one. Instead:
- Check its progress with
get_code_optimization_progress
- If bestScore is 0 after 10+ iterations, abort it with
abort_code_optimization — the evaluator is broken
- If it's making progress, report the status and wait
4. Get user approval
Create a lifecycle action and wait for the user to approve before proceeding:
lifecycle_actions_create(workspaceId, type="evolution", title="Optimize [target]", description="...", priority="high", repoId=repoId)
Wait for the user to execute the action (status changes to in_progress).
5. Write, test, and upload the evaluator
Write a Python evaluator yourself — never use create_ai_evaluator. You understand the code and the goal better than an auto-generator.
Self-test before uploading (critical — do not skip):
python3 -c "
from evaluator import evaluate
result = evaluate('/path/to/target_program.py')
print(result)
assert isinstance(result, dict), 'Must return dict'
assert 'combined_score' in result, 'Must have combined_score'
assert result['combined_score'] > 0, 'Score must be > 0 for the initial program'
print('PASS')
"
If the self-test fails, fix the evaluator before uploading. A broken evaluator wastes hundreds of LLM calls.
The evaluator must define evaluate(program_path) — it receives a file path string, not a module. Must return a dict like {"correctness": 1.0, "performance": score}. Load the evaluator-creation skill for detailed patterns and examples.
create_evaluator_from_code(workspaceId, repoId, code=evaluator_code, name="My Evaluator")
→ returns { evaluatorId }
If the evaluator needs GPU: the default path is Modal via the workspace proxy (zero user setup when MODAL_SERVER_URL is set). Load the kai-evolve/evaluator-creation skill and follow Option A in the GPU Evaluator Pattern. Only fall back to user-hosted GPU infrastructure (Option C) or CPU approximation (Option D) when Modal isn't connected and can't be.
6. Start the optimization
config = {
"llm": {
"models": [{"name": "openai/gpt-4o", "weight": 1.0}],
},
"prompt": {
"systemMessage": "Optimize <target> for <metric>. Keep public API unchanged.",
},
}
scopes = [
{"path": "src/foo.py", "fromLine": 42, "toLine": 87},
]
start_code_optimization(workspaceId, repoId, config, scopes, evaluatorId)
Field-name pitfalls (use these, not the alternatives on the right):
scopes[].path / fromLine / toLine — not filePath / startLine / endLine
config.llm.models (array of {name, weight}) — not config.llm.model (string)
config.prompt.systemMessage — not config.prompt.goal
7. Monitor iterations
Optimizations take time (minutes to hours depending on complexity). Set up a cron job to poll progress every 10-15 minutes:
get_code_optimization_progress(optimizationId) → overall status
get_optimization_iterations(optimizationId) → iteration history with fitness scores
Report to team at milestones:
- Optimization started (with goal and target code)
- Significant fitness improvement (e.g., "iteration 15: 1.8x speedup achieved")
- Optimization completed
8. Review results
get_optimized_programs(optimizationId) → best solutions found
For each solution:
- Compare with original code
- Verify the improvement is real (not just gaming the evaluator)
- Check for correctness (edge cases, error handling)
- Assess readability and maintainability
9. Contextualize the solution
Use research tools to:
- Find academic papers on the algorithmic approach used
- Compare with known benchmarks
- Explain why the optimized solution is faster/better
- Identify potential trade-offs
10. Report and deliver
Present to the team:
- Before/after comparison with metrics
- Explanation of what changed and why it works
- Any trade-offs or caveats
- Suggested next optimization targets based on learnings
Tips
- Start with clear, measurable optimization goals
- Always write evaluators yourself — never use create_ai_evaluator
- Multiple evaluator scopes can target different parts of the same file
- Watch for overfitting: optimized code might pass benchmarks but fail on edge cases
- Save successful optimization patterns (evaluator configs, scope strategies) as memory
- If optimization stagnates, the evaluator might be too narrow or too broad