FDE Times dataFDE jobs open 928▲21 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 85Companies hiring 200Remote-friendly 24%Median US pay $200kTop hirer Databricks 107
中文VI

The newspaper of the Forward Deployed Engineer

Guides

One stray parameter can sink a Claude demo. Learn the raw API

Writing the tool-use loop by hand on Claude and OpenAI, then comparing Gemini, teaches you to read the low-level failures that frameworks hide.

ShareLinkedInFacebookX

In brief

  • The Claude Messages API is stateless: every turn you must resend the full history, and remember to return tool_result with its tool_use_id
  • The OpenAI Responses API returns a function_call with a call_id in the output array; you send the result back as function_call_output
  • For new projects Gemini recommends the Interactions API and treats generateContent as legacy; with all three providers the model only proposes a call, and your code runs the function
Diagram of the tool-use loop in two lanes. The top lane is the MODEL (API): it only returns proposals and never runs functions. The bottom lane is YOUR CODE. Step 1: the code sends a request containing history and tools. Step 2: the model proposes a tool call with an id. Step 3, highlighted in orange: the code runs the function get_order_status. Step 4: the code sends the result back with the matching call id. A dashed arrow returns to step 2, noting that the loop repeats while the model keeps proposing calls and has a cap on iterations. A callout reads: if the tool-use loop breaks, check your own code first. Below are three columns of naming. Claude Messages uses stop_reason "tool_use", tool_result and tool_use_id. OpenAI Responses uses a function_call item, function_call_output and call_id. For Gemini, the model proposes a function call, the app returns the result, and id matching is to be checked in the docs. New projects should use the Interactions API.
At all three providers, the model only proposes function calls and your code is what runs them. Only the field names and the way results are matched to calls differ.

A single parameter is enough to wreck a demo. On recent Claude models, setting temperature, top_p or top_k to anything other than the default makes the API return a 400 error. From the 4.6 line onward, prefill is rejected too, so code copied from an old blog post can break right in front of a client.

Frameworks hide these details, but not forever. As an FDE, you will find client systems failing at the lowest layer: a wrong header, a mismatched id, a dropped conversation turn. The fastest way to learn to read those failures is to call the raw API by hand, at least once.

This guide walks through a small script with one tool, get_order_status(order_id), which looks up an order’s status from a mock function. You will go through the full cycle of request, streaming and tool use with Claude and OpenAI, then compare how Gemini handles the same problem. You need Python, API keys in environment variables, and the two SDKs anthropic and openai.

The code below is trimmed for readability and has no error handling or retries. Model names live in two variables, MODEL and OA_MODEL; fill in the current model names from each provider’s docs.

Step 1: why start with curl?

You need to see the raw request before letting an SDK wrap it. The Claude Messages API takes POST /v1/messages, authenticates with the x-api-key header and also needs an anthropic-version header. In Anthropic’s example, max_tokens and the messages array are the two required fields.

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{"model": "'"$CLAUDE_MODEL"'", "max_tokens": 512,
       "messages": [{"role": "user", "content": "Hello"}]}'

Check: you should get back JSON containing a reply. Now send a second turn containing only the new question. The model will remember nothing of the first turn, because the Messages API is stateless: every turn, you must resend the entire conversation history.

So when a client complains that the model “forgot” the previous turn, this is the first place to look.

Step 2: streaming should show text gradually

A user staring at a blank screen for ten seconds will assume the system has hung. With Claude, you set "stream": true to receive the response in pieces over server-sent events. The Python SDK ships a text_stream helper, so you do not have to parse events yourself.

import anthropic
client = anthropic.Anthropic()
history = [{"role": "user", "content": "Explain SSE in 3 sentences"}]

with client.messages.stream(model=MODEL, max_tokens=512,
                            messages=history) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Check: text should appear gradually in the terminal. If the whole paragraph shows up at once, find out whether a proxy or gateway between your machine and the API is buffering the response before passing it on. On a client’s internal network, that is a question worth asking early.

Step 3: the model proposes, your code runs the function

This is the most important idea in the guide. When Claude wants to use a client tool, it returns stop_reason: "tool_use" along with one or more tool_use blocks. Your code runs the function, then sends the result back in a tool_result block. Server tools are different: they run on Anthropic’s infrastructure.

First, write a mock function that returns a string, declare the tool, and write a shared function for calling the API:

def get_order_status(order_id): return f"Order {order_id}: out for delivery"  # mock data

tools = [{"name": "get_order_status",
          "description": "Look up an order's status by its ID",
          "input_schema": {"type": "object",
              "properties": {"order_id": {"type": "string"}},
              "required": ["order_id"]}}]

def ask():
    return client.messages.create(model=MODEL, max_tokens=512,
                                  tools=tools, messages=history)

Then put the question into history and write the loop, with a cap on rounds to avoid looping forever:

history = [{"role": "user", "content": "Where is order A123?"}]
resp = ask()
for _ in range(5):
    if resp.stop_reason != "tool_use":
        break
    history.append({"role": "assistant", "content": resp.content})
    results = [{"type": "tool_result", "tool_use_id": b.id,
                "content": get_order_status(**b.input)}
               for b in resp.content if b.type == "tool_use"]
    history.append({"role": "user", "content": results})
    resp = ask()

Check: add a log line inside get_order_status. If the log line appears and the final answer contains the words “out for delivery” returned by the function, the loop works.

Remember too that tools are not free: the API silently inserts a hidden system prompt to enable tool use, and the tools parameter plus the tool_use and tool_result blocks all count as tokens.

Step 4: OpenAI Responses renames things but keeps the logic

On the Responses API the loop is the same; only the names change. The function call sits in the output array as an item whose type is function_call, carrying a call_id. You return the result as a function_call_output item with that same call_id.

Declare the tool in OpenAI’s format, reusing the schema and mock function from step 3:

import json
from openai import OpenAI
oa = OpenAI()
oa_tools = [{"type": "function", "name": "get_order_status",
             "description": "Look up an order's status by its ID",
             "parameters": tools[0]["input_schema"]}]
inputs = [{"role": "user", "content": "Where is order A123?"}]

Then run one round of function calling and send the result back:

resp = oa.responses.create(model=OA_MODEL, input=inputs, tools=oa_tools)
for item in resp.output:
    if item.type == "function_call":
        args = json.loads(item.arguments)
        inputs.append(item)
        inputs.append({"type": "function_call_output",
                       "call_id": item.call_id,
                       "output": get_order_status(**args)})
resp = oa.responses.create(model=OA_MODEL, input=inputs, tools=oa_tools)

Note that this handles exactly one round of function calling, unlike the capped loop in step 3. If the model proposes further calls after receiving the result, wrap it in a similar for loop that stops when output contains no more function_call items.

Streaming on the Responses API is also switched on with stream=True, but what comes back is a series of semantic events, each with its own type. Before writing any handling logic, print every event.type to see what the event stream looks like:

for event in oa.responses.create(model=OA_MODEL, input=inputs,
                                 tools=oa_tools, stream=True):
    print(event.type)

Check: you will see a sequence of events with a distinct name for each kind. Pick the event that carries new text, and confirm its name against the docs rather than guessing.

Step 5: Gemini is changing APIs, so don’t copy old code

With Gemini, the trap is which API you choose. The current docs recommend the Interactions API for new projects and class generateContent as legacy, so tutorials online that use generateContent may already be out of date. Over REST, the key goes in the x-goog-api-key header.

# Trimmed skeleton: take the endpoint and body from the Interactions API page
curl "$GEMINI_ENDPOINT" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "content-type: application/json" \
  -d @request.json

This guide does not include a ready-made tool-use loop for Gemini, because you should take the Interactions API request structure straight from the docs. The principle is unchanged: Gemini does not run functions itself. It proposes a call, and your application runs the function and sends the result back.

By default, the response arrives only once the model has finished generating, so you must turn on streaming to receive it in pieces.

Extension exercise: rebuild the get_order_status loop on the Interactions API following the docs, with the same question about order A123, then compare how Gemini proposes function calls with the other two providers.

Three APIs, one comparison table

Claude Messages OpenAI Responses Gemini
Streaming stream: true, SSE stream=True, semantic events Turn on streaming to receive pieces
Tool-call signal stop_reason: "tool_use" function_call item in output Model proposes a function call
Returning results tool_result + tool_use_id function_call_output + call_id App sends the result back
History Client resends everything Can keep state on the server Depends on the API you choose

The errors you will hit on real projects

The most common is stale sampling config: if a client’s settings still carry temperature: 0.2 from an older model, a recent Claude model will return a 400. Next comes the missing id: when tool_result lacks tool_use_id or function_call_output lacks call_id, the model cannot tell which call a result belongs to. Then there is stuffing a few dozen tools into every request and being surprised when the token bill soars.

There is also an architectural decision to spell out to the client. Anthropic positions the Messages API for hand-written agent loops that need fine-grained control, while OpenAI says the Responses API preserves reasoning between turns, which Chat Completions cannot do, and runs hosted tools on the server side.

Simon Willison has also pointed out that Responses can manage conversation state on the server for you.

As an FDE, the sensible move is to ask the client two questions in the first meeting: where is conversation history allowed to live, and who will run the tools?

A bank that wants to keep every log inside its own systems will fit a stateless model better, while a startup that needs to ship fast may prefer to hand some of the state management to the server.

Turn the exercise into evidence on your CV

A line saying “experience with LLMs” on a CV does little to prove you understand the layer beneath the framework, yet that is the layer you will be debugging when the framework fails at a client site. Push this script to GitHub with Claude and OpenAI adapters sharing one call_tool interface, plus a README recording every 400 error you hit and how you fixed it.

On your CV, state specifically that you wrote tool-use loops by hand on Claude Messages and OpenAI Responses, and if you did the extension exercise, add the Gemini Interactions API.

When reading job descriptions, look for phrases such as “integrate with multiple model providers” or “build agent loops”. That is the exercise you have just done, and now you can describe it in terms of specific fields, not just framework names.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
10 sources
Read next on the roadmap · Stage 3: Applied AILet eval scores, not instinct, decide when a prompt needs moreA laptop test of zero-shot, few-shot, chain-of-thought and ReAct on 20 labelled tickets shows how to pay for heavier techniques only when the numbers say so.