How to Build a Long-Running AI Agent with the Claude Opus 5 API: An Overnight Build Log
A hands-on guide to building autonomous AI agents on the Claude Opus 5 API: the agent loop in Python, mid-conversation system messages, prompt caching costs, and what an overnight dependency-upgrade run actually cost.
The test I run against every new frontier model is the same: our dependency-upgrade agent. It takes a client repo with a year of deferred upgrades, walks the dependency tree, upgrades packages one at a time, runs the test suite after each, reads the failures, patches the breakages, and writes a report. Boring, high-value work that takes a human two days. It's also brutal on models, because it demands hundreds of tool calls of sustained coherence, and every model before this year eventually forgot why it was editing a file.
Claude Opus 5 launched Thursday. Thursday night I pointed the agent at a Next.js repo with 34 outdated packages and went to bed. If you're researching how to build a long-running AI agent on the Claude Opus 5 API, this build log covers the loop, the four features that ended up load-bearing, and the actual bill.
The Claude Opus 5 agent loop in Python
The core is the same agentic loop you'd write for any Claude model: call messages.create with tools, execute the tool_use blocks, append results, repeat until end_turn. Opus 5 didn't change the loop. It changed what you can afford to do inside it.
import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": TASK_SPEC}]
while True:
with client.messages.stream(
model="claude-opus-5",
max_tokens=64000,
output_config={"effort": "xhigh"},
tools=TOOLS, # bash, read_file, edit_file, run_tests
messages=messages,
) as stream:
response = stream.get_final_message()
if response.stop_reason == "end_turn":
break
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": execute_tools(response)})
Every parameter there is deliberate. effort: "xhigh" is the recommended setting for long agentic work, and on Opus 5 thinking is mandatory at that level; the interleaved thinking between tool calls is where the long-horizon coherence comes from. max_tokens: 64000 because thinking counts against the cap and at xhigh the model needs the room. Streaming because a single hard turn can run for minutes, and a non-streaming request that long will hit HTTP timeouts.
One more thing worth stating plainly: give the agent the whole task up front. One well-specified opening message covering the goal, the constraints, what "done" means, and where to write the report outperforms drip-feeding instructions across turns. Opus 5 plans against the goal it has. Vague goals produce thrashing.
Mid-conversation system messages: steering without a restart
This is the genuinely new API capability. At 2 a.m. the agent was six hours and roughly 300 tool calls in when it hit a package whose upgrade required a decision I hadn't specified: a breaking API change with two plausible migration paths. My old harness had exactly one option for this, and it was bad. Edit the system prompt, restart the conversation, throw away the entire cached prefix.
Opus 5 accepts {"role": "system", ...} messages inside the messages array, after a user turn. My harness now lets me inject steering without touching cached history:
messages.append({
"role": "system",
"content": "Operator note: for the router migration, take the codemod path, "
"not the compat-shim path. The client is deleting legacy routes in Q4."
})
Two properties matter. The instruction lands after the cached prefix instead of invalidating it from position zero, so the cache survives. And it carries system authority, meaning the model treats it as an operator instruction rather than as user text that might be a prompt injection smuggled in through tool output. For agents that run unattended and occasionally need a human to lean over their shoulder, this is the primitive we've wanted for two years.
Claude Opus 5 prompt caching: the floor dropped to 512 tokens
Prompt caching minimums used to mean our smaller sub-prompts, the focused per-package upgrade instructions the agent generates for itself, silently never cached. Opus 5 lowers the minimum cacheable prefix to 512 tokens. No code change; markers that were decorative before now work.
Across an overnight run where the conversation gets re-sent hundreds of times, this dominates the economics. Our morning-after usage report showed 87% of input tokens billed at the cache-read rate, which is about a tenth of base input price. The run cost $41. The same repo on our old multi-restart harness last year cost around $300, most of it reprocessed prefixes.
Practical setup: place one cache_control: {"type": "ephemeral"} breakpoint on the last block of the most recent turn each iteration, and keep your system prompt byte-stable. That means no timestamps in it. Inject time-sensitive facts through mid-conversation system messages instead.
The 1M context window, actually used
The repo's lockfile diff history, the full test output logs, the in-progress upgrade report: all of it stayed in context. Nothing needed summarizing until hour seven. When you do approach the window on longer runs, the compaction beta (compact-2026-01-12) summarizes server-side, with one rule: append the full response.content back each turn so the compaction blocks survive. The honest report is that at 1M tokens, a single-repo overnight task never needed it.
Delete your narration scaffolding
Opus 5 gives regular, well-calibrated progress updates in long agentic traces by default. My harness carried prompt scaffolding from the 4.6 era forcing a summary every N tool calls. With it left in, the agent over-reported, producing status messages twice as often as useful. Deleting the scaffolding produced better updates than the scaffolding ever did. The morning transcript read like a competent contractor's worklog: what was upgraded, what broke, what it did about it, what it left alone and why.
The morning after: results and cost
31 of 34 packages upgraded, test suite green. The three it left alone: one major-version jump it flagged as needing a human decision on a public API (the correct call), and two peer-dependency conflicts it documented with exact resolution options (also correct). It wrote everything to UPGRADE_REPORT.md unprompted, because the task spec said the deliverable was a report. Total API cost: $41.
What changed with Opus 5 isn't that agents can suddenly do new things. It's that the API finally has the right primitives for the operator: steer mid-run without a restart, cache aggressively enough that overnight economics work, and trust the default narration instead of fighting it. Long-running AI agents stopped being a demo this week. They became a line item we can quote to clients.
Related reading
An independent comparison of the three agentic models that launched this month. Real pricing, production failure modes, cost per completed task, and the routing table we actually run — not a benchmark aggregation.
A step-by-step tutorial for bulk AI document extraction with the Claude Opus 5 Batch API: structured outputs with JSON schemas, 50% batch pricing, the 300K output beta, and the real cost of processing 40,000 vendor contracts.
How to use the Claude Opus 5 effort parameter (low, medium, high, xhigh, max) to cut Claude API costs. Real per-request cost numbers, working Python code, and why we retired our Haiku/Sonnet/Opus routing layer.
Let's build something great.
Have a project in mind? We are an elite software and AI development studio ready to bring your ideas to production. Let's talk about your roadmap.