# `HuggingfaceClient.StreamHelpers`
[🔗](https://github.com/huggingface/huggingface_client/blob/v0.1.0/lib/huggingface_client/stream_helpers.ex#L1)

Utilities for consuming streaming chat-completion responses.

All functions accept a stream of OpenAI-style `chat.completion.chunk` maps
(the decoded JSON objects emitted by `HuggingfaceClient.SSE.parse_stream_json/1`).

# `async_collect`

```elixir
@spec async_collect(Enumerable.t()) :: Task.t()
```

Runs `collect_content/1` asynchronously in a `Task`.

Returns a `Task` that resolves to `{:ok, full_text}` or `{:error, exception}`.

# `collect_content`

```elixir
@spec collect_content(Enumerable.t()) :: String.t()
```

Collects all content tokens from a chunk stream into a single string.

Nil deltas and stop-reason chunks are silently ignored.

# `collect_response`

```elixir
@spec collect_response(Enumerable.t()) :: map()
```

Assembles a complete `"chat.completion"` response map from a chunk stream.

Uses the last chunk's metadata (id, model, created) and concatenates all content tokens.
Returns a map with `"object" => "chat.completion"` even for an empty stream.

# `content_stream`

```elixir
@spec content_stream(Enumerable.t()) :: Enumerable.t()
```

Returns a lazy stream of non-empty content strings from a chunk stream.

Stop-reason and nil-delta chunks produce no elements.

# `each_content`

```elixir
@spec each_content(Enumerable.t(), (String.t() -&gt; any())) :: :ok
```

Calls `callback` for each non-empty content token.  Returns `:ok`.

# `stream_to_pid`

```elixir
@spec stream_to_pid(Enumerable.t(), pid(), atom()) :: :ok
```

Streams content tokens to a PID as `{tag, token}` messages, then `{tag, :done}`.

On stream error sends `{tag, {:error, exception}}`.  Defaults `tag` to `:hf_stream`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
