---
title: "Stream a model's answer as it is written"
slug: "streaming-responses"
description: "Turn on streaming, read the server-sent events with curl and then line by line in Go, and see why the first word arrives long before the last."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-llm/streaming-responses"
---

# Stream a model's answer as it is written

How do you show an answer word by word instead of waiting for the whole reply?

## Run it against a real free API

The outputs in this lesson are simulated by a local mock server. To get real answers, create a free key at Mistral AI Free Plan and set these variables. Never put the key in your code.

```sh
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key
```

[Mistral AI Free Plan: what is free and how to get a key](https://aifree.dev/offer/mistral-ai-free-plan)

## Predict

You add "stream": true to a chat request. What comes back?

- One JSON object, just faster
- Many small events, each with a few words, then an end marker
- The reply as a downloadable file

Answer: Many small events, each with a few words, then an end marker — The server keeps the connection open and sends an event per piece of text, then a final marker.

You will see the raw events next.

## Server-sent events

With `"stream": true` the server keeps the response open and sends **server-sent events**: lines that start with `data: `, each holding one JSON chunk, separated by a blank line. The last event is the literal text `data: [DONE]`. The chunk's `object` is `chat.completion.chunk`, and your code stops reading when it sees `[DONE]`.

## Raw chunks with curl

```sh
curl -sN "$LLM_BASE_URL/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $LLM_API_KEY" \
  -d '{
    "model": "'"$LLM_MODEL"'",
    "stream": true,
    "messages": [{"role": "user", "content": "Hello"}]
  }'
```

Output:

```
data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{"content":"Hello!"},"finish_reason":null}]}

data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{"content":" How"},"finish_reason":null}]}

data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{"content":" can"},"finish_reason":null}]}

data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{"content":" I"},"finish_reason":null}]}

data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{"content":" help"},"finish_reason":null}]}

data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{"content":" you"},"finish_reason":null}]}

data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{"content":" today?"},"finish_reason":null}]}

data: {"id":"chatcmpl-mock-0001","object":"chat.completion.chunk","created":1796256000,"model":"mock-chat-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

```

_Simulated response (local mock server), 2026-12-03._

`curl -N` turns off buffering, so each event prints as it arrives. This is the simulated output.

## Delta, not message

Each chunk has a `delta` instead of a `message`. The first delta carries the role, the next ones carry a few characters of `content`, and the last one is empty with a `finish_reason`. Your code joins the pieces. Streaming matters because the time to the first word is short even when the whole answer is long, so the page feels fast and the user can stop early.

## Print each piece as it arrives

```go
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model":    os.Getenv("LLM_MODEL"),
		"stream":   true,
		"messages": []map[string]string{{"role": "user", "content": "Hello"}},
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer res.Body.Close()

	scanner := bufio.NewScanner(res.Body)
	for scanner.Scan() {
		data, ok := strings.CutPrefix(scanner.Text(), "data: ")
		if !ok {
			continue
		}
		if data == "[DONE]" {
			break
		}
		var chunk struct {
			Choices []struct {
				Delta struct {
					Content string `json:"content"`
				} `json:"delta"`
			} `json:"choices"`
		}
		if err := json.Unmarshal([]byte(data), &chunk); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		fmt.Print(chunk.Choices[0].Delta.Content)
	}
	fmt.Println()
}
```

Output:

```
Hello! How can I help you today?
```

_Simulated response (local mock server), 2026-12-03._

`bufio.Scanner` reads the body line by line. The program prints each delta without a newline and adds one at the end.

## Fix it

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model":    os.Getenv("LLM_MODEL"),
		"stream":   true,
		"messages": []map[string]string{{"role": "user", "content": "What is the capital of France?"}},
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	var out struct {
		Choices []struct {
			Delta struct {
				Content string `json:"content"`
			} `json:"delta"`
		} `json:"choices"`
	}
	if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
		fmt.Fprintln(os.Stderr, "decode:", err)
		os.Exit(1)
	}
	fmt.Println(out.Choices[0].Delta.Content)
}
```

The program fails before it prints anything. Why?

- A streamed body is not one JSON object
- The server does not support streaming
- The Content-Type header is missing

Answer: A streamed body is not one JSON object — It is a series of data: lines, so decoding the whole body as one object fails at the first character.

Error message:

```
decode: invalid character 'd' looking for beginning of value
```

Fixed:

```go
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func main() {
	payload, _ := json.Marshal(map[string]any{
		"model":    os.Getenv("LLM_MODEL"),
		"stream":   true,
		"messages": []map[string]string{{"role": "user", "content": "What is the capital of France?"}},
	})
	req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY"))
	res, _ := http.DefaultClient.Do(req)
	defer res.Body.Close()

	scanner := bufio.NewScanner(res.Body)
	for scanner.Scan() {
		data, ok := strings.CutPrefix(scanner.Text(), "data: ")
		if !ok {
			continue
		}
		if data == "[DONE]" {
			break
		}
		var chunk struct {
			Choices []struct {
				Delta struct {
					Content string `json:"content"`
				} `json:"delta"`
			} `json:"choices"`
		}
		json.Unmarshal([]byte(data), &chunk)
		fmt.Print(chunk.Choices[0].Delta.Content)
	}
	fmt.Println()
}
```

Output:

```
The capital of France is Paris.
```

_Simulated response (local mock server), 2026-12-03._

## Say it back

Explain to a friend why a streamed answer feels faster, and how your code knows the answer is complete.

Our sentence: The server sends the answer in small pieces as the model writes it, so the first words show up almost at once instead of after the whole reply is done. My code reads the data lines, prints each delta, and stops when it gets the data: [DONE] marker.

## Mission (10 min)

Use your free key from the offer at the top of the lesson. Run the Go program against it and watch the words arrive. Then ask for a long answer and measure how long the first word takes compared with the last.

```sh
export LLM_BASE_URL=<base URL from the offer page>
export LLM_MODEL=<model id from the offer page>
export LLM_API_KEY=<your key>
go run main.go
```

## Common questions

### What is time to first token?

It is the delay between sending a request and receiving the first piece of the answer. With streaming you can show text after that short delay, even if the whole answer takes many seconds. Without streaming you wait for every token before you see anything, which feels slow for long answers, so chat products almost always stream.

### How do I know when a streamed answer is finished?

Two signals mark the end. The last chunk carries a finish_reason such as stop, and after it the server sends the literal line data: [DONE]. Your loop should stop on [DONE] and should also handle the connection closing early, for example when the network drops, because then the answer you printed is incomplete.

### Can I stream and still get the token usage?

Usually yes, but it depends on the provider. Many APIs add the usage in a last chunk only when you ask for it with a stream option, and some always send it. Check your provider's documentation. The mock server in this lesson does not send usage in streams, so the examples print only the text.

## Sources

- https://platform.openai.com/docs/api-reference/chat/streaming (read 2026-12-03)
- https://docs.mistral.ai/capabilities/completion/ (read 2026-12-03)
- https://pkg.go.dev/bufio (read 2026-12-03)
- https://pkg.go.dev/net/http (read 2026-12-03)

Simulated responses from a local mock server, not from a real model. Run with local mock server (scripts/course-llm-mock.ts), go1.27.4 darwin/arm64, curl on 2026-12-03.
