Skip to main content
Change of provenance

The repository or configuration that created this release differ from a previous release. View details.

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',
)


async def main() -> None:
    # 1. Generate on the local server
    response = await ai.generate(prompt='Write a haiku about local models.')
    print(response.text)
    # => Weights on my own disk
    #    no packet leaves the building
    #    the fan hums along

    # 2. Embed with a pulled embedding model
    embeddings = await ai.embed(embedder='ollama/nomic-embed-text', content='local inference')
    print(len(embeddings[0].embedding))
    # => 768


if __name__ == '__main__':
    ai.run_main(main())

Streaming

async def main() -> None:
    # 1. Print chunks as they arrive
    stream_response = ai.generate_stream(prompt='Stream a haiku about Ollama.')
    async for chunk in stream_response.stream:
        print(chunk.text, end='', flush=True)
    print()
    # => Weights on my own disk ...

    # 2. The final response arrives after the last chunk
    final = await stream_response.response
    print(final.finish_reason)
    # => stop

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)
# => It's 18°C and partly cloudy in London.

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,
)
if response.output:
    print(response.output.line_one)
    # => Weights on my own disk

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: the Ollama embedder ignores context.secrets and always runs 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, the failure has status UNAVAILABLE and the URL it tried (DEADLINE_EXCEEDED if the request timed out). ai.generate returns it on res.error; ai.embed raises it as a GenkitError. Start the daemon (ollama serve) or set base_url to a reachable host.

Sample

See 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.14.0

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

Change of provenance

The repository or configuration that created these release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Source distribution (sdist)

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

Built distribution (wheel)

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

Total release size: 91.0 kB

Release files / genkit_ollama-0.14.0.tar.gz

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL genkit_ollama-0.14.0.tar.gz
Size 56.1 kB
Tags Source
SHA-256 checksum
How to use checksums
03cf4798b48c51aa5d0c8f77baf33cca3db467823a61c1be22c678ec51876b8d
BLAKE2b-256 checksum
How to use checksums
2c74dd3439e328fc986da78371ed839e34d4ea394a2428afa013fa46ddaf4aa7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 19, 2026.

Transparency log

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

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL genkit_ollama-0.14.0-py3-none-any.whl
Size 34.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d3bc03cdb9a005d8806ed8ec64dce39949043d38c8a56a9c088a8695ef59c169
BLAKE2b-256 checksum
How to use checksums
14ae440599709c78f81ef0cfcc071b6658cba9e6ce5de56eb338caf147423f9c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 19, 2026.

Transparency log

Security for genkit-ollama 0.14.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.

Change of provenance

The repository and configuration that created this release differ from a previous release.

While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.

Select from 2 files

Attestation for genkit_ollama-0.14.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 19, 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