Tips // Claude in practice

Tips for working better with Claude

One short tip at a time, with an example you can copy. Move through them at random or search for what you need.

APIBasicClaude API

The agent loop ends on stop_reason, not on the text

Keep iterating while stop_reason is tool_use and stop at end_turn; looking for the word "done" in the reply is fragile.

An agent is a loop: you call Claude, check stop_reason, run the requested tools and send back the results. tool_use means it wants to call a tool; end_turn means it finished. Avoid two anti-patterns: parsing the text to know whether it finished, and using a fixed iteration cap as the only brake. max_tokens is another case: the reply was truncated and has to be handled separately.

Example
while True:
    resp = client.messages.create(model=MODEL, max_tokens=1024, tools=tools, messages=messages)
    messages.append({"role": "assistant", "content": resp.content})
    if resp.stop_reason != "tool_use":
        break  # end_turn (or max_tokens: handle it separately)
    results = [{"type": "tool_result", "tool_use_id": b.id, "content": run_tool(b)}
               for b in resp.content if b.type == "tool_use"]
    messages.append({"role": "user", "content": results})
#agents#stop_reason#tool-use