Subscribe

Streaming structured JSON output from OpenAI and Anthropic in golang with plain net/http

One small golang interface over OpenAI and Anthropic that asks for JSON matching a schema and streams it as it arrives. No SDKs, a hand-written SSE reader with a bigger buffer, and error messages clipped before they reach the logs.

Streaming structured JSON output from OpenAI and Anthropic in golang with plain net/http

We wanted a golang API to ask a model for an answer that our code can parse, and to show that answer on screen while it is still being written. Both OpenAI and Anthropic can do this now. You send a JSON schema, the model is held to it, and with streaming on you get the JSON in small pieces over server-sent events (SSE).

We could have pulled in two SDKs. We didn't. The part we actually use is one POST and one stream per provider, and plain net/http keeps the dependency list short and makes every byte that goes out easy to see. In this blog we will look at the small interface over both providers, the SSE reader, the two provider clients, and how I tested all of it against a local httptest server, without a single real API call.

One interface for both

The rest of the code only sees this:

// Request is one call. Schema is a JSON schema for the answer.
type Request struct {
    System     string
    User       string
    SchemaName string
    Schema     map[string]any
    MaxTokens  int
}

// Result is a finished call. Text is empty when the model refused or ran out
// of tokens, because then the JSON is not complete.
type Result struct {
    Text         string
    StopReason   string
    InputTokens  int64
    OutputTokens int64
    CachedTokens int64
}

// Client is one provider.
type Client interface {
    Complete(ctx context.Context, req Request) (Result, error)
    Stream(ctx context.Context, req Request, onText func(string)) (Result, error)
}

onText gets each piece of text as it arrives, so the handler can forward it to the browser. The Result at the end has the full text and the token counts, including cached tokens, which is what you want for a cost log.

One rule we kept in the real service: one provider per environment, picked by config, and never an automatic fallback from one to the other. The prompts carry user data. Where that data goes should be a decision someone made, not something a retry loop decided at 2 AM.

Reading SSE by hand

SSE is a simple format. Lines of field: value, and a blank line ends an event. OpenAI only sends data: lines. Anthropic also sends an event: line with the event name. Lines starting with : are comments, some servers send them as keep-alives.

type event struct {
    Name string // the "event:" line, Anthropic sets it, OpenAI does not
    Data string
}

// maxLine is the longest SSE line we accept. bufio.Scanner stops at 64 KiB by
// default and a final usage event or an error can be longer than that.
const maxLine = 1 << 20

// readSSE calls fn for every event in body until the stream ends or fn
// returns an error.
func readSSE(body io.Reader, fn func(event) error) error {
    sc := bufio.NewScanner(body)
    sc.Buffer(make([]byte, 0, 64*1024), maxLine)

    var ev event
    var data []string

    flush := func() error {
        if len(data) == 0 {
            ev = event{}
            return nil
        }
        ev.Data = strings.Join(data, "\n")
        err := fn(ev)
        ev, data = event{}, nil
        return err
    }

    for sc.Scan() {
        line := sc.Text()
        switch {
        case line == "":
            if err := flush(); err != nil {
                return err
            }
        case strings.HasPrefix(line, ":"):
            // comment, used as a keep-alive by some servers
        case strings.HasPrefix(line, "event:"):
            ev.Name = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
        case strings.HasPrefix(line, "data:"):
            data = append(data, strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " "))
        }
    }
    if err := sc.Err(); err != nil {
        return err
    }
    return flush() // a last event without a blank line after it
}

The sc.Buffer line is the one people miss. bufio.Scanner has a default limit of 64 KiB per line, and when a line is longer it just stops with bufio.ErrTooLong. The text deltas are tiny so everything works in testing. Then one day an error body or a big final event shows up on one line and the stream dies half way. I wrote a test that proves the default really fails, because I wanted to see it and not just trust a comment:

func bigEvent() string {
    return "data: {\"pad\":\"" + strings.Repeat("x", 100*1024) + "\"}\n\n"
}

// The default bufio.Scanner gives up on a line over 64 KiB.
func TestDefaultScannerFailsOnBigLine(t *testing.T) {
    sc := bufio.NewScanner(strings.NewReader(bigEvent()))
    for sc.Scan() {
    }
    if !errors.Is(sc.Err(), bufio.ErrTooLong) {
        t.Fatalf("err = %v, want bufio.ErrTooLong", sc.Err())
    }
}

It passes, so yes, a 100 KiB line kill the default scanner. With the buffer raised to 1 MiB the same event goes through readSSE fine.

The OpenAI side

OpenAI's Chat Completions API takes the schema under response_format. With strict: true every property must be listed in required and objects need "additionalProperties": false, or the request is rejected. With streaming on, stream_options.include_usage adds one last chunk that has the usage and an empty choices list. Without it you get no token counts at all for a streamed call.

func (c *OpenAI) body(req Request, stream bool) ([]byte, error) {
    b := map[string]any{
        "model": c.Model,
        "messages": []map[string]string{
            {"role": "developer", "content": req.System},
            {"role": "user", "content": req.User},
        },
        "response_format": map[string]any{
            "type": "json_schema",
            "json_schema": map[string]any{
                "name":   req.SchemaName,
                "schema": req.Schema,
                "strict": true,
            },
        },
    }
    if req.MaxTokens > 0 {
        b["max_completion_tokens"] = req.MaxTokens
    }
    if stream {
        b["stream"] = true
        b["stream_options"] = map[string]bool{"include_usage": true}
    }
    return json.Marshal(b)
}

The stream handler skips [DONE], collects delta.content, remembers a delta.refusal and the finish_reason:

err = readSSE(resp.Body, func(ev event) error {
    if ev.Data == "[DONE]" {
        return nil
    }
    var ch oaChunk
    if err := json.Unmarshal([]byte(ev.Data), &ch); err != nil {
        return fmt.Errorf("openai: bad chunk: %w", err)
    }
    if ch.Error != nil {
        return fmt.Errorf("openai: stream error: %s", clip(ch.Error.Message))
    }
    ch.usageInto(&out) // the last chunk has usage and no choices

    for _, c := range ch.Choices {
        if c.Delta.Refusal != "" {
            refused = true
        }
        if c.Delta.Content != "" {
            text.WriteString(c.Delta.Content)
            if onText != nil {
                onText(c.Delta.Content)
            }
        }
        if c.FinishReason != "" {
            out.StopReason = c.FinishReason
        }
    }
    return nil
})

At the end, a refusal or finish_reason: "length" leaves Text empty. Half a JSON object is not an answer. We treat those as a failed call that the caller can retry, separate from a transport error.

In the real code there's one more knob: a reasoning effort setting with a special value default that leaves the field out of the request, for a model that rejects it. Small thing, but it means a model switch is only a config change and never a code change.

The Anthropic side

Anthropic's Messages API takes the schema under output_config.format. (There was an older output_format parameter during the beta, it is deprecated now.) The headers are x-api-key and anthropic-version.

func (c *Anthropic) body(req Request, stream bool) ([]byte, error) {
    maxTokens := req.MaxTokens
    if maxTokens <= 0 {
        maxTokens = 16000
    }
    return json.Marshal(map[string]any{
        "model":      c.Model,
        "max_tokens": maxTokens,
        "system":     req.System,
        "messages":   []map[string]string{{"role": "user", "content": req.User}},
        "output_config": map[string]any{
            "format": map[string]any{"type": "json_schema", "schema": req.Schema},
        },
        "stream": stream,
    })
}

The stream has named events: message_start carries input and cache read tokens, content_block_delta carries the text, message_delta carries the stop reason and final output tokens, and error can arrive in the middle of a stream with HTTP 200 already sent. There are also ping events and start/stop events for each block, which we ignore.

switch e.Type {
case "message_start":
    if e.Message != nil {
        out.InputTokens = e.Message.Usage.InputTokens
        out.CachedTokens = e.Message.Usage.CacheReadTokens
    }
case "content_block_delta":
    // thinking_delta and signature_delta also arrive here; only
    // text_delta is part of the JSON answer
    if e.Delta != nil && e.Delta.Type == "text_delta" {
        text.WriteString(e.Delta.Text)
        if onText != nil {
            onText(e.Delta.Text)
        }
    }
case "message_delta":
    if e.Delta != nil {
        out.StopReason = e.Delta.StopReason
    }
    if e.Usage != nil {
        out.OutputTokens = e.Usage.OutputTokens
    }
case "error":
    msg := "stream error"
    if e.Error != nil {
        msg = e.Error.Message
    }
    return fmt.Errorf("anthropic: %s", clip(msg))
}

The text_delta check matters more than it used to. Most current Claude models think before they answer, and on Claude Opus 5.5 that can't be turned off. Thinking comes as its own content block before the text, with thinking_delta and signature_delta events. If you append every delta to the answer you get thinking text glued to the front of your JSON. Thinking also counts against max_tokens, so don't set it tight: a max_tokens stop means the JSON got cut, and our code returns empty Text for it, same as a refusal.

I send anthropic-version: 2023-06-01. There is a newer API version, 2026-10-21; the main breaking change in it for a request like this is that temperature, top_p and top_k are rejected, and we don't send them, so moving later is a header change. For the model, the config default I'd use today is claude-opus-5-5.

Clipping errors before they hit the logs

When a call fails, the provider sends an error body. It's tempting to log the whole thing. Don't. The request carried user data, and some error messages quote parts of the input back. So we read at most 64 KiB, pull out only the provider's own message field, never the raw body, and clip that to 512 characters:

const maxErrLen = 512

func clip(s string) string {
    s = strings.TrimSpace(s)
    if len(s) > maxErrLen {
        return s[:maxErrLen] + "..."
    }
    return s
}

A long error still tells you what went wrong in the first 100 characters. The rest is mostly an echo of your own prompt.

Testing without an API key

I had no keys for this post and didnt want any either. Everything is tested against httptest.NewServer handlers that write SSE the same way the providers do, with a flush after each event. The base URL is a field on each client, so the test just points it at the local server:

c := &Anthropic{APIKey: "test-key", BaseURL: srv.URL, Model: "test-model", HTTP: srv.Client()}
res, err := c.Stream(context.Background(), req(), nil)

The Anthropic test stream has a thinking block with a signature_delta, a ping, then the text in two deltas, and checks that Text is exactly {"city":"Pune","score":8} with input, cached and output tokens right. Other tests cover a max_tokens stop with half a JSON (Text must be empty), a 401 with a JSON error body, an OpenAI stream with the usage chunk at the end, and a 2,800 character error message that must come out clipped.

go vet ./...
go test -race -count=1 ./...

All seven tests passed on Go 1.27.3. There is also a small cmd/fake that starts a local server sending a fake Claude stream with 150 ms between deltas and prints each piece with a timestamp:

  0.15s  {"city":"Chennai",
  0.31s  "reasons":["beach",
  0.46s  "food",
  0.61s  "filter coffee"],
  0.76s  "score":9}
stop=end_turn in=42 out=27
text={"city":"Chennai","reasons":["beach","food","filter coffee"],"score":9}

Funny thing, my first version of that fake server added a comma after every chunk, the last one too. The output ended in 9}, and nothing complained. Not the parser, not the stop reason, nothing. That is a good reminder that streaming gives you text, not JSON. Even with a schema enforced on the provider side, run json.Unmarshal on the final Text before you trust it, and treat a failure like any other failed call. I added a json.Valid check to the demo after that.

What I couldn't check here is the real APIs. The request shapes and event names come from the providers' current docs, and the tests prove my code handles them, but before you ship, make one real call to each with your own key and compare.

If you want the same "one interface, swap by config" idea for local models, I did that for Gemini and Ollama in switching between Gemini and Ollama behind one Go interface. And for why a schema alone doesn't make a small model give good answers, see why a 1B Ollama model failed as a trading risk gate.