Skip to main content
Combines Stream() with conversation history — demonstrates event handling so you do not print the same assistant text twice (deltas vs final body). Source: examples/agent_with_stream_conversation/

What it demonstrates

  • Stream with ConversationOptions
  • Distinguishing TEXT_MESSAGE_CONTENT deltas from RUN_FINISHED aggregate content
  • Pattern for chat UIs that stream then finalize

Key code

a, err := agent.NewAgent(
    agent.WithLLMClient(llmClient),
    agent.WithStream(true),
    agent.WithConversation(inMemoryConv),
)

eventCh, err := a.Stream(ctx, prompt, &agent.AgentRunOptions{
    ConversationOptions: &agent.ConversationRunOptions{ID: "demo"},
})
for ev := range eventCh {
    switch ev.Type() {
    case agent.AgentEventTypeTextMessageContent:
        if t, ok := ev.(*agent.AgentTextMessageContentEvent); ok {
            fmt.Print(t.Delta) // stream tokens as they arrive
        }
    case agent.AgentEventTypeRunFinished:
        fmt.Println() // newline after last delta — do NOT reprint full content
    }
}
This example uses in-memory conversation (no Redis required). The key pattern: print deltas on TEXT_MESSAGE_CONTENT and do not reprint RUN_FINISHED.Result.Content — it duplicates the streamed text.

Run

From examples/:
go run ./agent_with_stream_conversation
go run ./agent_with_stream_conversation "What is 5 * 8?"

Expected output

5 * 8 = 40
Tokens print as they stream; the run exits after RUN_FINISHED. Run again with a follow-up — in-memory history carries context within the same process (use Redis + conversation.mdx for cross-process persistence).

Learn more

Stream

Base streaming example

Conversation

Session history