Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ollama API Interaction

Programmatic Access to the Ollama REST API

After installation, Ollama provides a full set of REST APIs on local port 11434, covering text generation, chat, vector embedding, and model management, and offers two compatible protocols: OpenAI and Anthropic.

This article explains each core interface in detail: request structure, streaming, usage statistics, and error handling, so that any language can access local models.


Two Base URLs and Authentication Methods

Ollama's API has two entry points, local and cloud, with different authentication rules.

Ollama API overview: callers, service endpoints, local models, and Cloud

Entry point Base URL Authentication
Local service http://localhost:11434/api No authentication required
Local service (compatible protocol) http://localhost:11434/v1 No authentication required; api_key can be any value
Ollama Cloud https://ollama.com/api Authorization: Bearer + API Key

The local service is authentication-free by default and works out of the box; when directly connecting to the cloud interface at ollama.com, first create an API Key on the official website's settings page and put it in the request header.


Text Generation: /api/generate

generate is the most basic single-turn generation interface; just pass in the model name and prompt:

Example

curl http:

//

localhost:

11434

/

api

/

generate

-d

'{
  "model": "qwen3.5",
  "prompt": "Introduce RUNOOB Runoob Tutorial in one sentence",
  "stream": false
}'

When stream is set to false, a single JSON object is returned:



{

  "model": "qwen3.5",

  "created_at": "2026-08-29T03:20:00.499127Z",

  "response": "RUNOOB(Runoob Tutorial)是一个面向编程初学者的免费中文教程网站。",

  "done": true,

  "total_duration": 10706818083,

  "load_duration": 6338219291,

  "prompt_eval_count": 26,

  "prompt_eval_duration": 130079000,

  "eval_count": 42,

  "eval_duration": 4232710000

}

Common parameters are as follows:

Parameters Description
model Required, model name
prompt Prompt; leaving it empty can be used to preload the model
stream Defaults to true for streaming; false returns the complete result at once
system Temporarily specify a system prompt, overriding the settings in the Modelfile
options Generation parameter object, such as temperature, num_ctx (same as Modelfile parameters)
format "json" or a complete JSON Schema, forcing structured output
keep_alive How long the model stays resident after the request, such as "10m", -1 for permanent, 0 for immediate unload
raw When true, skip template assembly and directly use the complete prompt you provide
suffix Text appended after the model's output, used in text completion scenarios
images Array of base64 images, used with multimodal models

Two practical tips: sending an empty prompt can preload the model into memory, eliminating the loading wait for the first request; setting keep_alive to 0 together with an empty prompt can immediately unload the model and free VRAM.

Example

Preload the model (without generating content)

curl http:

//

localhost:

11434

/

api

/

generate

-d

'{"model": "qwen3.5"}'

Immediately unload the model and free VRAM

curl http:

//

localhost:

11434

/

api

/

generate

-d

'{"model": "qwen3.5", "keep_alive": 0}'


Chat Generation: /api/chat

chat is a multi-turn conversation interface; the message history is maintained by the caller itself, which is the essential difference from generate.

Example

curl http:

//

localhost:

11434

/

api

/

chat

-d

'{
  "model": "qwen3.5",
  "messages": [
    { "role": "user", "content": "What is RUNOOB?" },
    { "role": "assistant", "content": "A Chinese tutorial website for beginners." },
    { "role": "user", "content": "Is it free? Answer in one sentence" }
  ],
  "stream": false
}'

Fields supported by the message object:

Field Description
role Four roles: system / user / assistant / tool
content Message content
images Optional, list of base64 images (multimodal models)
thinking Optional, the reasoning process of a thinking model (used with the think parameter)
tool_calls Optional, list of tools the model requests to call (see the tool calling chapter for practice)

The correct way to handle multi-turn conversations: append the assistant message returned each round back into the messages array, then send it with the new question, and the model can "remember" the full context.

messages are entirely managed by you, which means the history can be persisted to a database, summarized and compressed, or restored across sessions—the "forgetting upon exiting the command line" problem mentioned in article 5 has an engineering solution here.


Vector Embedding: /api/embed

The embed interface converts text into vectors; it is the raw material workshop for RAG and semantic search.

Example

Single text

curl http:

//

localhost:

11434

/

api

/

embed

-d

'{
  "model": "embeddinggemma",
  "input": "RUNOOB is a programming tutorial website"
}'

Batch: pass an array to input to return multiple vectors at once

curl http:

//

localhost:

11434

/

api

/

embed

-d

'{
  "model": "embeddinggemma",
  "input": ["first piece of text", "second piece of text", "third piece of text"]
}'

The embeddings in the response are a two-dimensional array; each vector has been L2-normalized (unit length) and can be directly compared using cosine similarity.

Two parameters worth noting: dimensions can specify the output vector dimension (when the model supports it, reducing dimension saves storage); truncate defaults to true and automatically truncates overly long text, while setting it to false causes an error when text is too long.


Streaming and Non-Streaming: How to Handle Responses

Generation interfaces return streaming responses by default, in NDJSON format: each line is a separate JSON object.



{"model":"qwen3.5","created_at":"...","response":"RUNOOB","done":false}

{"model":"qwen3.5","created_at":"...","response":"(Runoob Tutorial)","done":false}

{"model":"qwen3.5","created_at":"...","response":"是编程初学者的入门网站。","done":false}

{"model":"qwen3.5","created_at":"...","response":"","done":true,"done_reason":"stop"}

The client reads line by line and concatenates the response fields to get the complete answer; the concatenation process can be rendered to the interface in real time.

The trade-off between the two modes:

Mode Advantage Applicable scenarios
Streaming (default) Low time to first token, can display in real time Chat interfaces, long text generation
Non-streaming stream:false Get the complete result at once, simple to handle Batch processing, structured output, script calls

In streaming mode, errors may occur in the middle of output, when the HTTP status code can no longer be changed; the error appears as a line {"error": "..."} at the end of the data stream, and the client should check this line when parsing.


Usage Statistics and Error Handling

Each generation response ends with performance statistics fields, which are first-hand data for evaluating inference cost.

Field Meaning
total_duration Total request duration (nanoseconds)
load_duration Model loading duration (noticeable on the first request)
prompt_eval_count Number of input tokens consumed
prompt_eval_duration Input processing duration
eval_count Number of output tokens generated
eval_duration Output generation duration

The formula for generation speed (token/s) is: eval_count / eval_duration * 10^9; all time fields are in nanoseconds.

For error handling, the interface uses standard HTTP status codes to express results:

Status code Meaning
200 Success
400 Request error (missing parameters, invalid JSON, etc.)
404 Model not found (run ollama pull first or check the name)
429 Rate limited due to too frequent requests
500 Internal server error
502 Gateway error (e.g., cloud model unreachable)

The error response body always has the structure {"error": "error description"}; the client can uniformly take the error field.


Quick Overview of Model Management Interfaces

Everything the command line can do for model management has a corresponding API, suitable for building admin dashboards or automation scripts.

Endpoint Method Purpose
/api/tags GET List local models (including parameter count, quantization level)
/api/show POST View model details, capabilities, template
/api/pull POST Pull a model, streaming the download progress
/api/push POST Push a model to the model library
/api/copy POST Copy a model (source / destination)
/api/delete DELETE Delete a model
/api/create POST Create a model (including quantization, corresponding to Modelfile capabilities)
/api/ps GET View currently loaded models and VRAM usage
/api/version GET Query the Ollama version

Taking /api/tags as an example, the response contains specification details for each model:



{

  "models": [

    {

      "name": "qwen3.5:latest",

      "size": 6600000000,

      "details": {

        "family": "qwen3.5",

        "parameter_size": "9B",

        "quantization_level": "Q4_K_M"

      }

    }

  ]

}

Fields such as quantization_level and parameter_size can be directly used to build a model selector interface.


OpenAI-Compatible Interface

Switching existing OpenAI applications to local models usually only requires changing one base_url.

Example

curl http:

//

localhost:

11434

/

v1

/

chat

/

completions \

 

-H

"Content-Type: application/json"

\

 

-d

'{
    "model": "qwen3.5",
    "messages": [{ "role": "user", "content": "Introduce RUNOOB in one sentence" }]
  }'

The compatibility coverage includes five endpoints:

Endpoint Description
/v1/chat/completions Chat completions, supporting streaming, vision, tools, JSON mode
/v1/completions Text completions
/v1/responses Responses API (non-stateful mode)
/v1/embeddings Vector embeddings
/v1/models Model list

Two high-frequency differences to note:

First, the OpenAI protocol has no num_ctx concept; to change the context, first create a model with PARAMETER num_ctx and then call it by the new name (you can use the Modelfile or cp from article 7 to borrow a name).

Second, some fields are not yet supported: tool_choice, logit_bias, n, logprobs, etc.; before migrating, it is recommended to check the manual's support list.


Anthropic-Compatible Interface

Ollama also provides an Anthropic Messages API compatibility layer, so tools like Claude Code can directly use local models.

Example

curl http:

//

localhost:

11434

/

v1

/

messages \

 

-H

"Content-Type: application/json"

\

 

-H

"anthropic-version: 2023-06-01"

\

 

-d

'{
    "model": "qwen3.5",
    "max_tokens": 1024,
    "messages": [{ "role": "user", "content": "Introduce RUNOOB in one sentence" }]
  }'

When connecting tools like Claude Code, you only need to set two environment variables:

Example

export

ANTHROPIC_AUTH_TOKEN

=ollama

export

ANTHROPIC_BASE_URL

=http:

//

localhost:

11434

claude

--model

qwen3.5

Note the capability boundaries: Anthropic features such as forced tool_choice, prompt caching, batch interfaces, and PDF input are not yet supported; token counts are approximate.