Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ curl https://ollama.com/api/tags
import os
from ollama import Client

client = Client(host='https://ollama.com', headers={'Authorization': 'Bearer ' + os.environ.get('OLLAMA_API_KEY')})
client = Client(host='https://ollama.com', headers={'Authorization': 'Bearer ' + os.environ['OLLAMA_API_KEY']})

messages = [
{
Expand Down Expand Up @@ -239,14 +239,16 @@ ollama.push('user/gemma4')

### Embed

Pull an embedding model first: `ollama pull embeddinggemma`.

```python
ollama.embed(model='gemma4', input='The sky is blue because of rayleigh scattering')
ollama.embed(model='embeddinggemma', input='The sky is blue because of rayleigh scattering')
```

### Embed (batch)

```python
ollama.embed(model='gemma4', input=['The sky is blue because of rayleigh scattering', 'Grass is green because of chlorophyll'])
ollama.embed(model='embeddinggemma', input=['The sky is blue because of rayleigh scattering', 'Grass is green because of chlorophyll'])
```

### Ps
Expand Down Expand Up @@ -280,6 +282,9 @@ v0.35.0 or later) or `clef` (v0.35.1 or later), and in the cloud with `clef:clou
on a paid plan (through Ollama v0.40.5 or later, or [directly against
ollama.com](#cloud-api-ollamacom)).

System One image inputs below require the current `main` checkout; they are not
in the 0.6.3 release.

Clef also reads images (v0.40.0 or later locally): pass `images` as file paths,
bytes, or base64 strings, shared by all questions. Cloud requests accept up to 4
PNG, JPEG, or WebP images (each at most 4 MiB and 16 megapixels, 8 MiB total).
Expand Down
47 changes: 39 additions & 8 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,47 @@
# Running Examples

Run the examples in this directory with:
Run commands from the repository root. Use Python 3.11 or later for the full example set, install [Ollama](https://ollama.com/download), and start its server.

To run against this checkout:

```sh
# Run example
python3 examples/<example>.py
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -e . rich tqdm 'mcp>=2,<3'
python examples/chat.py
```

Or use uv (including for scripts with inline dependencies):

# or with uv
uv run examples/<example>.py
```sh
uv run --with-editable . examples/chat.py
uv run --with-editable . examples/web-search-mcp.py
```

See [ollama/docs/api.md](https://github.com/ollama/ollama/blob/main/docs/api.md) for full API documentation
`--with-editable .` keeps scripts with inline dependencies on the SDK in this checkout. To use a released package instead, install `ollama>=0.6.3` and run the scripts with that environment. System One is available in 0.6.3; System One image inputs are currently on `main` and require this checkout. Python 0.6.3 also accepts model-defined thinking levels; the examples use the GPT-OSS levels `low`, `medium`, and `high`.

Pull the model named in the example before running it, for example `ollama pull gemma4`. Use `ollama list` to see installed models and `ollama show <model>` to check capabilities. Models may require several GB of memory and disk space; pulling is a separate step except in `pull.py`. See the [model library](https://ollama.com/search) for available tags.

| Examples | Model / additional requirements |
| --- | --- |
| Basic chat/generate, logprobs, show, create | `gemma4` |
| Tools, structured text output | `gemma4` |
| Multi-tool, web search | `qwen3` (thinking and tools) |
| GPT-OSS tools, thinking levels | `gpt-oss:20b` |
| GPT-OSS web search | `gpt-oss:120b-cloud`, `ollama signin`, and a web-search API key |
| Thinking chat/generate | `deepseek-r1` |
| Fill in the middle | `codellama:7b-code` |
| Multimodal chat, structured image output | `gemma4` and an image path |
| Multimodal generate | `gemma4`; fetches an XKCD comic over the internet |
| Embeddings | `embeddinggemma`; Ollama v0.11.10 or later |
| Image generation | `x/z-image-turbo`; supported macOS installation; writes `output.png` |
| System One | `nimble`; Ollama v0.35.0 or later |

The `ps.py` and `list.py` examples only inspect models. `create.py` writes a model named `my-assistant`; choose an unused name before running it. `pull.py` downloads `gemma4`. Image generation overwrites `output.png` in the working directory.

Most examples call the local server at `http://localhost:11434`. Set `OLLAMA_HOST` to use another server. A connection error means the server is not reachable; a model-not-found error means you need to pull that exact tag on that server. Structured outputs require a local model; Ollama's cloud does not currently support the `format` schema.

For direct cloud inference, set `OLLAMA_API_KEY` and use `Client(host='https://ollama.com')` with the direct model name, such as `gpt-oss:120b`. Through a signed-in local server, use the `-cloud` tag instead. Web search/fetch always call `https://ollama.com` and require an API key, even when inference is local. Python reads `OLLAMA_API_KEY` automatically. See [cloud authentication](https://docs.ollama.com/cloud/api) and the [API documentation](https://docs.ollama.com/api/introduction).

### Chat - Chat with a model

Expand Down Expand Up @@ -104,11 +135,11 @@ Configuration to use with an MCP client:

### Ollama Pull - Pull a model from Ollama

Requirement: `pip install tqdm`
Requires `tqdm` (installed above).

- [pull.py](pull.py)

### Ollama Create - Create a model from a Modelfile
### Ollama Create - Create a model from an existing model

- [create.py](create.py)

Expand Down
6 changes: 3 additions & 3 deletions examples/async-chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ async def main():
},
]

client = AsyncClient()
response = await client.chat('gemma4', messages=messages)
print(response['message']['content'])
async with AsyncClient() as client:
response = await client.chat('gemma4', messages=messages)
print(response['message']['content'])


if __name__ == '__main__':
Expand Down
6 changes: 3 additions & 3 deletions examples/async-generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@


async def main():
client = ollama.AsyncClient()
response = await client.generate('gemma4', 'Why is the sky blue?')
print(response['response'])
async with ollama.AsyncClient() as client:
response = await client.generate('gemma4', 'Why is the sky blue?')
print(response['response'])


if __name__ == '__main__':
Expand Down
22 changes: 11 additions & 11 deletions examples/async-structured-outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ class FriendList(BaseModel):


async def main():
client = AsyncClient()
response = await client.chat(
model='llama3.1:8b',
messages=[{'role': 'user', 'content': 'I have two friends. The first is Ollama 22 years old busy saving the world, and the second is Alonso 23 years old and wants to hang out. Return a list of friends in JSON format'}],
format=FriendList.model_json_schema(), # Use Pydantic to generate the schema
options={'temperature': 0}, # Make responses more deterministic
)

# Use Pydantic to validate the response
friends_response = FriendList.model_validate_json(response.message.content)
print(friends_response)
async with AsyncClient() as client:
response = await client.chat(
model='gemma4',
messages=[{'role': 'user', 'content': 'I have two friends. The first is Ollama 22 years old busy saving the world, and the second is Alonso 23 years old and wants to hang out. Return a list of friends in JSON format'}],
format=FriendList.model_json_schema(), # Use Pydantic to generate the schema
options={'temperature': 0}, # Make responses more deterministic
)

# Use Pydantic to validate the response
friends_response = FriendList.model_validate_json(response.message.content)
print(friends_response)


if __name__ == '__main__':
Expand Down
69 changes: 34 additions & 35 deletions examples/async-tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ def add_two_numbers(a: int, b: int) -> int:
Returns:
int: The sum of the two numbers
"""
return a + b
return int(a) + int(b)


def subtract_two_numbers(a: int, b: int) -> int:
"""
Subtract two numbers
"""
return a - b
return int(a) - int(b)


# Tools can still be manually defined and passed into chat
Expand Down Expand Up @@ -52,39 +52,38 @@ def subtract_two_numbers(a: int, b: int) -> int:


async def main():
client = ollama.AsyncClient()

response: ChatResponse = await client.chat(
'llama3.1',
messages=messages,
tools=[add_two_numbers, subtract_two_numbers_tool],
)

if response.message.tool_calls:
# There may be multiple tool calls in the response
# Add the assistant message with tool calls to the conversation
messages.append(response.message)

for tool in response.message.tool_calls:
# Ensure the function is available, and then call it
if function_to_call := available_functions.get(tool.function.name):
print('Calling function:', tool.function.name)
print('Arguments:', tool.function.arguments)
output = function_to_call(**tool.function.arguments)
print('Function output:', output)
else:
print('Function', tool.function.name, 'not found')
output = 'Function not found'

# Add each tool result as a separate message
messages.append({'role': 'tool', 'content': str(output), 'tool_name': tool.function.name})

# Get final response from model with all tool call results
final_response = await client.chat('llama3.1', messages=messages)
print('Final response:', final_response.message.content)

else:
print('No tool calls returned from model')
async with ollama.AsyncClient() as client:
response: ChatResponse = await client.chat(
'gemma4',
messages=messages,
tools=[add_two_numbers, subtract_two_numbers_tool],
)

if response.message.tool_calls:
# There may be multiple tool calls in the response
# Add the assistant message with tool calls to the conversation
messages.append(response.message)

for tool in response.message.tool_calls:
# Ensure the function is available, and then call it
if function_to_call := available_functions.get(tool.function.name):
print('Calling function:', tool.function.name)
print('Arguments:', tool.function.arguments)
output = function_to_call(**tool.function.arguments)
print('Function output:', output)
else:
print('Function', tool.function.name, 'not found')
output = 'Function not found'

# Add each tool result as a separate message
messages.append({'role': 'tool', 'content': str(output), 'tool_name': tool.function.name})

# Get final response from model with all tool call results
final_response = await client.chat('gemma4', messages=messages)
print('Final response:', final_response.message.content)

else:
print('No tool calls returned from model')


if __name__ == '__main__':
Expand Down
8 changes: 3 additions & 5 deletions examples/chat-logprobs.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
from typing import Iterable

import ollama


def print_logprobs(logprobs: Iterable[dict], label: str) -> None:
def print_logprobs(logprobs, label: str) -> None:
print(f'\n{label}:')
for entry in logprobs:
token = entry.get('token', '')
logprob = entry.get('logprob')
print(f' token={token!r:<12} logprob={logprob:.3f}')
for alt in entry.get('top_logprobs', []):
for alt in entry.top_logprobs or []:
if alt['token'] != token:
print(f' alt -> {alt["token"]!r:<12} ({alt["logprob"]:.3f})')

Expand All @@ -28,4 +26,4 @@ def print_logprobs(logprobs: Iterable[dict], label: str) -> None:
top_logprobs=3,
)
print('Chat response:', response['message']['content'])
print_logprobs(response.get('logprobs', []), 'chat logprobs')
print_logprobs(response.logprobs or [], 'chat logprobs')
8 changes: 6 additions & 2 deletions examples/chat-with-history.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@
]

while True:
user_input = input('Chat with history: ')
try:
user_input = input('Chat with history (Ctrl-D to quit): ')
except (EOFError, KeyboardInterrupt):
print()
break
response = chat(
'gemma4',
messages=[*messages, {'role': 'user', 'content': user_input}],
Expand All @@ -30,6 +34,6 @@
# Add the response to the messages to maintain the history
messages += [
{'role': 'user', 'content': user_input},
{'role': 'assistant', 'content': response.message.content},
response.message,
]
print(response.message.content + '\n')
2 changes: 1 addition & 1 deletion examples/embed.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ollama import embed

response = embed(model='llama3.2', input='Hello, world!')
response = embed(model='embeddinggemma', input='Hello, world!')
print(response['embeddings'])
8 changes: 3 additions & 5 deletions examples/generate-logprobs.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
from typing import Iterable

import ollama


def print_logprobs(logprobs: Iterable[dict], label: str) -> None:
def print_logprobs(logprobs, label: str) -> None:
print(f'\n{label}:')
for entry in logprobs:
token = entry.get('token', '')
logprob = entry.get('logprob')
print(f' token={token!r:<12} logprob={logprob:.3f}')
for alt in entry.get('top_logprobs', []):
for alt in entry.top_logprobs or []:
if alt['token'] != token:
print(f' alt -> {alt["token"]!r:<12} ({alt["logprob"]:.3f})')

Expand All @@ -21,4 +19,4 @@ def print_logprobs(logprobs: Iterable[dict], label: str) -> None:
top_logprobs=3,
)
print('Generate response:', response['response'])
print_logprobs(response.get('logprobs', []), 'generate logprobs')
print_logprobs(response.logprobs or [], 'generate logprobs')
15 changes: 3 additions & 12 deletions examples/gpt-oss-tools-stream.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# /// script
# requires-python = ">=3.11"
# dependencies = [
# "gpt-oss",
# "ollama",
# "rich",
# ]
Expand All @@ -11,8 +10,7 @@

from rich import print

from ollama import Client
from ollama._types import ChatResponse
from ollama import ChatResponse, Client


def get_weather(city: str) -> str:
Expand Down Expand Up @@ -50,15 +48,11 @@ def get_weather_conditions(city: str) -> str:

messages = [{'role': 'user', 'content': 'What is the weather like in London? What are the conditions in Toronto?'}]

client = Client(
# Ollama Turbo
# host="https://ollama.com", headers={'Authorization': (os.getenv('OLLAMA_API_KEY'))}
)
client = Client()

model = 'gpt-oss:20b'
# gpt-oss can call tools while "thinking"
# a loop is needed to call the tools and get the results
final = True
while True:
response_stream: Iterator[ChatResponse] = client.chat(model=model, messages=messages, tools=[get_weather, get_weather_conditions], stream=True)
tool_calls = []
Expand All @@ -70,10 +64,7 @@ def get_weather_conditions(city: str) -> str:
tool_calls.extend(chunk.message.tool_calls)

if chunk.message.content:
if not (chunk.message.thinking or chunk.message.thinking == '') and final:
print('\n\n' + '=' * 10)
print('Final result: ')
final = False
content += chunk.message.content
print(chunk.message.content, end='', flush=True)

if chunk.message.thinking:
Expand Down
Loading
Loading