Ollama Python usage
Ollama provides a Python SDK that lets us interact with locally running models in a Python environment.
Ollama's Python SDK makes it easy to integrate natural language processing tasks into Python projects, performing operations such as text generation, conversation generation, and model management without manually calling the command line.
Install the Python SDK
First, we need to install the Ollama Python SDK.
It can be installed with pip:
pip install ollama
Make sure Python 3.x is installed in your environment and that the network can access the local Ollama service.
Start the local service
Before using the Python SDK, make sure the local Ollama service has been started.
You can use the command-line tool to start it:
ollama serve
After starting the local service, the Python SDK communicates with it to perform tasks such as model inference.
Inference with Ollama's Python SDK
After installing the SDK and starting the local service, we can interact with Ollama through Python code.
First, import chat and ChatResponse from the ollama library:
from ollama import chat
from ollama import ChatResponse
With the Python SDK, you can send requests to a specified model to generate text or conversation:
Example
from
ollama
import
chat
from
ollama
import
ChatResponse
response: ChatResponse
=
chat
(
model
=
'qwen3.5'
,
messages
=
[
{
'role'
:
'user'
,
'content'
:
'Who are you?'
,
}
,
]
)
Print the response content
(
response
[
'message'
]
[
'content'
]
)
Or directly access the fields of the response object
#print(response.message.content)
The output of the code above is:
你好!我是 Qwen3.5,是通义千问系列中最新推出的大语言模型。我具备强大的语言理解与生成能力,能协助你完成多种任务!
The llama SDK also supports streaming responses; we can enable response streaming by setting stream=True when sending a request.
Example
from
ollama
import
chat
stream
=
chat
(
model
=
'qwen3.5'
,
messages
=
[
{
'role'
:
'user'
,
'content'
:
'Who are you?'
}
]
,
stream
=
True
,
)
Print the response content chunk by chunk
for
chunk
in
stream:
(
chunk
[
'message'
]
[
'content'
]
,
end
=
''
,
flush
=
True
)
Custom client
You can also create a custom client to further control request configuration, such as setting custom headers or specifying the URL of the local service.
Create a custom client
With Client, you can customize request settings (such as headers, URL, etc.) and send requests.
Example
from
ollama
import
Client
client
=
Client
(
host
=
'http://localhost:11434'
,
headers
=
{
'x-some-header'
:
'some-value'
}
)
response
=
client.
chat
(
model
=
'qwen3.5'
,
messages
=
[
{
'role'
:
'user'
,
'content'
:
'Who are you?'
,
}
,
]
)
(
response
[
'message'
]
[
'content'
]
)
Async client
If you want to execute requests asynchronously, you can use the AsyncClient class, suitable for scenarios requiring concurrency.
Example
import
asyncio
from
ollama
import
AsyncClient
async
def
chat
(
)
:
message
=
{
'role'
:
'user'
,
'content'
:
'Who are you?'
}
response
=
await AsyncClient
(
)
.
chat
(
model
=
'qwen3.5'
,
messages
=
[
message
]
)
(
response
[
'message'
]
[
'content'
]
)
asyncio.
run
(
chat
(
)
)
Asy
nc client supports the same functionality as traditional synchronous requests; the only difference is that requests are executed asynchronously, improving performance especially in high-concurrency scenarios.
Async streaming responses
If you need to handle streaming responses asynchronously, you can do so by setting stream=True as an async generator.
Example
import
asyncio
from
ollama
import
AsyncClient
async
def
chat
(
)
:
message
=
{
'role'
:
'user'
,
'content'
:
'Who are you?'
}
async
for
part
in
await AsyncClient
(
)
.
chat
(
model
=
'qwen3.5'
,
messages
=
[
message
]
,
stream
=
True
)
:
(
part
[
'message'
]
[
'content'
]
,
end
=
''
,
flush
=
True
)
asyncio.
run
(
chat
(
)
)
Here, the response will be returned asynchronously part by part, and each part can be processed immediately.
Common API methods
The Ollama Python SDK provides several common API methods for operating and managing models.
1. chat method
Generate a conversation with the model, send user messages and get model responses:
ollama.chat(model='llama3.2', messages=[{'role': 'user', 'content': 'Why is the sky blue?'}])
2. generate method
Used for text generation tasks. Similar to the chat method, but it only needs a prompt parameter:
ollama.generate(model='llama3.2', prompt='Why is the sky blue?')
3. list method
List all available models:
ollama.list()
4. show method
Show detailed information about a specified model:
ollama.show('llama3.2')
5. create method
Create a new model from an existing one:
ollama.create(model='example', from_='llama3.2', system="You are Mario from Super Mario Bros.")
6. copy method
Copy a model to another location:
ollama.copy('llama3.2', 'user/llama3.2')
7. delete method
Delete a specified model:
ollama.delete('llama3.2')
8. pull method
Pull a model from a remote repository:
ollama.pull('llama3.2')
9. push method
Push a local model to a remote repository:
ollama.push('user/llama3.2')
10. embed method
Generate text embeddings:
ollama.embed(model='llama3.2', input='The sky is blue because of rayleigh scattering')
11. ps method
View the list of currently running models:
ollama.ps()
Error handling
The Ollama SDK throws errors when a request fails or when there's a problem with response streaming.
We can use try-except statements to catch these errors and handle them as needed.
Example
model
=
'does-not-yet-exist'
try
:
response
=
ollama.
chat
(
model
)
except
ollama.
ResponseError
as
e:
(
'Error:'
,
e.
error
)
if
e.
status_code
==
404
:
ollama.
pull
(
model
)
In the above example, if the model does-not-yet-exist doesn't exist, a ResponseError is thrown; after catching it you can choose to pull that model or handle it another way.