📚Academy
likeone
online

Streaming & Events

Build real-time UIs by listening to every heartbeat of your agent's thinking process

Why Streaming Matters

When you call query(), you wait for the entire response before seeing anything. For short tasks, that is fine. But when an agent is reading files, running commands, and thinking for 30 seconds, your user stares at a blank screen. Streaming fixes that by sending you each piece of the response as it happens — word by word, tool by tool, event by event.

Real-world analogy: Non-streaming is like ordering food at a restaurant and sitting in silence until the entire meal arrives at once. Streaming is like watching the chef cook through the kitchen window — you see the prep, the sizzle, the plating. Same food, completely different experience.

The Event Stream

When you use streaming mode, the SDK emits a sequence of events that tell you exactly what is happening inside your agent. Each event has a type and a payload:

1
content_block_start
Claude is about to start generating text or requesting a tool. This is your signal to prepare the UI for incoming content.
2
content_block_delta
A chunk of text or tool input has arrived. This is what you append to your display in real time — the "typing" effect users expect from AI interfaces.
3
content_block_stop
A content block is complete. If it was a tool call, the SDK will now execute the tool and continue the loop.
4
tool_use / tool_result
A tool was called and returned a result. You can display this to show users what the agent is doing behind the scenes.

Streaming in Practice

The SDK provides a streaming interface that lets you handle events as they arrive. Here is a complete example:

TypeScript — streaming agent output
import { Claude } from "@anthropic-ai/claude-agent";

const agent = new Claude({
  model: "claude-sonnet-4-6",
  tools: "defaults",
});

// Use the streaming query method
const stream = agent.streamQuery(
  "Read package.json and summarize the project."
);

// Listen for events as they arrive
for await (const event of stream) {
  switch (event.type) {
    case "text_delta":
      // A chunk of text — print it immediately
      process.stdout.write(event.text);
      break;

    case "tool_use":
      // Claude is calling a tool
      console.log(`\n[Tool: ${event.name}]`);
      break;

    case "tool_result":
      // Tool finished — show a brief status
      console.log(`[Tool complete]\n`);
      break;

    case "result":
      // Final result with metadata
      console.log(`\nCost: $${event.cost}`);
      break;
  }
}
🔒

This lesson is for Pro members

Unlock all 355+ lessons across 36 courses with Academy Pro. Founding members get 90% off — forever.

Already a member? Sign in to access your lessons.

Academy
Built with soul — likeone.ai