# optim-agent

Adopt this skill: https://proskills.md/skills/other/optim-agent-optim-agent

Page: https://proskills.md/skills/other/optim-agent-optim-agent
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 5088
upstream: https://github.com/optim-agent/optim-agent/blob/HEAD/SKILL.md

````text
---
name: optim-agent
description: Use when the user wants to optimize configurable system parameters against a measurable scalar objective, especially for model training, inference, quantitative strategies, reinforcement learning, scientific workflows, or other expensive black-box evaluations where reading the project can improve trial selection.
---

# optim-agent

Act as the sampler inside any coding-agent session: Claude Code, Codex,
OpenCode/OpenClaw, or another agent that can read project files and run shell
commands. Read the project to understand parameter meaning and interactions,
propose one configuration, run the real evaluator, and record the result
through optim-agent's ask/tell API. Let the measured objective, not the agent's
intuition, decide what works.

## Load the workflow

Use this file as the operating guide for the active coding agent. In Codex, it
can be installed directly from GitHub:

```text
$skill-installer install https://github.com/Optim-Agent/optim-agent
```

In Claude Code, OpenCode/OpenClaw, or another coding-agent environment, place
this repository or `SKILL.md` in the agent-visible workspace and ask the agent
to follow the optim-agent workflow. The workflow does not depend on Codex-only
APIs; it needs file access, shell access, and Python.

Ensure the Python package is importable. Choose one source; do not install both:

```bash
# Stable release from PyPI
python -m pip install optim-agent

# Latest source from GitHub
python -m pip install "optim-agent @ git+https://github.com/Optim-Agent/optim-agent.git"
```

For a reproducible GitHub install, append `@<tag-or-commit>` after `.git`.

## Workflow

1. **Understand the system.** Read the evaluation entry point and every file
   that defines the target parameters. Record each parameter's type, legal
   range, semantics, interactions, and operational constraints.
2. **Define the experiment.** Confirm the scalar objective, `minimize` or
   `maximize`, trial budget, evaluation command, runtime/cost limit, and fixed
   workload or seed. For multiple metrics or hard constraints, agree on one
   scalar feasibility or penalty rule before running trials.
3. **Establish a baseline.** Evaluate the current/default configuration with the
   same command and environment used for every later trial.
4. **Initialize or resume.** Keep artifacts in the repository's ignored
   `.optim-agent-runs/` directory:

   ```bash
   if git rev-parse --git-dir >/dev/null 2>&1 && ! git check-ignore -q .optim-agent-runs/; then
     printf '/.optim-agent-runs/\n' >> "$(git rev-parse --git-path info/exclude)"
   fi
   ```

   ```python
   from pathlib import Path
   import optim_agent as oa

   run_dir = Path(".optim-agent-runs")
   run_dir.mkdir(exist_ok=True)
   study = oa.create_study(
       direction="minimize",
       storage=run_dir / "skill-study.json",
       seed=0,
   )
   print([(t.params, t.value, t.state) for t in study.trials])
   ```

5. **Run one informed trial.** Choose parameters from code understanding and all
   completed history, then use explicit ask/tell:

   ```python
   params = {"threshold": 0.72, "budget": 80}
   trial = study.ask(params)
   try:
       value = evaluate_system(**trial.params)
   except Exception:
       study.tell(trial, state="failed")
       raise
   else:
       study.tell(trial, value)
   ```

   For a deliberately stopped trial, report the latest valid intermediate
   metric first, then call `study.tell(trial, state="pruned")`.
6. **Select the next point.** Avoid accidental repeats, explore broadly before
   exploiting, respect bounds and constraints, and treat failed regions as
   evidence. If the evaluator is noisy, repeat promising configurations under
   the same workload before declaring a winner.
7. **Stop and report.** Stop at the approved budget or stopping condition.
   Report the baseline, best value and parameters, trial count, failed/pruned
   trials, convergence trend, and exact reproduction command.

## Recovery

JSON storage records a trial when `study.tell` runs. Before launching an
expensive external evaluation, save its parameters, command, and output path in
a per-trial directory under `.optim-agent-runs/`. After interruption, inspect
that output before rerunning: if a valid result exists, recreate the same point
with `study.ask(params)` and record it; otherwise rerun it deliberately.

Use SQLite storage (`skill-study.db`) only when the user explicitly wants
multiple processes. Sequential trials are the default because each proposal
should use the complete prior history.

## Rules

- Use ask/tell in skill mode; do not delegate proposal selection to
  `AgentSampler` when the session agent is meant to read and reason over code.
- Keep evaluation inputs and outputs isolated from production configuration.
- Never fabricate, infer, or manually improve an objective value.
- Record crashes as `failed`; record intentional early stops as `pruned`.
- Preserve the study and trial artifacts so the result is auditable and resumable.
- Do not tune secrets, credentials, or unbounded parameters.
````

## File: README.md
upstream: https://github.com/optim-agent/optim-agent/blob/HEAD/README.md

````text
<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="docs/assets/optim-agent-logo-dark.svg">
    <img alt="optim-agent" src="docs/assets/optim-agent-logo-light.svg" width="500">
  </picture>
</p>

<h1 align="center">optim-agent</h1>

<p align="center">
  <strong>Agentic system optimization with coding agents.</strong><br>
  Automate the iterative parameter-tuning work of an algorithm engineer.
</p>

<p align="center">
  <a href="https://github.com/Optim-Agent/optim-agent/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/Optim-Agent/optim-agent?style=square"></a>
  <a href="https://hits.sh/github.com/Optim-Agent/optim-agent/"><img alt="Repo views" src="https://hits.sh/github.com/Optim-Agent/optim-agent.svg?label=repo%20views"></a>
  <a href="https://pypi.org/project/optim-agent/"><img alt="PyPI" src="https://img.shields.io/pypi/v/optim-agent"></a>
  <a href="https://pypi.org/project/optim-agent/"><img alt="Python versions" src="https://img.shields.io/pypi/pyversions/optim-agent"></a>
  <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/pypi/l/optim-agent"></a>
  <a href="https://optim-agent.github.io/optim-agent/"><img alt="Docs" src="https://img.shields.io/badge/docs-online-blue"></a>
  <a href="https://code.claude.com/docs/en/skills"><img alt="Claude Skill" src="https://img.shields.io/badge/Claude-Skill-D97757?logo=claude&logoColor=white"></a>
  <a href="https://developers.openai.com/codex/skills"><img alt="Codex Skill" src="https://img.shields.io/badge/Codex-Skill-blue?logo=openai&logoColor=white"></a>
</p>

<p align="center">
  <strong>English</strong> |
  <a href="docs/i18n/README_ZH.md">简体中文</a> |
  <a href="docs/i18n/README_JA.md">日本語</a> |
  <a href="docs/i18n/README_KO.md">한국어</a> |
  <a href="docs/i18n/README_FR.md">Français</a> |
  <a href="docs/i18n/README_DE.md">Deutsch</a> |
  <a href="docs/i18n/README_ES.md">Español</a> |
  <a href="docs/i18n/README_PT.md">Português</a> |
  <a href="docs/i18n/README_RU.md">Русский</a>
</p>

optim-agent lets Claude Code / Codex / OpenCode tune real system parameters by
reading your code, proposing trials, and recording measured objective results.
Use it when your system exposes configurable parameters and a measurable objective.
It combines what each parameter *means* with what the trial history *shows*,
then proposes the next configuration to evaluate. Objective evaluations remain
authoritative: optim-agent proposes values, validates them against the declared
space, records outcomes, and falls back to safe sampling when an agent reply is
invalid.

<p align="center">
  <img alt="optim-agent tuning loop" src="docs/assets/optim-agent-overview.png" width="900">
</p>

| Models | Systems | Research |
|---|---|---|
| Training, architecture, and RL experiments | Inference, latency, cost, control, and decision rules | Quant signals, simulations, and scientific workflows |

## Why optim-agent

- **Semantic proposals** - coding agents reason over parameter meanings, study
  context, and observed outcomes instead of treating every dimension as an
  anonymous coordinate.
- **Small-budget leverage** - useful when evaluations are expensive and classical
  surrogates are still data-starved.
- **Agent CLI upside** - proposal quality can improve as the underlying coding
  agents improve, such as moving from GPT-5.5 to GPT-5.6, without changing your
  optimization code.
- **Auditable decisions** - JSON/SQLite studies retain configurations,
  outcomes, states, context, and optional agent rationale.
- **Bounded execution** - the agent only proposes values; optim-agent validates
  them against the declared space, and invalid output falls back to safe
  sampling.

## Install

Install the Codex skill:

```text
$skill-installer install https://github.com/Optim-Agent/optim-agent
```

Install the Claude Code plugin:

```bash
claude plugin marketplace add Optim-Agent/optim-agent && claude plugin install optim-agent@optim-agent
```

Install the Python package:

```bash
# Stable release from PyPI
python -m pip install optim-agent

# Latest source from GitHub
python -m pip install "optim-agent @ git+https://github.com/Optim-Agent/optim-agent.git"
```

Requires one authenticated agent CLI on `PATH`:
[claude](https://docs.anthropic.com/en/docs/claude-code),
[codex](https://github.com/openai/codex), or
[opencode](https://github.com/sst/opencode).

## Quickstart

```python
import optim_agent as oa

def objective(trial):
    threshold = trial.suggest_float(
        "threshold", 0.05, 0.95,
        context="decision threshold; higher values trade recall for precision",
    )
    budget = trial.suggest_int(
        "budget", 10, 200, log=True,
        context="compute or operating budget; larger values may improve quality",
    )
    return evaluate_system(threshold=threshold, budget=budget)  # domain code

study = oa.create_study(
    direction="maximize",
    sampler=oa.AgentSampler(
        backend="claude",  # or "codex" / "opencode"
        effort="high",
        context="maximize system quality under a strict operating-cost budget",
        history=5,
        explicit_reasoning=True,
        qualitative_notes=True,
    ),
    storage="study.json",  # optional: persist and resume
    summarize=True,  # optional: agent-written result summary after the last trial
)
study.optimize(objective, n_trials=20)
print(study.best_value, study.best_params)
print(study.summary)  # the summary agent's narration of the finished study
```

Optional `context` gives domain meaning to the study and parameters. Provide it
study-wide on `AgentSampler(context=...)`, per parameter on
`suggest_*(..., context=...)`, or both.

## Where It Applies

| Area | Parameters optim-agent can tune | Example objective |
|---|---|---|
| **Model training** | learning rates, architectures, augmentation, regularization | validation quality, compute, robustness |
| **Inference and serving** | quantization, batching, decoding, caching, routing | quality, latency, throughput, cost |
| **Quantitative research** | signal windows, thresholds, rebalance rules, risk controls | walk-forward return, drawdown, turnover |
| **Reinforcement learning and decisions** | objective weights, exploration schedules, environment settings, policy thresholds | return, safety, sample efficiency |
| **Scientific workflows** | simulation inputs, solver settings, experimental controls | fit, error, runtime, resource use |
| **Black-box systems** | any bounded categorical, integer, or continuous configuration | scalar objective score |

For reinforcement learning, optim-agent tunes the system around the learning
loop; it does not replace the policy-learning algorithm.

## Optimization Trajectory

![Agent optimization trajectory compared with TPE](docs/assets/optimization_trajectory.gif)

This seed-0 Branin trace compares TPE and GPT-5.5 under the same 10-trial
budget, with incumbent objective values after each trial. It is a trajectory
illustration; aggregate benchmark results and reproduction commands follow.

### Optimizing Math Functions without Context: Branin-2D and Ackley-5D

Hard-function agents receive **no supplied task context**: only generic
`x1...x5` parameter names, numeric bounds, and trial history. Runs use 10 trials
over five seeds; Random and TPE are unchanged baselines.

#### Top-tier Agents

![No-context top-tier hard-function benchmark](docs/assets/hard_benchmarks_tier.png)

| method        | mean best Branin ↓ | mean best Ackley-5D ↓ |
| ------------- | -----------------: | --------------------: |
| Random        |              5.008 |                19.639 |
| TPE           |             11.395 |                18.843 |
| GPT-5.5       |              1.326 |                 3.960 |
| **Opus-4.8**  |          **0.398** |             **0.061** |
| Sonnet-5      |              3.850 |                 0.143 |
| Kimi-K3       |              2.082 |                 0.907 |
| Minimax-M3    |              0.97
````
