Claude API Math: How to Write Formal Proofs You Can Check in Lean

Send a math problem to the Claude API, get a Lean 4 proof back, and let Lean check every step. A step-by-step guide with curl, a Python retry loop and effort settings.

INEZA Felin-Michel

INEZA Felin-Michel

23 November 2026

Claude API Math: How to Write Formal Proofs You Can Check in Lean

Apidog for Enterprise

On-Premises Deploy

SSO & RBAC

SOC 2 Compliant

Explore Apidog Enterprise

To use the Claude API for math, send a POST /v1/messages request to claude-opus-5-5 with output_config.effort set to high, ask for a Lean 4 proof in a single code block, then compile that block with Lean. If Lean rejects it, send the error back and ask for a fix. Claude writes the proof; Lean decides whether it’s correct.

That split is why Claude API math work is suddenly a hot topic. On November 20, 2026, Anthropic mathematician Levent Alpöge posted a 4-page note saying he had proved the Generalized Riemann Hypothesis for Dirichlet L-functions “working with Claude.” The proof was written in Lean, and the Lean and Mathlib communities certified it on November 21. Mathematicians still say it will take weeks to digest, and a Stanford postdoc has a competing, independent claim. No source names the Claude model he used.

You can’t reproduce that result from one API call, but you can reuse the workflow: a model proposes, a proof checker verifies.

What you need before you start

You need four things set up before your first request:

  1. An Anthropic API key, exported as ANTHROPIC_API_KEY.
  2. Lean 4 and Mathlib. Install Lean with elan from the Lean install guide, then create a project that depends on Mathlib.
  3. The Python SDK (pip install anthropic) or plain curl.
  4. Optional: Apidog CLI, so your coding agent can save and re-run the request as a test case (covered below).

If you’re new to proof assistants, our explainer on DeepSeek Prover V2 covers how AI models and Lean fit together.

Why pair the Claude API with Lean?

A language model can write a convincing proof that’s wrong. A plausible-looking step that doesn’t follow is the classic failure, and it’s hard to spot by eye. Lean removes the guesswork: its small trusted kernel checks every step, and the file compiles only if the whole proof holds for the exact statement you wrote.

So the work divides cleanly:

Part Who does it Trusted?
State the theorem You Yes, if you read it carefully
Search for a proof Claude, through the API No
Check every step Lean kernel Yes
Retry loop and file handling Your script Not needed: Lean has the last word

One trap: Lean proves what the statement says, not what you meant. If Claude quietly weakens the theorem, Lean accepts it, so your script must check that the statement didn’t change (Step 3 does).

Step 1: Send your first Claude API math request

Start with a plain curl call so you can see the raw request shape:

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-opus-5-5",
    "max_tokens": 16000,
    "thinking": {"type": "adaptive", "display": "summarized"},
    "output_config": {"effort": "high"},
    "messages": [{"role": "user", "content": "Prove that the sum of the first n odd numbers is n^2. Give a short informal proof, then a Lean 4 proof that uses Mathlib."}]
  }'

Three fields matter for math:

You can’t tune temperature here. Opus 5.5 rejects sampling parameters, and the 2026-10-21 API version rejects them on every model. Our guide to Claude API version 2026-10-21 covers the other changes.

Step 2: Ask for Lean 4, not prose

Informal proofs are fine for intuition, but you can’t check them automatically. For the loop to work, every reply needs one Lean file you can compile as is.

Write the theorem yourself, with sorry as a placeholder. Save it as Statement.lean:

import Mathlib

theorem sum_odd (n : ℕ) :
    ∑ i ∈ Finset.range n, (2 * i + 1) = n ^ 2 := by
  sorry

Then pin the output format in the system prompt:

You are a Lean 4 and Mathlib expert. Reply with exactly one fenced lean code block
containing the complete file, imports included. Keep the theorem statement
character for character. Never use sorry, admit or new axioms.

Two habits make replies more useful. Give the exact statement: don’t ask Claude to “formalize” a claim unless you’ll review the formal version yourself. And name the Mathlib lemmas you expect, such as Finset.sum_range_succ, to cut wasted attempts.

Step 3: Check the proof in Lean and loop on errors

First attempts often fail on a lemma name or tactic detail, so loop: generate, compile, return the error, repeat.

Sequence diagram of the proof loop: your script asks the Claude API for a Lean proof, compiles it with Lean, and sends compiler errors back until Lean accepts it or the attempt limit is reached

Here’s a Python version. It streams, because the SDK needs streaming for large max_tokens values:

import pathlib, re, subprocess
import anthropic

client = anthropic.Anthropic()
SYSTEM = pathlib.Path("system.txt").read_text()
statement = pathlib.Path("Statement.lean").read_text()
header = statement.split(":= by")[0].strip()
messages = [{"role": "user", "content": f"Prove this theorem:\n\n{statement}"}]

for attempt in range(1, 6):
    with client.messages.stream(
        model="claude-opus-5-5",
        max_tokens=64000,
        system=SYSTEM,
        output_config={"effort": "high"},
        messages=messages,
    ) as stream:
        msg = stream.get_final_message()

    if msg.stop_reason != "end_turn":
        raise SystemExit(f"Stopped early: {msg.stop_reason}")

    text = "".join(b.text for b in msg.content if b.type == "text")
    match = re.search(r"`{3}lean\n(.*?)`{3}", text, re.S)
    code = match.group(1) if match else ""
    pathlib.Path("Proof.lean").write_text(code)

    run = subprocess.run(["lake", "env", "lean", "Proof.lean"],
                         capture_output=True, text=True)
    log = run.stdout + run.stderr
    if run.returncode == 0 and header in code and "sorry" not in code:
        print(f"Lean accepted the proof on attempt {attempt}")
        break

    messages += [
        {"role": "assistant", "content": msg.content},
        {"role": "user", "content": f"Lean rejected it or the statement changed:\n{log[-4000:]}\nFix the proof."},
    ]

A few details are doing real work here:

For a final check, add #print axioms sum_odd to the end of Proof.lean. Lean lists every axiom the proof relies on, so a smuggled sorryAx or a custom axiom shows up immediately.

Choosing effort, model and token limits

Most of your tuning happens in three settings. Here’s where to start:

Setting Start with Raise it when
model claude-opus-5-5 You need the hardest reasoning: try claude-fable-5-2
output_config.effort high Attempts keep failing on the same step: try xhigh or max
max_tokens 64,000 with streaming Replies hit max_tokens: Opus 5.5 allows up to 128,000
Attempts per theorem 5 Errors change each round, so the model is still making progress
Thinking display summarized Always, while you debug prompts

For large batches of easy lemmas, claude-sonnet-5-5 at medium effort is the cheaper place to start. Measure before you switch: count how many theorems each setup proves within your attempt limit, not how much one request costs. The same principle applies to evals of any formal-math model; our look at DeepSeekMath V2 shows how self-verification changes those numbers.

Keep expectations honest. The Riemann result came from months of expert steering, not one prompt. The API is a strong proof search partner for textbook lemmas, competition problems and the glue steps in your own formalization.

Where trust lives in this setup

Two things in this pipeline need protection: your API key and the theorem statement. Everything else can fail safely.

Schema of a Claude API math pipeline: the theorem statement and Lean kernel are trusted, Claude's output and the retry script are untrusted, and the API key stays in an environment variable on your machine

Keep the key in an environment variable, never in a file or prompt. Keep the statement in version control, so any change is a visible diff. Treat each Proof.lean as untrusted until Lean accepts it with only standard axioms.

Let your coding agent test the Claude math request with Apidog CLI

Once the loop works, the request itself becomes something you depend on: model ID, effort level, headers and the output contract. Hand that to your coding agent. Apidog CLI gives Claude Code, Codex or Cursor a command line into your Apidog project, so the agent can save the request as an endpoint, add a test case that checks the response and run it on demand.

Set it up once:

npm install -g apidog-cli@latest
apidog auth login --with-token <YOUR_TOKEN>
apidog skill install

Then give your agent one prompt:

In Apidog project <projectId>, find POST /v1/messages for the Claude API. Add a
Positive test case that sends my sum_odd Lean prompt to claude-opus-5-5 with
effort high, and assert a 200, stop_reason "end_turn" and a text block that
contains a lean code fence. Run it with my key from $ANTHROPIC_API_KEY and show me the result.

The agent reads the project, looks up the payload shape and only writes after validation passes:

apidog endpoint list --project <projectId>
apidog test-case category --project <projectId>
apidog cli-schema get test-case-create
apidog cli-schema validate test-case-create --file ./sum-odd-case.json
apidog test-case create --project <projectId> --file ./sum-odd-case.json
apidog test-case run <caseId> --project <projectId> --env-var "key=$ANTHROPIC_API_KEY"
A coding agent running Apidog CLI on a sandbox project: it lists the endpoints and the test case categories, then shows the run command for the Claude math test case

--env-var passes your key at run time instead of storing it in the project. High-effort math replies can take minutes, so add --timeout-request 600000 (milliseconds, so ten minutes) if the run gives up too early. This test checks the API contract, not the math: Lean still judges the proof.

The same apidog test-case run ... -r junit command drops into CI, which our Apidog CLI CI/CD guide walks through. For the agent side, see how to use Apidog CLI in Claude Code. Apidog’s Free plan covers up to 4 users.

Conclusion

The Claude API math workflow is short: state the theorem in Lean, ask claude-opus-5-5 at high effort for one Lean file, compile it and loop on the errors. Guard the statement, reject sorry and check the axioms. Download Apidog to let your agent keep the request under test while you work on the theorems.

FAQ

Can the Claude API prove theorems on its own? It can find proofs, but it can’t certify them. Treat every reply as a candidate until a proof checker such as Lean accepts it against a statement you wrote and reviewed.

Which Claude model did Levent Alpöge use for the Riemann proof? No source names it. His note says he worked “with Claude,” and reports since then haven’t identified a model. Any article that names one is guessing.

What effort level should I use for math with the Claude API? Start at high. Claude Opus 5.5 defaults to medium, which is often too shallow for proofs. Move to xhigh or max only when attempts keep failing on the same step and you’ve measured a gain.

Do I need Lean, or can Claude check its own proofs? You need an independent checker. A model reviewing its own work can miss the same mistake twice. Lean’s kernel checks every step mechanically. The Riemann proof passed the official Lean kernel and independent checkers such as nanoda, according to the community certification summary.

Explore more

Best AI Model for Math 2026: Claude vs GPT-6 vs Gemini 4

Best AI Model for Math 2026: Claude vs GPT-6 vs Gemini 4

Claude Fable 5.2, GPT-6.2 Astra and Gemini 4 compared on published math benchmarks: MathArena, HLE-Diamond, LeanLean and RiemannBench, with cost per problem and a way to test them on your own problems.

23 November 2026

Testing AI-Generated API Code: Check It Like Lean Checks Proofs

Testing AI-Generated API Code: Check It Like Lean Checks Proofs

Lean accepted an AI-written proof without trusting its author. Use the same split for your API: a frozen spec, agent-written code, and contract tests the agent runs but can't edit.

23 November 2026

Did Claude Prove the Riemann Hypothesis? What Actually Happened

Did Claude Prove the Riemann Hypothesis? What Actually Happened

Levent Alpöge says he proved the Riemann Hypothesis working with Claude, and the Lean community certified the code. Here's what was claimed, what Lean checked and what's still open.

23 November 2026

Practice API Design-first in Apidog

Discover an easier way to build and use APIs

Claude API Math: How to Write Formal Proofs You Can Check in Lean