New Tool Radar

Local AI

How to Chat with a Local Ollama Model from a JavaScript Script

Install the official ollama package for JavaScript, send one chat request to the model on your own computer, and print the reply.

Schematic diagram with three steps: install with npm i ollama, write chat.mjs with ollama.chat, then run node chat.mjs and print response.message.content.

If you write JavaScript, the shortest way to call a local model from your own code is the official ollama package. Its README says the Ollama JavaScript library provides the easiest way to integrate your JavaScript project with Ollama, and its API is designed around the Ollama REST API. One install command and a few lines of code are enough to send a chat request to the model on your own computer, with no API key and no cloud account for local use.

Install the package and write one script

Install the package in a project folder with npm i ollama, then save the script below as chat.mjs. The .mjs ending tells Node to treat the file as a module, which is what the README’s import syntax needs. It uses the README’s own example: model llama3.1 and the question “Why is the sky blue?”

import ollama from 'ollama'

const response = await ollama.chat({
  model: 'llama3.1',
  messages: [{ role: 'user', content: 'Why is the sky blue?' }],
})

console.log(response.message.content)

Run it with node chat.mjs. The reply arrives in response.message.content, which the script prints.

Try it: three checks from install to reply

Step Command or check What you should see
1. Ollama is ready ollama pull llama3.1, then curl http://localhost:11434 “Ollama is running”, and the model is downloaded
2. Package is installed npm i ollama The ollama package appears in the project
3. Script runs node chat.mjs A printed answer to “Why is the sky blue?” from the local model

Expected result. We checked the Ollama JavaScript library README. We did not install the package or run a script on this machine.

Limits

The script only works while Ollama is running and the model named in the script is already pulled; a missing model is a download step, not a code error. The README’s chat call also takes a stream option: with stream: true the call returns an async generator and each part arrives separately, so the plain version above is the one to start with. The README shows a browser import, import ollama from 'ollama/browser', for use without Node, and an API key only for the cloud API at ollama.com; local calls need none. We did not test any of this ourselves.

Sources

See all