Skip to main content

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

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 (plus /getSnapshot and /abort companion endpoints)
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 Depends, 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:
    stream = ai.generate_stream(prompt=prompt)
    async for chunk in stream:
        ctx.send_chunk(chunk.text)
    return (await stream.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.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-fastapi 0.13.0
File Size Uploaded Provenance Actions
genkit_fastapi-0.13.0.tar.gz 26.1 kB With provenance Details for genkit_fastapi-0.13.0.tar.gz

Built distribution (wheel)

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

Total release size: 42.9 kB

Release files / genkit_fastapi-0.13.0.tar.gz

Download URL genkit_fastapi-0.13.0.tar.gz
Size 26.1 kB
Tags Source
SHA-256 checksum
How to use checksums
6f360ae2f3d7f765b7e577b4e6457b04fd11862060c51faf2812ca720c0f094c
BLAKE2b-256 checksum
How to use checksums
2ded247cd577ee06edf6db5cd3143d55226bc735ae71cf1540356b167396c5c4
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_fastapi-0.13.0-py3-none-any.whl

Download URL genkit_fastapi-0.13.0-py3-none-any.whl
Size 16.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
477143a69235789b20b9681a1699cd1dae58b00105d9783abb4fc8dd0b13c137
BLAKE2b-256 checksum
How to use checksums
070913f8c6cc2fdbc6a0a325b0139649676268db0bcb4f44fcadb070cd4352f0
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-fastapi 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_fastapi-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