# Streaming & Runs

`Agent.Stream` executes the agent loop asynchronously and returns a `*agent.Run` handle whose `Events()` channel delivers ordered runtime events until `agent.RunEnd`. Both `Generate` and `Stream` wrap the same underlying loop, adapting model streaming when available or falling back seamlessly to `Generate`.

## Stream vs. Generate

Choose the adapter that fits your caller:

- **`Generate` / `GenerateWith` / `GenerateMessages`:** Blocks until the run finishes and returns `(*agent.Response, error)`. You can still observe live events during `Generate` by passing `agent.WithSink(...)`.
- **`Stream` / `StreamWith` / `StreamMessages`:** Starts the run in a background goroutine and immediately returns `(*agent.Run, error)` for incremental UI rendering, cancellation, and waiting.

```go
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/ijaidev/gojent/core/agent"
	"github.com/ijaidev/gojent/core/session"
	"github.com/ijaidev/gojent/providers/mockllm"
)

func main() {
	ctx := context.Background()
	model := mockllm.New("Interfaces specify behavior without coupling callers to concrete types.")

	assistant, err := agent.New(agent.Config{
		Name:  "assistant",
		Model: model,
	})
	if err != nil {
		log.Fatal(err)
	}

	run, err := assistant.Stream(ctx, "Explain Go interfaces briefly.",
		agent.WithStore(session.NewMemory()),
		agent.WithSession("demo", "user-1"),
	)
	if err != nil {
		log.Fatal(err)
	}

	for event := range run.Events() {
		switch event := event.(type) {
		case agent.TextDelta:
			fmt.Print(event.Text)
		case agent.RunEnd:
			if event.Err != nil {
				log.Print(event.Err)
			}
		}
	}

	response, err := run.Wait(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("\nTokens: %d\n", response.Usage.TotalTokens)
}
```

## Run lifecycle: Events, Wait, and Cancel

Understanding the `*agent.Run` contract avoids goroutine leaks and blocked dispatchers:

- **`Run.Events()`** returns `<-chan agent.Event`, which terminates with `agent.RunEnd` and closes afterward on normal, drained completion. If the run or context is canceled before events are drained, the channel may close before `agent.RunEnd` is delivered—call `Run.Wait` with a live context when you need the final `(*agent.Response, error)` after cancellation. Events are observations only and cannot alter execution.
- **`Run.Wait(ctx)`** blocks until the run finishes or `ctx` expires and returns the final `(*agent.Response, error)`. **`Wait` does not drain `Events()`**—if you ignore `Events()` without draining or canceling, the internal event dispatcher can block. Always either drain `run.Events()` or call `run.Cancel(...)` (or `run.Close()`) when abandoning a run.
- **`Run.Cancel(cause)`** cancels the run with an explicit cause (`agent.ErrRunCanceled` when `cause` is `nil`). `Run.Close()` calls `Cancel(agent.ErrRunCanceled)` to satisfy `io.Closer`.
- **`Run.Response()`** returns the cached response and error non-blockingly once the run has completed.

## Model streaming and TextDelta.Replace

When a model also implements `llm.Streamer`, the runner calls `Stream(ctx, req)` and translates canonical `llm.StreamEvent` values into `agent.TextDelta`, `agent.ThinkingDelta`, and `agent.ToolCallDelta`. If the model only implements `llm.Model`, the runner falls back to `Generate` automatically.

When `TextDelta.Replace` (or `ThinkingDelta.Replace`) is `true`, `Text` is a **full snapshot** of that content part rather than an incremental suffix—replace your accumulated buffer for `(Step, Index)` instead of appending.

See [Observability](/docs/core/observability) for the full event catalog, or [pkg.go.dev](https://pkg.go.dev/github.com/ijaidev/gojent/core/agent#Run) for the `Run` reference.
