Skip to content
This repository was archived by the owner on Dec 20, 2025. It is now read-only.
This repository was archived by the owner on Dec 20, 2025. It is now read-only.

How to get the usage and cost if the response is streamed? #6

Description

@scottmessinger

I'm unclear how I can both stream the response and get the usage/cost.

To stream:

{:ok, stream} = ExLLM.stream_chat(:openai, messages)

for chunk <- stream do
  case chunk do
    %{content: content} when content != nil ->
      IO.write(content)
      
    %{finish_reason: reason} when reason != nil ->
      IO.puts("\nFinished: #{reason}")
      
    _ ->
      # Other chunk types (role, etc.)
      :ok
  end
end

and

{:ok, response} = ExLLM.chat(:openai, messages)
%ExLLM.Types.LLMResponse{
  content: "I'm doing well, thank you!",
  model: "gpt-4o",
  finish_reason: "stop",
  usage: %{
    input_tokens: 12,
    output_tokens: 8,
    total_tokens: 20
  },
  cost: %{
    input_cost: 0.00006,
    output_cost: 0.00016,
    total_cost: 0.00022,
    currency: "USD"
  }
}

I'm not sure how to get the response if I'm streaming. Is this possible?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions