Skip to main content

Genkit Ollama Plugin

This Genkit plugin connects Python apps to locally running Ollama models for chat, streaming, tool calling, multimodal prompts, and embeddings.

Building with a coding agent? Install the Genkit Python skill first.

npx skills add genkit-ai/skills --skill developing-genkit-python

It teaches your agent the current Genkit Python APIs and common gotchas. Source, manual install and skills for other languages: genkit-ai/skills.

Installation

uv add genkit genkit-ollama

Install Ollama from ollama.com/download, then start the local server:

ollama serve

Ollama serves http://127.0.0.1:11434 by default. Pull the models your app will use before running Genkit:

ollama pull llama3.2
ollama pull llava
ollama pull nomic-embed-text

Usage

from genkit import Genkit
from genkit_ollama import Ollama

ai = Genkit(
    plugins=[Ollama()],
    model='ollama/llama3.2',
)

response = await ai.generate(prompt='Write a haiku about local models.')
print(response.text)

embeddings = await ai.embed(embedder='ollama/nomic-embed-text', content='local inference')
print(len(embeddings[0].embedding))

These snippets assume an async context (await inside an async def); pasting them at module top level raises SyntaxError: 'await' outside function. See the runnable sample for a complete async def main() plus ai.run_main(...) entry point.

Streaming

stream_response = ai.generate_stream(prompt='Stream a haiku about Ollama.')
async for chunk in stream_response.stream:
    print(chunk.text, end='', flush=True)
final = await stream_response.response

Tool calling

from pydantic import BaseModel, Field


class WeatherInput(BaseModel):
    city: str = Field(description='City to look up')


@ai.tool()
async def current_weather(input: WeatherInput) -> str:
    return f'{input.city} is 18°C and partly cloudy.'


response = await ai.generate(
    prompt='What is the weather in London?',
    tools=['current_weather'],
)
print(response.text)

Ollama tool inputs are object schemas, so wrap primitive inputs in a Pydantic model as above. When a tool's schema declares properties but omits an explicit type, the plugin infers an object schema rather than dropping the tool.

JSON / schema-constrained output

from pydantic import BaseModel


class Haiku(BaseModel):
    line_one: str
    line_two: str
    line_three: str


response = await ai.generate(
    prompt='Write a haiku about local models.',
    output_schema=Haiku,
)
print(response.output)

Ollama-specific config (OllamaConfig)

OllamaConfig extends the common Genkit ModelConfig with think, keep_alive, and every sampler option the installed ollama client knows (num_ctx, min_p, seed, repeat_penalty, mirostat, ...). Unknown keys raise INVALID_ARGUMENT, so a misspelled num_ctx fails instead of running with the default context window.

from genkit_ollama import OllamaConfig

# Reasoning model with a 32k context window kept warm for an hour
response = await ai.generate(
    model='ollama/deepseek-r1',
    prompt='Plan a small REST API.',
    config=OllamaConfig(
        think=True,
        num_ctx=32_000,
        keep_alive='1h',
        temperature=0.2,
    ),
)

A sampler option this class doesn't declare yet goes in extra. It is merged into the request's options as written and wins over a declared field with the same name:

config={'temperature': 0.2, 'extra': {'new_sampler_option': 0.5}}
# => options={'temperature': 0.2, 'new_sampler_option': 0.5}

Set the reply cap and stop strings with the common fields. The plugin sends max_output_tokens as Ollama's num_predict and stop_sequences as stop. Passing num_predict or stop at the top level raises as an unknown config key; extra passes raw options through as written:

config={'max_output_tokens': 256, 'stop_sequences': ['###']}
# => options={'num_predict': 256, 'stop': ['###']}

config={'num_predict': 256}
# => GenkitError INVALID_ARGUMENT: ollama/llama3.2: unknown config key 'num_predict'; ...

Remote server, headers, and timeouts

Ollama() reads OLLAMA_HOST, then falls back to http://127.0.0.1:11434. base_url is the server root, with no /v1 or /api suffix; the plugin calls {base_url}/api/chat.

Ollama(base_url='http://ollama.example.com:11434')

# Static headers
Ollama(request_headers={'Authorization': 'Bearer <token>'})

# Headers computed per request: Ollama on Cloud Run behind IAM needs a fresh ID token
import asyncio

import google.auth.transport.requests
from google.oauth2 import id_token

OLLAMA_URL = 'https://ollama-gpu-abc123-uc.a.run.app'
creds = id_token.fetch_id_token_credentials(OLLAMA_URL)


async def cloud_run_auth() -> dict[str, str]:
    # Refresh only when the cached token has expired, off the event loop.
    if not creds.valid:
        await asyncio.to_thread(creds.refresh, google.auth.transport.requests.Request())
    return {'Authorization': f'Bearer {creds.token}'}


Ollama(base_url=OLLAMA_URL, request_headers=cloud_run_auth, timeout=60.0)

A dict is sent as-is. A callable takes no arguments, may be sync or async, and runs before every HTTP request on the plugin's shared connection pool, so it should cache its token and only refresh when it expires.

Per-request API key (hosted Ollama)

A multi-tenant app can bill each call to the caller's own key. Pass it on the call's context, not the config, so it never lands in a trace:

# 1. Plugin runs on OLLAMA_API_KEY (or no key) by default
ai = Genkit(plugins=[Ollama(base_url='https://ollama.com')])

# 2. This call authenticates as the tenant
response = await ai.generate(
    model='ollama/gpt-oss:120b',
    prompt='Summarize the order history.',
    context={'secrets': {'api_key': tenant_key}},
)
# => sent with Authorization: Bearer <tenant_key>
  • Slot: context.secrets.api_key (apiKey works too). It applies to that call only; concurrent tenants each send their own key.
  • No key in secrets: secrets without api_key, or keys elsewhere in the context (an auth provider's context['api_key'], another provider's key), are ignored and the call runs on the plugin's headers.
  • Bad key: a key that is blank, not a string, or contains whitespace fails the call with INVALID_ARGUMENT.
  • Config: config={'api_key': ...} or config.extra.api_key raises INVALID_ARGUMENT before anything is sent.
  • Proxy auth: if request_headers sets Authorization (a dict, or a callable that returns one), a per-request key fails with FAILED_PRECONDITION rather than replacing the proxy's token.
  • Embedders: embed() takes no context, so embedders always run on the plugin's headers.

Model capabilities

There is nothing to configure. The Dev UI lists the models the server has pulled (/api/tags), and any ollama/<name> resolves on first use. Every model goes through /api/chat. The plugin asks /api/show once per model: vision turns on media input and tools turns on tool calling. If the probe fails (server down, model not pulled, an Ollama too old to report capabilities), the model advertises both, as JS and Go do. Names containing embed are listed as embedders.

Troubleshooting

If the plugin can't reach the server it raises a GenkitError with status UNAVAILABLE and the URL it tried (DEADLINE_EXCEEDED if the request timed out). Start the daemon (ollama serve) or set base_url to a reachable host.

Sample

See py/samples/ollama-sample for a runnable sample covering chat, streaming, tool calling, and embeddings with a local Ollama server.

Notes

Ollama is open-source software under the MIT License. Individual models pulled through Ollama have their own licenses; review model cards before production use. Models run locally on your hardware by default — no data leaves the machine unless you point the plugin at a remote Ollama server.

Acknowledgements

Thanks to the community contributors who built and maintained the original community version of this plugin.

License

Apache-2.0

Metadata

Release files for genkit-ollama 0.13.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for genkit-ollama 0.13.0
File Size Uploaded Provenance Actions
genkit_ollama-0.13.0.tar.gz 56.0 kB With provenance Details for genkit_ollama-0.13.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for genkit-ollama 0.13.0
File Interpreter ABI Platform Actions
genkit_ollama-0.13.0-py3-none-any.whl Python 3 none any Details for genkit_ollama-0.13.0-py3-none-any.whl

Total release size: 90.7 kB

Release files / genkit_ollama-0.13.0.tar.gz

Download URL genkit_ollama-0.13.0.tar.gz
Size 56.0 kB
Tags Source
SHA-256 checksum
How to use checksums
a47912a73b15d810141f4576359de5960ced6f12d6a7fd73c62474b2fd3a4432
BLAKE2b-256 checksum
How to use checksums
7a436b21d42a8eafb2955a4fe79f576b8d1a2da93a3931412a8b33ff878f555f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Release files / genkit_ollama-0.13.0-py3-none-any.whl

Download URL genkit_ollama-0.13.0-py3-none-any.whl
Size 34.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4e9a213df8a31725fc813d79c2c520a08a74be62a5bb291c01659e351a1252a3
BLAKE2b-256 checksum
How to use checksums
4fa2117626cfbbc7c866439ab10b31ea28e3546f58df64dd406395228111e8be
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

Security for genkit-ollama 0.13.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for genkit_ollama-0.13.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page