◉CLAUDE LABJP
●2.1.334 — Claude Code 2.1.334: /model now has a search box once the list passes 25 models, matching names and model IDs●FAST — Fast mode for Claude Opus 4.8 ended on 11/30. Drop speed: "fast" and Opus 4.8 keeps working●OPUS 4.5 — claude-opus-4-5 retires on 2027/1/22, 50 days from now. The replacement is claude-opus-5-5●IME — On the Windows desktop app, pressing Enter to confirm Japanese IME input can send the message early●NEW — New: Compare tool-use requests across three routes before moving to Bedrock●MCP — More setups now share one local MCP server across Claude Code, Cursor and Antigravity●2.1.334 — Claude Code 2.1.334: /model now has a search box once the list passes 25 models, matching names and model IDs●FAST — Fast mode for Claude Opus 4.8 ended on 11/30. Drop speed: "fast" and Opus 4.8 keeps working●OPUS 4.5 — claude-opus-4-5 retires on 2027/1/22, 50 days from now. The replacement is claude-opus-5-5●IME — On the Windows desktop app, pressing Enter to confirm Japanese IME input can send the message early●NEW — New: Compare tool-use requests across three routes before moving to Bedrock●MCP — More setups now share one local MCP server across Claude Code, Cursor and Antigravity
Articles/API & SDK
⬡ API & SDK/2026-12-03Intermediate

Calling Claude and Gemini from One Code Path: Folding Their Stop Reasons into Six States

Claude's stop_reason and Gemini's finishReason do not map one to one. A standard-library Python function that folds tool calls, truncation, refusals, and resumable pauses into six app-level states, checked against 17 fixtures, plus why the raw value still belongs in your logs.

Claude API152Gemini APIstop_reason4Python35Indie Development13

It was early evening, and I was adding a Gemini route to a small script that translates store descriptions into several languages. I already use Gemini for image classification in my wallpaper app, so I assumed swapping the client call would be most of the work.

What stopped me was the if block after the response comes back. On the Claude side, I branch on stop_reason: run a tool, handle a cut-off answer, or deal with a refusal. When I tried to build the same table for Gemini, there was simply no row that matched Claude's tool_use.

The short version: you can't translate one provider's stop reasons into the other's. What worked for me was folding both into the state my app actually cares about — what should happen next — and the branching got much shorter.

Lined up side by side, the values don't pair off

Putting Claude's list (Stop reasons and fallback) next to Gemini's (the FinishReason enum in the JS SDK), the mismatches came in three shapes.

MismatchClaudeGemini
Only one side has ittool_use, pause_turnNo function-call reason; you detect calls through functionCall in parts
One side merges themend_turn and stop_sequence are separateBoth are STOP
One side splits themA single refusal, with details in stop_detailsSAFETY, RECITATION, PROHIBITED_CONTENT, SPII, and more

Gemini's own sample code checks parts, not finishReason, to decide whether the model wants a function called. In other words, "why it stopped" and "whether it wants a tool" live in two different places.

The counts don't line up either. Claude has seven stop reasons; the Gemini JS SDK enum lists 24, including values for image generation and server-side tool loops.

Deciding on six states for the app

So I stopped mapping values and started mapping next steps. For my own script, six states covered everything.

StateMeaningClaudeGemini
doneSafe to use the answerend_turn, stop_sequenceSTOP with no function call
tool_callRun the tool and send back the resulttool_useSTOP plus functionCall
truncatedThe output was cut offmax_tokens, model_context_window_exceededMAX_TOKENS
resumeSend the content back and continuepause_turnnone
blockedStopped for safety reasonsrefusalSAFETY and friends, or an input-side blockReason
unknownUnexpected; log it, don't crashanything unrecognizedMALFORMED_FUNCTION_CALL, anything unrecognized

There's a reason truncated holds two Claude values. With max_tokens, raising the limit gets you the rest. model_context_window_exceeded means the context window itself filled up, so raising max_tokens won't help. The state is the same; the hint attached to it is not.

The folding function, standard library only

It takes the raw REST response as a dict and returns one of the six states plus a hint for the next step. If you use the SDK objects, convert them first (for example with model_dump()).

"""Fold Claude and Gemini stop reasons into six app-level states (stdlib only)."""
from dataclasses import dataclass, field
 
@dataclass
class Stop:
    kind: str                 # done / tool_call / truncated / resume / blocked / unknown
    raw: str                  # the provider's original value (always log this too)
    hint: str = ""            # what to do next
    detail: dict = field(default_factory=dict)
 
CLAUDE = {
    "end_turn": ("done", ""),
    "stop_sequence": ("done", "check stop_sequence to see which one fired"),
    "tool_use": ("tool_call", "run the tool and return tool_result"),
    "max_tokens": ("truncated", "raise max_tokens or ask for the rest"),
    "model_context_window_exceeded": ("truncated", "trim the input; raising max_tokens won't help"),
    "pause_turn": ("resume", "send content back unchanged as the assistant turn"),
    "refusal": ("blocked", "a retry on another Claude model usually works"),
}
 
GEMINI_BLOCKED = {"SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII",
                  "IMAGE_SAFETY", "IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION"}
GEMINI_BROKEN = {"MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "MALFORMED_RESPONSE"}
 
def from_claude(resp: dict) -> Stop:
    raw = resp.get("stop_reason") or "null"
    kind, hint = CLAUDE.get(raw, ("unknown", "unrecognized value; log it, don't crash"))
    detail = {}
    if raw == "end_turn" and not resp.get("content"):
        hint = "empty end_turn; don't resend the same request unchanged"
        detail["empty"] = True
    if raw == "refusal":
        d = resp.get("stop_details") or {}
        detail = {"category": d.get("category")}
        if d.get("category") == "reasoning_extraction":
            hint = "fix the prompt instead of switching models"
    return Stop(kind, raw, hint, detail)
 
def from_gemini(resp: dict) -> Stop:
    cands = resp.get("candidates") or []
    if not cands:  # blocked at the input stage: no candidates at all
        reason = (resp.get("promptFeedback") or {}).get("blockReason", "NO_CANDIDATE")
        return Stop("blocked", f"prompt:{reason}", "stopped on input; retrying the output won't fix it")
    c = cands[0]
    raw = c.get("finishReason") or "null"
    parts = (c.get("content") or {}).get("parts") or []
    calls = [p["functionCall"] for p in parts if "functionCall" in p]
    if raw == "STOP" and calls:  # there is no dedicated function-call finishReason
        return Stop("tool_call", raw, "run the functionCall entries in parts", {"calls": len(calls)})
    if raw == "STOP":
        return Stop("done", raw, "can't tell whether a stop sequence fired")
    if raw == "MAX_TOKENS":
        return Stop("truncated", raw, "raise max_output_tokens or ask for the rest")
    if raw in GEMINI_BLOCKED:
        return Stop("blocked", raw, "avoid retrying the same input")
    if raw in GEMINI_BROKEN:
        return Stop("unknown", raw, "check the function declarations and call shape")
    return Stop("unknown", raw, "unrecognized value; log it, don't crash")

Why a lookup table with an unknown fallback? Gemini's enum already carries values for image generation and server-side tools, and sooner or later a value you've never seen will arrive. If that raises a KeyError, an unattended batch dies one morning for no visible reason. I'd rather send surprises to "log it and let a person look."

Only Claude's refusal also reads stop_details.category. According to Refusals and fallback, most refusals can be answered by retrying on another Claude model — except reasoning_extraction (asking the model to write out its internal reasoning in the reply), where the guidance is to change the prompt instead.

Checking the branches against 17 fixtures

To test the branching without calling either API, I built 17 dicts in the same shape as the official response examples — 10 for Claude, 7 for Gemini — and ran them through.

from stop_norm import from_claude, from_gemini
 
C = [
    ({"stop_reason": "end_turn", "content": []}, "done"),
    ({"stop_reason": "model_context_window_exceeded", "content": [{"type": "text", "text": "..."}]}, "truncated"),
    ({"stop_reason": "refusal", "content": [],
      "stop_details": {"type": "refusal", "category": "reasoning_extraction"}}, "blocked"),
    ({"stop_reason": "something_new", "content": []}, "unknown"),
    # plus end_turn, stop_sequence, tool_use, max_tokens, pause_turn, refusal(cyber)
]
G = [
    ({"candidates": [{"content": {"parts": [{"functionCall": {"name": "f", "args": {}}},
                                            {"functionCall": {"name": "g", "args": {}}}]},
                      "finishReason": "STOP"}]}, "tool_call"),
    ({"promptFeedback": {"blockReason": "SAFETY"}}, "blocked"),
    ({"candidates": [{"finishReason": "TOO_MANY_TOOL_CALLS"}]}, "unknown"),
    # plus STOP, MAX_TOKENS, SAFETY, MALFORMED_FUNCTION_CALL
]
for fn, cases in ((from_claude, C), (from_gemini, G)):
    for resp, want in cases:
        s = fn(resp)
        print("OK" if s.kind == want else "NG", s.raw, "->", s.kind, s.hint)

All 17 landed where I expected. A few lines from the run (the hints were in Japanese in my copy; translated here):

OK claude end_turn                         -> done      empty end_turn; don't resend the same request unchanged
OK claude model_context_window_exceeded    -> truncated trim the input; raising max_tokens won't help
OK claude refusal                          -> blocked   fix the prompt instead of switching models
OK gemini STOP                             -> tool_call run the functionCall entries in parts
OK gemini prompt:SAFETY                    -> blocked   stopped on input; retrying the output won't fix it
OK gemini TOO_MANY_TOOL_CALLS              -> unknown   unrecognized value; log it, don't crash
17/17 passed

TOO_MANY_TOOL_CALLS means the server-side tool loop stopped before producing a final answer. It feels close to Claude's pause_turn, but I haven't confirmed that continuing works the same way, so I deliberately kept it out of resume. I'd rather route an unverified mapping to a human than write it into the table as fact.

Keep the raw value, even after folding

At one point I nearly switched to logging only kind. The branching was down to one path, so one field felt like enough. But on a day with a run of blocked, if I can't tell whether it was a Claude refusal or a Gemini input-side blockReason, I can't tell where to fix it.

Branch on six states; log the raw value. That's the line I keep now. Stop.raw always goes into the log, and on days an unknown shows up, the table grows by one row.

Three places that tend to bite

Refusals come back as HTTP 200. Claude's refusal is a normal response, not an exception, so a plain try/except lets it walk straight through. With streaming, a refusal can arrive after some text has already appeared; the docs say to discard that partial output.

When streaming, stop_reason starts out null. Claude sends null in message_start and fills it in only in message_delta. Call the folding function on the first event and everything becomes unknown. On the Gemini side, a stream stopped by SAFETY can arrive with empty content.

Don't resend an empty end_turn unchanged. The docs note that adding text right after tool results can teach Claude to end its turn there. Checking for stray text after your tool_result blocks is usually faster than retrying.

I looked at answers that change without any error after a model switch in After Sonnet 4.5 Retired: Checking the Three Things That Change Without an Error. If truncated leaves you with broken JSON, a four-layer defense that outlived prefill may help.

One next step

Search your code for the if statements that compare stop_reason or finishReason as raw strings, and replace just one of them with a call to the folding function. The 17 fixtures above work fine as a starting point, and once they settle in, keeping them next to your golden-dataset regression tests means a model switch gets checked in one pass.

As an indie developer using two providers, I keep getting pulled toward whichever one I wrote first. Match the next step, not the value — that's the idea I plan to keep even on the day a third provider joins the script.

Share

Thank You for Reading

Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

⬡ API & SDK2026-11-25
After Sonnet 4.5 Retired: Checking the Three Things That Change Without an Error, Even When the Old Model No Longer Answers
claude-sonnet-4-5 retired from the Claude API on November 30, 2026, and calls now return a 404. Switching to claude-sonnet-5-5 raises no 400, yet thinking runs by default, max_tokens covers more than the answer, and stop_reason shifts. Three ways to fill the 'before' column after retirement (old logs, Bedrock, thinking on vs. off), a troubleshooting table, and how to get ahead of the Opus 4.5 deadline.
⬡ API & SDK2026-04-18
Building a Real-Time AI Processing Pipeline with Claude API and Apache Kafka
Learn how to integrate Claude API into Apache Kafka event streams with production-grade patterns. Implement smart buffering, model routing, and Dead Letter Queues to run large-scale real-time AI analysis at low cost.
⬡ API & SDK2026-04-11
Monetizing SaaS with Claude API: Your Roadmap to ¥100K Monthly
A practical guide to building a profitable SaaS business using the Claude API. Learn pricing design, user acquisition, API cost optimization, and a roadmap to reaching your first ¥100K/month.