Claude API Tutorial: Build a Chatbot With Tool Use and Streaming
Build a Claude API chatbot with tool use and streaming: set up the SDK, send your first message, stream replies, and wire up tools Claude can call.
By Galactic News Editorial · Published 2026-11-19T13:35:09+00:00 · Updated 2026-11-19T13:35:09+00:00
Claude API Tutorial: Build a Chatbot With Tool Use and Streaming
This Claude API chatbot tutorial takes you from zero to a working chatbot with tool use and streaming. You will create an API key, send your first message, add a tool Claude can call, and stream replies token by token. The whole build uses the official Anthropic Python SDK and the Messages API. By the end you will have a chatbot that looks up real data instead of guessing.
Step 1: Set up the Claude API
Start at the Anthropic Console at console.anthropic.com. Create an account, verify your email, then create an API key in the API Keys section. Keys start with sk-ant- and you only see the key once, so copy it somewhere safe right away.
Install the official Python SDK:
pip install anthropicSet the key as an environment variable. Never paste it into source code or commit it to a repo.
export ANTHROPIC_API_KEY="sk-ant-your-key-here"Every request goes to one endpoint: POST https://api.anthropic.com/v1/messages. The SDK wraps that endpoint. You send a model ID and a list of messages. The max_tokens parameter is required on every request. Claude does not use a default.
Step 2: Send your first message
Create the client and send a message. Use a pinned model ID such as claude-sonnet-4-5 so your code does not silently change behavior when models update.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(message.content[0].text)The response text sits at message.content[0].text. Multi-turn conversation works by passing the full message history with each request. The API is stateless, so your code owns the history. Store it in a list, append each turn, and send the whole list every time.
Claude API chatbot tutorial: add streaming
Waiting for a full reply feels slow in a chatbot. Streaming sends text as it is generated over server-sent events, so users see output immediately. Anthropic recommends streaming for long-running requests and for large max_tokens values, which can otherwise hit HTTP timeouts.
Use the SDK streaming helper:
with client.messages.stream(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Explain streaming in two sentences."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)The stream.text_stream yields text chunks as they arrive. Print them, send them over a websocket, or append them to a chat UI in real time. If you only want the finished message without handling events, call stream.get_final_message() in Python or await stream.finalMessage() in TypeScript.
For finer control, call messages.create with stream=True and iterate over the raw event stream. That gives you every event type: message start, content block deltas, and message stop. The stream() helper is the easier path for most chatbots. The raw stream is for when you need to handle each event explicitly.
Step 4: Add tool use so the chatbot can act
Tool use turns a chatbot into an assistant that can do things. You describe a tool with a name, a description, and a JSON Schema input_schema. When Claude decides the tool would help, it returns a tool_use content block and sets stop_reason to tool_use. Your code runs the tool, returns the result in a tool_result block, and Claude continues.
Define a tool that looks up an order:
tools = [
{
"name": "get_order",
"description": "Look up an order by its ID and return its status.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "The order ID."}
},
"required": ["order_id"],
},
}
]Then run the loop. Send the messages with tools attached. Check the response for a tool_use block. Run your function with the inputs Claude provided. Send the result back as a user message containing a tool_result block with the matching tool_use_id. Call create again so Claude can use the result to answer.
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
messages=messages,
)
for block in response.content:
if block.type == "tool_use":
result = get_order(block.input["order_id"])
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [{"type": "tool_result", "tool_use_id": block.id, "content": result}],
})These are client tools: your app runs them. Server tools such as web search, web fetch, and code execution run on Anthropic's infrastructure. You just declare them. The SDKs also include a tool runner helper that executes your functions and sends results back automatically, so you can skip writing the loop by hand.
Step 5: Combine streaming and tool use
A production chatbot needs both. Streaming keeps the UI responsive. Tool use keeps answers grounded in real data. Combine them by streaming the response and watching for tool_use blocks in the event stream.
Follow these rules when you combine them:
- Stream text deltas to the UI: show text as it arrives.
- Collect tool calls: gather the full input JSON before running the tool.
- Validate inputs: check every argument before executing anything.
- Return results as tool_result blocks: always reference the matching tool_use id.
- Loop until a text answer: keep calling until stop_reason is end_turn.
Watch for fine-grained tool streaming. Setting eager_input_streaming to true on a tool lets Claude stream large tool parameters without buffering or JSON validation. That cuts latency, but you may receive partial or invalid JSON. Handle those edge cases in your code.
Common mistakes to avoid
- Forgetting max_tokens: it is required on every Messages API request.
- Losing history: the API is stateless, so a missing turn breaks the conversation.
- Trusting tool inputs blindly: validate every argument like user input, because it is.
- Skipping the loop: one call is never enough when a tool is involved.
- Exposing the key: keep it in an environment variable or a secret store, never in code.
Bottom line
A Claude API chatbot with tool use and streaming needs four pieces: the Messages API endpoint, a pinned model ID, a streaming loop for the UI, and a tool loop for real data. Start with a single tool, test the full round trip, then add more tools one at a time. The pattern scales from a demo to production without changing shape.