Streaming responses from a local LLM using Ollama
This example demonstrates how to stream the response of a local LLM through the Ollama HTTP API using JavaScript. Instead of waiting for the complete answer, the script prints each fragment as the model produces it and reports the time to first token.
Requirements
Steps for running this example in the shell
- Install the model in Ollama:
bash
ollama pull gemma3:4b- Install dependencies:
bash
npm install- Run the script:
bash
npm startOptional environment variables
OLLAMA_HOSTdefaults tohttp://localhost:11434OLLAMA_MODELdefaults togemma3:4b
Output
When you run the script, it sends a prompt to a local model through Ollama and prints the answer as it is generated. Once the stream ends, it prints the model name, the time to first token, the total latency, and the token counts reported by the local API. The timings depend on your hardware and on the model you have pulled.