Article
AI engineering · Guides
Set Up Claude Code and Codex for Speed and Low Cost: A Step-by-Step Guide
Seven steps, in build order, with the config for both tools side by side. Most of the cost and the waiting comes from context, so most of the steps are about what gets read, by whom, and how often.
Start readingAs of October 2026. Every setting below links to the official page it comes from.
Claude Code and Codex are quick to install and easy to like. Then a few weeks of real work go by, and two things creep up: the bill, and the time you spend waiting.
Most of both comes from context, not from how hard the model thinks. On every turn, the tool sends the model its instructions plus the whole conversation so far. So cost and time follow three things: how much loads on every turn, how many turns a task takes, and how often an expensive model does cheap reading.
In one week of my own work, about 97.6% of all tokens were cache reads: the same context, read again and again.
This guide sets up both tools in seven steps, in the order I would do them. Each step gives the reason first, then the config for Claude Code and Codex side by side. Copy what you need. Each step helps on its own. Here is the setup you will have at the end.
Most work takes the fast lane; the expensive tiers run only when a trigger says so
New taskpicks one lane, then runs through its roles in order
Fast lane
The default for most work
- ScoutReads and searches, no editsSmall tierClaude Code: Haiku 5.5Codex: gpt-6-luna
- BuilderThe main session: edits and testsMid tierClaude Code: Sonnet 5.5Codex: gpt-6.1-sol
- ReviewerOne pass on the final diffMid tierClaude Code: Sonnet 5.5Codex: gpt-6.1-sol
Heavy lane
Only on a named trigger: migration, auth, payments
- ScoutReads and searches, no editsSmall tierClaude Code: Haiku 5.5Codex: gpt-6-luna
- ArchitectWrites the design firstTop tierClaude Code: Opus 5.5Codex: gpt-6-astra
- BuilderThe main session: edits and testsMid tierClaude Code: Sonnet 5.5Codex: gpt-6.1-sol
- ReviewerOne pass on the final diffMid tierClaude Code: Sonnet 5.5Codex: gpt-6.1-sol
Planning
Only when decisions are still open
- ScoutReads and searches, no editsSmall tierClaude Code: Haiku 5.5Codex: gpt-6-luna
- PlannerSettles open decisions into a specTop tierClaude Code: Opus 5.5Codex: gpt-6-astra
- BuilderThe main session: edits and testsMid tierClaude Code: Sonnet 5.5Codex: gpt-6.1-sol
1. Pick a model per role
The main session needs judgment. Most of the work around it does not: searching, reading files, summarising logs. At October 2026 list prices, Haiku 5.5 input costs a twentieth of Sonnet 5.5 input and a fortieth of Opus 5.5. Paying top-tier prices for reading is an easy way to waste money.
Keep the top tier for the few jobs where a wrong answer is expensive: a design you will build on for weeks, a tricky bug that has already beaten the mid tier once, a review of a change you cannot easily undo. Everything else starts on the mid tier, and plain reading starts on the small one. If the small tier gets something wrong, move that one job up a tier, not the whole setup.
Effort is the second dial. It changes how much a model thinks on each turn. In my experience it matters less than which model runs. Leave it at medium, the default for current Claude models, and raise it for one hard task rather than for everything.
In Claude Code, set the main model and effort in settings. Start the main session on the mid tier. If you want Opus for planning only, use the opusplan alias instead: Opus while you plan, Sonnet while it carries the plan out. effortLevel takes low, medium, high or xhigh. The max level is available only through /effort or --effort for one session.
In Codex, set model and model_reasoning_effort in config.toml, and give helpers their own default with default_subagent_model. plan_mode_reasoning_effort raises effort only while planning.
Every code block in this guide is a fragment of the file it names, so merge it in rather than pasting it as a whole file. In settings.json, keep a single top-level object. In config.toml, put top-level keys above the first table, such as [agents].
Claude Code · ~/.claude/settings.json
{
"model": "sonnet",
"effortLevel": "medium"
}Codex · ~/.codex/config.toml
# The main session: the mid tier at medium effort
model = "gpt-6.1-sol"
model_reasoning_effort = "medium"
# Think harder only while planning
plan_mode_reasoning_effort = "high"
[agents]
# Helpers start on the small tier unless an agent file says otherwise
default_subagent_model = "gpt-6-luna"One change to know if you used Codex profiles before: [profiles.name] tables are no longer read. A profile is now its own file, ~/.codex/name.config.toml, chosen with codex --profile name.
2. Keep the always-loaded instructions small
Your instruction file is sent on every turn of every session. Cached reads are cheap per token, but they add up, and a long file buries the rules that matter under the ones that rarely do.
The Claude Code docs say to keep each CLAUDE.md under 200 lines. Codex stops reading AGENTS.md files at 32 KiB by default (project_doc_max_bytes). Treat both as ceilings, not targets. Splitting the file with @path imports does not help: the imported text still loads.
Keep only the rules that apply to every task. Move procedures into skills. A skill keeps just its name and description in context, and its body loads only when a task needs it. That is true in Claude Code and in Codex, where the skill list is capped at about 2% of the context window by default.
When I trimmed my own setup, the always-loaded file went from 273 lines to about 100. Before that, my own layer (instructions, plus the descriptions of my agents, skills and tool servers) came to about 22,000 of the roughly 50,000 tokens every session started with.
Claude Code · ./CLAUDE.md
# Working agreement
## Always
- Run the tests after your last edit. If you did not run them, say "unverified".
- Ask before deploys, force pushes and anything that is hard to undo.
- Never write secrets or tokens into a file.
## Where things live
- Build and test: `npm run check`
- Longer procedures (releases, migrations, incident notes) are skills. Use them when the task needs them.Codex · ./AGENTS.md
# Working agreement
## Always
- Run the tests after your last edit. If you did not run them, say "unverified".
- Ask before deploys, force pushes and anything that is hard to undo.
- Never write secrets or tokens into a file.
## Where things live
- Build and test: `npm run check`
- Longer procedures (releases, migrations, incident notes) are skills. Use them when the task needs them.If you use both tools in one repository, you can keep a single AGENTS.md: Claude Code reads it when there is no CLAUDE.md.
Claude Code · ~/.claude/skills/release-notes/SKILL.md
---
name: release-notes
description: Drafts release notes from the commits since the last tag. Use when asked for release notes or a changelog.
---
1. Find the last tag: `git describe --tags --abbrev=0`
2. List the commits since it: `git log <tag>..HEAD --oneline`
3. Group them as Added, Changed and Fixed, one user-facing line each.Codex · ~/.agents/skills/release-notes/SKILL.md
---
name: release-notes
description: Drafts release notes from the commits since the last tag. Use when asked for release notes or a changelog.
---
1. Find the last tag: `git describe --tags --abbrev=0`
2. List the commits since it: `git log <tag>..HEAD --oneline`
3. Group them as Added, Changed and Fixed, one user-facing line each.Figure 2 shows why the token count and the bill tell different stories. Cache reads are almost all the tokens, but at 0.05 times the input price they are not most of the cost. A bigger instruction file costs a little on every turn. A longer session costs more on every later turn, because the history keeps growing.
Cache reads are almost all the tokens, but not all the cost
100Cost indexLean = 100 · 2M tokens in the session
- Cache reads 94%
- Cache writes 5%
- Output 1%
- Cache reads 29%
- Cache writes 35%
- Output 36%
| Preset | Context | Turns | Tokens | Cache reads, tokens | Cache reads, cost | Index |
|---|---|---|---|---|---|---|
| Lean | 8K | 40 | 2M | 94% | 29% | 100 |
| Heavy instructions | 40K | 40 | 3.3M | 95% | 37% | 131 |
| Long session | 8K | 120 | 16M | 98% | 54% | 447 |
Sonnet 5.5 list prices, against one uncached input token: cache read 0.05×, cache write 1.25×, output 5×. Each turn adds 1.5K input and 600 output tokens and resends the history; new input and the last turn's output are written to the cache as they enter it. Source: Anthropic pricing page, checked 2026-10-11.
3. Add role agents, each pinned to a model
A role agent gets a narrow job, a short prompt and the cheapest model that does the job well. It also runs in its own context, so a scout can read forty files and hand back ten lines. Your main session only pays for the ten lines.
Three to five roles are enough. Start with a read-only scout on the small tier and a reviewer on the mid tier. Add an architect on the top tier later, for heavy work only. Keep one writer: the main session. Two agents editing the same files cost more turns than they save.
In Claude Code, an agent is a Markdown file in ~/.claude/agents/ with name, description, model, effort and tools in its frontmatter. The tools line enforces read-only for the scout.
In Codex, an agent is a TOML file in ~/.codex/agents/ with name, description, developer_instructions, and optionally model and model_reasoning_effort (custom agents). Codex has no read-only switch in an agent file: the scout’s instructions ask it not to edit, and the sandbox comes from the main session’s settings.
Claude Code · ~/.claude/agents/scout.md
---
name: scout
description: Read-only search. Use it to find where something is defined or used before editing.
model: haiku
tools: Read, Grep, Glob
---
Find what was asked. Report file paths with line numbers and one line on each.
Do not edit files. Return at most 15 results, most relevant first.Codex · ~/.codex/agents/scout.toml
name = "scout"
description = "Read-only search. Use it to find where something is defined or used before editing."
model = "gpt-6-luna"
developer_instructions = """
Find what was asked. Report file paths with line numbers and one line on each.
Do not edit files. Return at most 15 results, most relevant first.
"""Claude Code · ~/.claude/agents/reviewer.md
---
name: reviewer
description: Reviews the final diff of a change. Use it once, after the tests pass.
model: sonnet
effort: high
tools: Read, Grep, Glob, Bash
---
Read the diff and the files it touches. Return at most five findings, ranked by how
costly they would be to miss. Skip style nitpicks. Do not edit files.Codex · ~/.codex/agents/reviewer.toml
name = "reviewer"
description = "Reviews the final diff of a change. Use it once, after the tests pass."
model = "gpt-6.1-sol"
model_reasoning_effort = "high"
developer_instructions = """
Read the diff and the files it touches. Return at most five findings, ranked by how
costly they would be to miss. Skip style nitpicks. Do not edit files.
"""The description line matters more than it looks. It is what the main session reads when it decides whether to hand a job over, so write it as a rule: what the agent does, and when to use it. Then use the agents on purpose for the first week. Ask for them by name (“use the scout to find every caller of this function”) until you see the main session reaching for them on its own. The reviewer’s limit of five findings is deliberate too: a long list of small points costs turns and buries the one finding that matters.
4. Route work by lanes
The expensive path is worth it only for work that can go badly wrong. Write the triggers down in your instruction file, so routing is a rule the agent follows, not a judgment call it makes fresh every time.
Use three lanes. The fast lane is the default: read, edit, test, and one review at the end. The heavy lane runs only on a named trigger, such as a database migration, auth, payments or a change across services, and adds a design step first. Planning runs only when decisions are still open: a planner on the top tier settles them into a short written spec.
Lanes are my own convention, not a feature of either tool. I learned the “only” the hard way. When every task went through a mandatory chain of agents, my delivery got about ten times slower, and compactions went from about 10 a week to 251.
Claude Code · ./CLAUDE.md
## Lanes
Pick one lane at the start of every task and say which.
- **Fast (default):** read the code, edit, run the tests, then one review of the final diff.
- **Heavy, only when the task touches** a database migration, auth, payments or more than one
service: write a short design first, then build, then review.
- **Planning, only when** two or more product decisions are still open: ask, write a short spec,
then build in the fast lane.Codex · ./AGENTS.md
## Lanes
Pick one lane at the start of every task and say which.
- **Fast (default):** read the code, edit, run the tests, then one review of the final diff.
- **Heavy, only when the task touches** a database migration, auth, payments or more than one
service: write a short design first, then build, then review.
- **Planning, only when** two or more product decisions are still open: ask, write a short spec,
then build in the fast lane.A heavy-lane task: only the design step runs on the top tier
Step 1
A migration is in the task, so it takes the heavy lane
The lane rule
The instruction file names migrations as a heavy-lane trigger, so nobody has to judge it case by case.
Step 2
Find every place the table is used
ScoutSmall tierClaude Code: Haiku 5.5Codex: gpt-6-luna
Reading and searching is most of the tokens. The small tier does it well, and the reading stays out of the main session.
Step 3
Write the design and the rollback plan
ArchitectTop tierClaude Code: Opus 5.5Codex: gpt-6-astra
A migration is costly to undo. One top-tier pass before any code is cheaper than fixing it afterwards.
Step 4
Write the migration, the code and the tests
BuilderMid tierClaude Code: Sonnet 5.5Codex: gpt-6.1-sol
Once the design is settled, the mid tier is enough to edit and run the tests.
Step 5
Review the final diff
ReviewerMid tierClaude Code: Sonnet 5.5Codex: gpt-6.1-sol
One pass on the finished diff catches what matters. A review after every edit would cost more turns.
5. Add only the hooks that pay
A hook runs on every matching event. A guard that checks every tool call adds a little delay and a new way to fail to all of your work, to catch a few cases.
I removed 21 guard hooks from my own setup after an audit tied the guard layer itself to 31% of the quality problems I had measured.
The hook worth having is a compaction hand-off. When a long session compacts, the model keeps a summary and loses details, such as which branch you are on and which files were half done. PreCompact runs just before compaction and saves a short note. SessionStart with the matcher compact runs just after and prints the note back. Both tools add that printed text to the model’s context. Both have both events, and both use a hooks object of event names with matcher groups (Claude Code hooks, Codex hooks).
Claude Code · ~/.claude/settings.json
{
"hooks": {
"PreCompact": [
{ "hooks": [{ "type": "command", "command": "~/.agent-hooks/save-state.sh" }] }
],
"SessionStart": [
{ "matcher": "compact", "hooks": [{ "type": "command", "command": "~/.agent-hooks/restore-state.sh" }] }
]
}
}Codex · ~/.codex/hooks.json
{
"hooks": {
"PreCompact": [
{ "hooks": [{ "type": "command", "command": "~/.agent-hooks/save-state.sh" }] }
],
"SessionStart": [
{ "matcher": "compact", "hooks": [{ "type": "command", "command": "~/.agent-hooks/restore-state.sh" }] }
]
}
}Keep the note short and factual: the branch, the changed files, the last few commits. That is the part a summary tends to blur, and it is cheap to collect. Resist adding the whole plan or a log. Whatever the hook prints comes back on every turn until the next compaction.
The two scripts are a generic starter. Make them executable with chmod +x. They use jq to read the session folder from the JSON each tool passes in.
save-state.sh · ~/.agent-hooks/save-state.sh
#!/usr/bin/env bash
# PreCompact: note what the session is working on before its history is summarised.
# Both tools pass the hook a JSON object on stdin; "cwd" is the session's folder (needs jq).
cwd=$(jq -r '.cwd // empty')
[ -n "$cwd" ] || exit 0
key=$(printf %s "$cwd" | shasum | cut -c1-12) # one note per folder, even if two share a name
state="$HOME/.agent-hooks/state/$key.md"
mkdir -p "$(dirname "$state")"
cd "$cwd" || exit 0
{
echo "Saved before compaction: $(date '+%Y-%m-%d %H:%M')"
echo "Branch: $(git branch --show-current 2>/dev/null)"
echo "Changed files:"; git status --short 2>/dev/null
echo "Last commits:"; git log --oneline -5 2>/dev/null
} > "$state"restore-state.sh · ~/.agent-hooks/restore-state.sh
#!/usr/bin/env bash
# SessionStart (matcher "compact"): print the saved note. Both tools add a
# SessionStart hook's plain stdout to the model's context.
cwd=$(jq -r '.cwd // empty')
[ -n "$cwd" ] || exit 0
key=$(printf %s "$cwd" | shasum | cut -c1-12) # one note per folder, even if two share a name
state="$HOME/.agent-hooks/state/$key.md"
[ -f "$state" ] && { echo "State saved before the last compaction:"; cat "$state"; }
exit 0Codex skips new or changed hooks until you trust them: run /hooks once after adding these.
One optional extra: a PreToolUse hook can rewrite a helper’s model before it starts, by returning updatedInput with an allow decision. It is worth adding only if you see helpers drifting onto an expensive model.
6. Control context and compaction
A long session resends its whole history on every turn. Figure 2’s turns slider shows what that costs. Three habits keep it in check. Use /clear between unrelated tasks. Use /compact with a line saying what to keep, such as “keep the plan and the failing test”. And use /context in Claude Code to see what is loaded.
A good /compact line names what the next hour needs and nothing else: the goal, the decision you made and why, the file you are in, the test that fails. Compact at a natural break, after a step is done, not in the middle of a change. And when a task is finished, clear rather than compact. A fresh session with a two-line summary costs less than carrying a long history into unrelated work.
Do not switch models halfway through a task. In Claude Code, a model switch drops the prompt cache, so the next turn pays to write the whole context again. Plan for the same in Codex, because a cache belongs to one model. Pauses cost too. The cache lasts an hour on a Claude subscription within plan usage, but five minutes on an API key.
Both tools compact on their own when the window fills. You can make that happen earlier, while the history is still small. In Claude Code, CLAUDE_AUTOCOMPACT_PCT_OVERRIDE takes a percentage from 1 to 100 and can only lower the threshold (environment variables). In Codex, model_auto_compact_token_limit sets the token count.
Claude Code · ~/.claude/settings.json
{
"env": {
"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": "70"
}
}Codex · ~/.codex/config.toml
# A top-level key: put it above any [table] such as [agents].
# Example value: set it to about 70% of your model's context window
model_auto_compact_token_limit = 1800007. Check cost once a week
Five minutes a week is enough. In Claude Code, /usage shows cost and tokens, with a prompt cache hit-rate line (/cost does the same) (costs). In Codex, /status shows context usage and rate limits for the chat, and /usage opens your usage settings (slash commands).
Claude Code
/usage cost and tokens, with the prompt cache hit rate
/context what is loaded into the context right nowCodex
/status context usage and rate limits for this chat
/usage opens usage and billing settings (signed in with ChatGPT)Look at three things. A falling cache hit rate means something keeps breaking the cached prefix: an edited instruction file, a changed tool server, a model switch. Rising tokens per session mean longer sessions or a bigger always-loaded layer, so clear more often and trim. And check which models did the reading. If the top tier did most of it, a helper is not pinned.
Change one thing at a time and check again the next week. If the hit rate dropped, look for what changed in the prefix and stop changing it mid-session. If tokens per session rose, open /context and cut the biggest thing you do not use on every task. Then write down what you changed. Two weeks later, you will want to know which change helped.
Trimming the setup cut the always-loaded file by almost two thirds
Always-loaded instruction file
273 lines- Before trimming
- 273 lines
- After trimming
- about 100 lines
Guard hooks on every action
21- Before trimming
- 21
- After trimming
- 0
The setup in seven lines
- The main session gets the mid tier at medium effort; helpers get the small tier.
- The always-loaded file holds only every-task rules; procedures are skills.
- Three to five role agents, each pinned to a model, with one writer.
- Three lanes, with the triggers written down.
- One compaction hand-off hook, and no guards on every action.
/clearbetween tasks, no model switches mid-task, earlier compaction.- A five-minute cost check every week.
If one step saved you more than the others, I would like to hear which.