Skip to main content
Change of provenance

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

Genkit FastAPI Plugin

Expose Genkit flows and agents as HTTP endpoints in a FastAPI application.

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-fastapi genkit-google-genai uvicorn

uvicorn runs the examples below. Any ASGI server works; the adapter doesn't depend on one.

Usage

Serving Flows (serve_flow)

Use serve_flow to register a Genkit flow as a FastAPI endpoint:

from fastapi import FastAPI
from genkit import Genkit
from genkit_fastapi import serve_flow
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
app = FastAPI()


@ai.tool(description='Get current weather for a location')
async def get_weather(location: str) -> str:
    return f'Sunny in {location}'


@ai.flow
async def chat_flow(prompt: str) -> str:
    response = await ai.generate(
        prompt=prompt,
        tools=[get_weather],
    )
    return response.text


# Mount flow endpoint at POST /api/chat_flow
app.include_router(serve_flow(chat_flow), prefix='/api')

Serving Agents (serve_agent)

Use serve_agent to expose an agent as FastAPI routes (including /getSnapshot and /abort endpoints when session state storage is enabled). Agents are experimental, so serve_agent comes from genkit_fastapi.exp:

from fastapi import FastAPI
from genkit.exp import Genkit
from genkit_fastapi.exp import serve_agent
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
app = FastAPI()


@ai.tool(description='Get current weather for a location')
async def get_weather(location: str) -> str:
    return f'Sunny in {location}'


weather_agent = ai.define_agent(
    name='weatherAgent',
    model=GoogleAI.gemini('gemini-flash-latest'),
    system='You are a helpful weather assistant.',
    tools=[get_weather],
)

# Mount agent turn route at POST /api/weatherAgent
# (/getSnapshot and /abort are added only when the agent has a store=)
app.include_router(serve_agent(weather_agent), prefix='/api')

Custom Base Path & Dependency Injection

Customize the base path or resolve request context using FastAPI's dependency injection system:

from fastapi import Header
from genkit_fastapi import serve_flow


async def user_context(authorization: str = Header(...)):
    return {'uid': parse_token(authorization)}


app.include_router(
    serve_flow(
        chat_flow,
        base_path='/chat',
        context_dependency=user_context,
    ),
    prefix='/api',
)

Streaming from Custom Routes (genkit.web.to_sse)

to_sse(handle) frames any streaming handle as Genkit SSE events: a data: {"message": ...} per chunk, then data: {"result": ...}, or data: {"error": ...} if the run fails. It takes flow.stream(), ai.generate_stream(), prompt.stream() and chat.send_stream(), so your route keeps its own typed params and Depends(...) and still sends the frames serve_flow sends:

from fastapi import Depends, FastAPI
from fastapi.responses import StreamingResponse
from genkit import FlowContext, Genkit
from genkit.web import to_sse

ai = Genkit(...)
app = FastAPI()


@ai.flow
async def ask_chef(prompt: str, ctx: FlowContext[str]) -> str:
    result = ai.generate_stream(prompt=prompt)
    # The context manager closes the model stream if the client disconnects.
    async with result.stream as chunks:
        async for chunk in chunks:
            ctx.send_chunk(chunk.text)
    return (await result.response).text


@app.post('/chat/stream')
async def chat_stream(prompt: str, user: User = Depends(current_user)):
    # 1. FastAPI owns the route: typed params, Depends, OpenAPI
    stream = ask_chef.stream(prompt, context={'user_id': user.id})

    # 2. Genkit owns the wire
    return StreamingResponse(to_sse(stream), media_type='text/event-stream')
    # => data: {"message":"Pad thai"}
    #    data: {"message":", no peanuts."}
    #    data: {"result":"Pad thai, no peanuts."}

to_sse(chat.send_stream(...)) frames agent turns the same way serve_agent does (AgentStreamChunk messages, then the AgentOutput result). Failures are logged with Python's logging module (5xx with a traceback, 4xx as a warning), so they show up wherever your app's logging config sends them.

Handling Full Genkit Requests (handle_genkit_request)

When FastAPI owns the route signature and Depends(...) parameters (for authentication, rate limiting, or database sessions) and you want one endpoint to serve both JSON POST ({"result": ...}) and SSE streaming (Accept: text/event-stream or ?stream=true), delegate the HTTP turn to handle_genkit_request:

from fastapi import Depends, Request
from genkit_fastapi import handle_genkit_request


@app.post('/api/deploy')
async def deploy_endpoint(request: Request, user: User = Depends(current_user)):
    return await handle_genkit_request(
        request,
        action=deploy_service,
        context={'user_id': user.id},
    )

Decorator Handler (genkit_fastapi_handler)

For custom route definitions, you can also use @genkit_fastapi_handler:

from genkit_fastapi import genkit_fastapi_handler


@app.post('/custom-chat')
@genkit_fastapi_handler(ai)
@ai.flow
async def custom_chat(prompt: str) -> str:
    response = await ai.generate(
        prompt=prompt,
        tools=[get_weather],
    )
    return response.text

Running

# With Genkit Dev UI
genkit start -- uvicorn main:app --reload

# Production (no Dev UI)
uvicorn main:app

Streaming

Endpoints automatically support streaming when the client sends Accept: text/event-stream or specifies ?stream=true:

curl -X POST http://localhost:8000/api/chat_flow \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{"data": "Tell me a joke"}'

Metadata

Release files for genkit-fastapi 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-fastapi 0.14.0
File Size Uploaded Provenance Actions
genkit_fastapi-0.14.0.tar.gz 32.8 kB With provenance Details for genkit_fastapi-0.14.0.tar.gz

Built distribution (wheel)

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

Total release size: 50.0 kB

Release files / genkit_fastapi-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_fastapi-0.14.0.tar.gz
Size 32.8 kB
Tags Source
SHA-256 checksum
How to use checksums
c784c9e3ebfe974fe66ada21fec01b9ac7fa1d78772044d3d99162f8a551e6a5
BLAKE2b-256 checksum
How to use checksums
7bd47c480c6a2c1653877e7c58ae2980557be63d6cb82ce16af4b0b43ac3e1ce
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_fastapi-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_fastapi-0.14.0-py3-none-any.whl
Size 17.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
daebe9acadae4b282a4e6d596009744adb231f26640938201e81f71645b0b854
BLAKE2b-256 checksum
How to use checksums
c764ad5fdc71578b778171656072e80ffeabd83478ce3b656e4e205bd53c2e9e
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-fastapi 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_fastapi-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