Ollama programming language calls
This article systematically reviews four code routes for calling Ollama: the official Python library, the official JavaScript library, native HTTP, and OpenAI / Anthropic compatible SDKs, and ties them together with two practical projects.
Official SDKs: Python and JavaScript
The official side provides two first-party maintained libraries with consistent interface design—knowing one means knowing both.
Installation
Python
pip
install
ollama
JavaScript / TypeScript
npm
install
ollama
Comparison of the core methods of the two libraries:
| Method | Purpose | Key parameters |
|---|---|---|
| chat | Multi-turn conversation (main method) | model、messages、stream、tools、think、format、options |
| generate | Single-turn text generation | model、prompt、stream、suffix |
| embed | Vector embeddings | model, input (single item or array) |
| list | List local models | None |
| pull | Pull model (progress can be monitored) | model、stream |
A chat call with all parameters in Python, covering most of the capabilities learned in the previous articles:
Example
from
ollama
import
chat
from
pydantic
import
BaseModel
Define the schema for structured output
class
Answer
(
BaseModel
)
:
site
:
str
free:
bool
response
=
chat
(
model
=
'qwen3.5'
,
messages
=
[
{
'role'
:
'user'
,
'content'
:
'Introduce RUNOOB Runoob Tutorial'
}
]
,
stream
=
False
,
Streaming switch
think
=
False
,
Thinking mode switch
format
=
Answer.
model_json_schema
(
)
,
Structured output schema
options
=
{
'temperature'
:
0.3
,
'num_ctx'
:
8192
}
,
Generation parameters
)
(
Answer.
model_validate_json
(
response.
message
.
content
)
)
The equivalent in JavaScript:
Example
import
ollama from
'ollama'
// Streaming conversation example
const
stream
=
await ollama.
chat
(
{
model
:
'qwen3.5'
,
messages
:
[
{
role
:
'user'
,
content
:
'Introduce RUNOOB in three sentences'
}
]
,
stream
:
true
,
}
)
// Output chunk by chunk
let content
=
''
for
await
(
const
chunk of stream
)
{
process.
stdout
.
write
(
chunk.
message
.
content
)
content
+=
chunk.
message
.
content
}
When connecting to a non-default address (such as a remote server or Ollama Cloud), specify it with host and headers:
Example
import
os
from
ollama
import
Client
Connect to remote Ollama or Ollama Cloud (Bearer authentication)
client
=
Client
(
host
=
'https://ollama.com'
,
headers
=
{
'Authorization'
:
'Bearer '
os
.
environ
.
get
(
'OLLAMA_API_KEY'
)
}
,
)
response
=
client.
chat
(
model
=
'qwen3.5'
,
messages
=
[
{
'role'
:
'user'
,
'content'
:
'Introduce RUNOOB in one sentence'
}
]
)
Native HTTP: curl quick reference
When writing scripts, debugging APIs, and troubleshooting, curl is the fastest tool.
| Scenario | Command |
|---|---|
| Single-turn generation (non-streaming) | curl http://localhost:11434/api/generate -d '{"model":"qwen3.5","prompt":"Hello","stream":false}' |
| Dialogue | curl http://localhost:11434/api/chat -d '{"model":"qwen3.5","messages":[...],"stream":false}' |
| Vector embeddings | curl http://localhost:11434/api/embed -d '{"model":"embeddinggemma","input":"text"}' |
| List models | curl http://localhost:11434/api/tags |
| Model details | curl http://localhost:11434/api/show -d '{"model":"qwen3.5"}' |
| Pull a model | curl http://localhost:11434/api/pull -d '{"model":"qwen3.5:4b"}' |
| Delete a model | curl -X DELETE http://localhost:11434/api/delete -d '{"model":"qwen3.5:4b"}' |
Reusing OpenAI / Anthropic SDK
When migrating an existing project, a compatibility layer is far less work than rewriting.
Using the OpenAI SDK in a JavaScript project to connect to a local model:
Example
import
OpenAI from
"openai"
// Only change base_url; api_key can be anything
const
openai
=
new
OpenAI
(
{
baseURL
:
"http://localhost:11434/v1"
,
apiKey
:
"ollama"
,
}
)
const
res
=
await openai.
chat
.
completions
.
create
(
{
model
:
"qwen3.5"
,
messages
:
[
{
role
:
"user"
,
content
:
"Introduce RUNOOB in one sentence"
}
]
,
}
)
console.
log
(
res.
choices
[
0
]
.
message
.
content
)
The same goes for using the Anthropic SDK in a Python project:
Example
import
anthropic
base_url points to local; key can be anything
client
=
anthropic.
Anthropic
(
base_url
=
'http://localhost:11434'
,
api_key
=
'ollama'
,
)
message
=
client.
messages
.
create
(
model
=
'qwen3.5'
,
max_tokens
=
1024
,
messages
=
[
{
'role'
:
'user'
,
'content'
:
'Introduce RUNOOB in one sentence'
}
]
,
)
(
message.
content
[
0
]
.
text
)
Selection advice: new projects use the official SDK directly (most complete capabilities); existing projects use a compatibility layer with their current SDK (minimal changes); when integrating with a framework that only understands the OpenAI protocol, the compatibility layer is the only path.
Practical one: command-line chat script
With fewer than 40 lines of Python, assemble the chat, streaming, and history management learned earlier into a usable terminal chat tool.
Example
File path: cli_chat.py
Run: python cli_chat.py
from
ollama
import
chat
MODEL
=
'qwen3.5:4b'
Conversation history: system defines the role, subsequent dialogue is appended
messages
=
[
{
'role'
:
'system'
,
'content'
:
'You are RUNOOB's programming assistant; answer concisely and provide example code.'
,
}
]
(
f
'Starting conversation (model {MODEL}); type exit to quit.'
)
while
True
:
user_input
=
input
(
'\nYou: '
)
.
strip
(
)
if
user_input.
lower
(
)
==
'exit'
:
break
if
not
user_input:
continue
Append the user message and initiate a streaming request
messages.
append
(
{
'role'
:
'user'
,
'content'
: user_input
}
)
stream
=
chat
(
model
=
MODEL
,
messages
=
messages
,
stream
=
True
)
Print chunk by chunk while accumulating the full answer
(
'Assistant: '
,
end
=
''
,
flush
=
True
)
reply
=
''
for
chunk
in
stream:
reply +
=
chunk
.
message
.
content
(
chunk
.
message
.
content
,
end
=
''
,
flush
=
True
)
Key: append this turn's answer back to the history so the model can "remember" the context
messages.
append
(
{
'role'
:
'assistant'
,
'content'
: reply
}
)
$ python cli_chat.py
开始对话(模型 qwen3.5:4b),输入 exit 退出。
你:什么是 Python 的切片?
助手:切片是用 [start:stop:step] 从序列中取子序列的语法,
例如 s[1:3] 取索引 1 到 2 的元素。
你:给个 RUNOOB 风格的例子
助手:s = "RUNOOB"
print(s[1:4]) # 输出 UNO
你:exit
There's only one core point: each turn, append both the user message and the assistant's full answer into messages. The model itself is stateless; "memory" comes entirely from this list.
Practical two: a multi-turn conversation web app with memory
To bring the same idea to the browser, a backend is needed to coordinate: manage conversation history, call Ollama, and forward streaming results to the frontend.
Backend: Flask wraps the Ollama streaming API
Example
File path: server.py
Install dependencies: pip install flask ollama
from
flask
import
Flask
,
request
,
Response
,
stream_with_context
from
ollama
import
chat
app
=
Flask
(
name
)
Conversation history temporarily stored in memory: real projects should use a database
sessions
=
{
}
@
app.
route
(
'/chat'
)
def
do_chat
(
)
:
session_id
=
request.
args
.
get
(
'session'
,
'default'
)
user_input
=
request.
args
.
get
(
'q'
,
''
)
if
not
user_input:
return
{
'error'
:
'Missing q parameter'
}
Retrieve (or initialize) the history for this session
history
=
sessions.
setdefault
(
session_id
,
[
{
'role'
:
'system'
,
'content'
:
'You are RUNOOB's programming assistant.'
}
]
)
history.
append
(
{
'role'
:
'user'
,
'content'
: user_input
}
)
Stream generation, forwarded to the frontend line by line in NDJSON format
def
generate
(
)
:
reply
=
''
stream
=
chat
(
model
=
'qwen3.5:4b'
,
messages
=
history
,
stream
=
True
)
for
chunk
in
stream:
reply +
=
chunk
.
message
.
content
yield
chunk
.
message
.
content
'\n'
Key: write the full answer back to the history to form memory
history.
append
(
{
'role'
:
'assistant'
,
'content'
: reply
}
)
return
Response
(
stream_with_context
(
generate
(
)
)
,
mimetype
=
'application/x-ndjson'
,
)
if
name
==
'main'
:
app.
run
(
port
=
5000
)
Frontend: fetch streaming read
Example
// Browser side: read NDJSON line by line and render in real time
async
function
ask
(
question
)
{
const
resp
=
await fetch
(
`
/
chat
?
session
=
demo
&
q
=
$
{
encodeURIComponent
(
question
)
}
`
)
const
reader
=
resp.
body
.
getReader
(
)
const
decoder
=
new
TextDecoder
(
)
while
(
true
)
{
const
{
done
,
value
}
=
await reader.
read
(
)
if
(
done
)
break
// Append each chunk to the page as it arrives for a typewriter effect
document.
getElementById
(
'answer'
)
.
textContent
+=
decoder.
decode
(
value
)
}
}
Run and verify
Example
Start the backend
python server.py
Simulate two consecutive requests to verify memory
curl
"http://localhost:5000/chat?session=demo&q=what is Python slicing"
curl
"http://localhost:5000/chat?session=demo&q=another RUNOOB-style example"
In the second request the model can continue answering along the "slicing" topic, showing that the server-side managed conversation history works; changing the session parameter creates a brand-new session that doesn't interfere.
This dozens-of-lines skeleton already covers the three key elements of a ChatGPT-like app: session isolation (session parameter), streaming experience (NDJSON forwarding), and memory persistence (history write-back). Add database storage and a multi-session list and you have the prototype of a full practical project; the web app practical chapter will continue expanding it.