Generated banner for Developing Genkit Python
Generated logo for Developing Genkit Python

Developing Genkit Python

GoogleOfficialPublished by Google

  • Skill
  • Tool integration
  • Data and AI
  • Apache-2.0
  • Medium risk

From the author

Develop AI-powered applications using Genkit in Python. Use when the user asks about Genkit, AI agents, flows, or tools in Python, or when encountering Genkit errors, import issues, or API problems.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The Genkit Python SDK provides a unified framework for developing AI features, including generation, streaming, tool integration, and multi-turn agents. It emphasizes a developer-centric workflow that integrates with the Genkit CLI for tracing, debugging, and monitoring model interactions. The framework supports advanced agent capabilities such as session management, human-in-the-loop interactions, branching, and background task execution.

What it does

  • Provides a unified SDK for building AI agents, flows, and generative features in Python.
  • Supports multi-turn agent interactions with state management and session persistence.
  • Enables observability through the Genkit CLI for tracing model inputs, outputs, and tool calls.
  • Facilitates integration with FastAPI for serving agents and flows.
  • Supports advanced agent patterns like background task execution, branching, and human-in-the-loop approval.
  • Includes tools for evaluating AI performance and managing prompts.

When to use it

  • When building AI-powered applications or chatbots in Python.
  • When you need to implement multi-turn agents with history and state.
  • When you need to debug AI model interactions, tool calls, or latency issues.
  • When you require a structured way to define and run generative flows.
  • When you need to integrate human-in-the-loop or background processing into AI workflows.

Advantages

  • Unified SDK for diverse AI tasks including generation, agents, and flows.
  • Powerful CLI-based tracing and debugging that works without modifying application code.
  • Native support for complex agent patterns like branching and background work.
  • Flexible session management for persistent agent interactions.
  • Seamless integration with existing Python web frameworks like FastAPI.

Usage examples

“How do I generate a simple response using Genkit in Python?”
The agent provides a code snippet using the Genkit class and GoogleAI plugin to perform a basic generate call.
“How can I debug my Genkit application to see tool calls?”
The agent explains how to use 'genkit start -- uv run src/main.py' to capture traces and inspect them via the Dev UI or CLI.
“How do I run a specific flow from the command line?”
The agent provides the 'genkit flow:run' command syntax to execute a named flow with specific input data.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/google/developing-genkit-python/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip developing-genkit-python.zip -d .agents/skills

Documentation by Google

Genkit Python

Build AI features in Python — generate, stream, tools, flows, and multi-turn agents — with one SDK.

Prerequisites

  • Python 3.10+ and uv (install)

  • Genkit CLI: npm install -g genkit-cli if genkit --version is missing

New app? Setup. Patterns? Examples.

Hello World

from genkit import Genkit
from genkit_google_genai import GoogleAI

ai = Genkit(
    plugins=[GoogleAI()],
    model='googleai/gemini-flash-latest',
)

async def main():
    response = await ai.generate(prompt='Tell me a joke about Python.')
    print(response.text)

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

Agents (Beta)

Multi-turn chats with history, typed state, human approval, branching, and background work. Start here: Agents.

chat = agent.chat()
res = await chat.send('Hello')           # AgentResponse
turn = chat.send_stream('Hello')         # AgentTurn — .stream / .response

More: sessions · HITL · branching · background · state · artifacts · custom · HTTP

Imports

  • Google AI: from genkit_google_genai import GoogleAI

  • Agents: from genkit.agent import InMemorySessionStore, ...

  • Middleware: from genkit_middleware import Middleware, ToolApproval, ...

  • FastAPI: from genkit_fastapi import serve_agent, serve_flow

  • Evals: from genkit_evaluators import register_genkit_evaluators

Workflow

  1. Agent or flow? If the task is conversational, multi-turn, or described as "an agent", "assistant", or "chatbot", build it with ai.define_agent (see Agents) rather than hand-rolling a generate + tools loop inside a flow. Reach for a plain flow only for single-shot, stateless generation.

  2. Set GEMINI_API_KEY. Use prefixed model ids (googleai/gemini-flash-latest).

  3. Enter via ai.run_main(main()) for Genkit apps (especially under genkit start). See Common Errors.

  4. Run with Dev Workflow (genkit start + Dev UI).

  5. Verify with traces, not a blind run. Running the app directly (uv run) does not capture dev traces. See Genkit CLI for how to run your app and capture traces.

  6. Stuck? Common Errors first.

genkit start unintrusively wraps any Python program that uses the Genkit library, running it unchanged while capturing traces from every Genkit action so you can prove tools were actually called and inspect model I/O from the terminal, even for headless checks. It forwards stdio, so interactive CLI tools that rely on stdin/stdout work without issues. Running the app directly (uv run) skips trace capture, so you're debugging blind.

Primary pattern (default): prefix genkit start -- to your normal run command. This collects telemetry from any Genkit code your program runs, whether triggered from the dev UI, your own web server/web UI, or a plain script:

genkit start -- uv run src/main.py
genkit start --noui -- uv run src/main.py   # same, without the Dev UI (still a persistent server)

genkit start runs until you stop it with Ctrl+C. That is expected and correct for the common cases: a server your web/mobile app calls, or an interactive CLI you exit yourself. --noui only drops the Dev UI; it is not a one-shot command and will not exit on its own. Do not use genkit start as a blocking step in automated/non-interactive contexts; use flow:run (below) for that.

Non-interactive use (agents/CI): add the global --non-interactive flag before -- so the CLI uses defaults and never blocks on a prompt (e.g. the first-run analytics notice): genkit start --non-interactive -- uv run src/main.py (works with flow:run too).

Run a flow (flow:run): invoke a specific flow by name from the CLI. Append your run command after -- to spin up the runtime just for this run (the command runs as-is to register your flows):

genkit flow:run myFlow '{"data": "input"}' -- uv run src/main.py

This is self-terminating: it runs the flow once, prints a Trace ID, then exits, so it's the right choice for a quick, non-interactive check (unlike genkit start). Note: flow:run runs flows (@ai.flow()), not agents; you can't flow:run an agent (ai.define_agent) directly. To exercise an agent from the CLI, wrap one turn in a throwaway flow and run that (see Agents).

Debugging with traces: the fastest way to see prompts, model inputs/outputs, tool calls, latencies, and errors. Inspect from the terminal after any run under genkit start:

genkit trace:list                        # find recent trace IDs
genkit trace:get <traceId>               # full trace details (inputs, outputs, tool calls, errors)
genkit trace:get <traceId> --format json # machine-readable JSON, safe to pipe into jq or other parsers

For machine-readable output, pass --format json to get clean JSON you can pipe into jq or other parsers. The default output is human-oriented (banner/log lines, possible truncation on large traces), so don't pipe that form directly; use --format json, grep, or the Dev UI trace viewer.

See Dev Workflow for the full checklist and Dev UI walkthrough.

References

Files

references/fastapi.md

FastAPI — Genkit Python

Install

uv add genkit-fastapi fastapi uvicorn

Import from genkit_fastapi:

  • serve_agent / serve_flow — mount an agent or flow as a router

  • handle_genkit_request — escape hatch for a custom @app.post that needs its own Depends / auth wiring while still speaking the Genkit wire format

For agents, see also Agent HTTP.


Serve an agent or flow

import uvicorn
from fastapi import FastAPI
from genkit import Genkit
from genkit.agent import InMemorySessionStore
from genkit_fastapi import serve_agent, serve_flow
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()], model='googleai/gemini-flash-latest')

agent = ai.define_agent(
    name='weatherAgent',
    system='Weather assistant. Be concise.',
    store=InMemorySessionStore(),
)

@ai.flow()
async def hello(name: str) -> str:
    return f'Hello, {name}'

app = FastAPI()
# Routes use the action name as defined: agent `weatherAgent` → /api/weatherAgent;
# flow `hello` → /api/hello. Override with base_path=... if needed.
app.include_router(serve_agent(agent), prefix='/api')
app.include_router(serve_flow(hello), prefix='/api')

# Under genkit start, drive uvicorn from ai.run_main (don't nest uvicorn.run inside it).
async def main() -> None:
    import os
    config = uvicorn.Config(app, host='0.0.0.0', port=int(os.environ.get('PORT', '8080')))
    await uvicorn.Server(config).serve()

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

Streaming

serve_agent, serve_flow, and handle_genkit_request all stream when the client sends Accept: text/event-stream (same wire path). Otherwise they return a one-shot {"result": ...} JSON body.

Wire format (SSE):

data: {"message": "<chunk text>"}   ← one per ctx.send_chunk() call
data: {"message": "<chunk text>"}
data: {"result": <final output>}    ← sent once when the action completes

Frontend:

const res = await fetch('/api/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream' },
  body: JSON.stringify({ data: { topic: 'quantum computing' } }),
});
const reader = res.body.getReader();
// decode and parse each `data: {...}` line

curl test:

curl -N -X POST http://localhost:8080/api/chat \
  -H 'Content-Type: application/json' \
  -H 'Accept: text/event-stream' \
  -d '{"data": {"topic": "quantum computing"}}'

Minimal streaming FastAPI app

import uvicorn
from pydantic import BaseModel
from fastapi import FastAPI
from genkit import Genkit, ActionRunContext
from genkit_fastapi import serve_flow
from genkit_google_genai import GoogleAI

ai = Genkit(plugins=[GoogleAI()], model='googleai/gemini-flash-latest')


class ChatInput(BaseModel):
    topic: str


@ai.flow()
async def chat(input: ChatInput, ctx: ActionRunContext) -> str:
    sr = ai.generate_stream(prompt=f'Tell me about {input.topic}.')
    full = ''
    async for chunk in sr.stream:
        if chunk.text:
            ctx.send_chunk(chunk.text)   # each chunk → SSE event on the wire
            full += chunk.text
    return full


app = FastAPI()
app.include_router(serve_flow(chat), prefix='/api')  # POST /api/chat

async def main() -> None:
    import os
    config = uvicorn.Config(app, host='0.0.0.0', port=int(os.environ.get('PORT', '8080')))
    await uvicorn.Server(config).serve()

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

Key: the flow must accept ctx: ActionRunContext and call ctx.send_chunk(text) to emit SSE chunks. Without ctx.send_chunk, the flow runs but streams nothing — the client waits for the final result.


Advanced use cases

Nested flow streaming

Chain flows so a child's chunks surface on the parent's HTTP stream. Call the child with .run(..., on_chunk=ctx.send_chunk) — do not pass ctx as a second positional argument to await child(input, ctx) (that raises TypeError).

class ResearchInput(BaseModel):
    topic: str

@ai.flow()
async def research(input: ResearchInput, ctx: ActionRunContext) -> str:
    sr = ai.generate_stream(prompt=f'Explain {input.topic} in depth.')
    full = ''
    async for chunk in sr.stream:
        if chunk.text:
            ctx.send_chunk(chunk.text)
            full += chunk.text
    return full


class HeadlineInput(BaseModel):
    text: str

@ai.flow()
async def make_headline(input: HeadlineInput) -> str:
    response = await ai.generate(prompt=f'One-line headline for: {input.text}')
    return response.text.strip()


class ReportInput(BaseModel):
    topic: str

@ai.flow()
async def report(input: ReportInput, ctx: ActionRunContext) -> str:
    headline = await make_headline(HeadlineInput(text=input.topic))
    ctx.send_chunk(f'# {headline}\n\n')

    body = (
        await research.run(
            ResearchInput(topic=input.topic),
            on_chunk=ctx.send_chunk,
        )
    ).response

    return f'# {headline}\n\n{body}'


app.include_router(serve_flow(report), prefix='/api')  # POST /api/report

Rules:

  • Streaming children accept ctx: ActionRunContext and call ctx.send_chunk

  • Parents forward chunks with child.run(input, on_chunk=ctx.send_chunk)

  • Non-streaming children: await child(input) is fine

Executing flows in parallel

Use asyncio.gather to run multiple flows concurrently. Only makes sense when children don't need to stream.

import asyncio

class AnalysisInput(BaseModel):
    text: str

class CheckResult(BaseModel):
    issues: list[str]

class CombinedAnalysis(BaseModel):
    issues: list[str]

@ai.flow()
async def check_security(input: AnalysisInput) -> CheckResult:
    r = await ai.generate(
        prompt=f'List security concerns as a short comma-separated line (or "none"): {input.text[:2000]}',
    )
    raw = (r.text or '').strip()
    issues = [s.strip() for s in raw.split(',') if s.strip() and s.strip().lower() != 'none']
    return CheckResult(issues=issues)

@ai.flow()
async def check_bugs(input: AnalysisInput) -> CheckResult:
    r = await ai.generate(
        prompt=f'List likely bugs or correctness issues as a short comma-separated line (or "none"): {input.text[:2000]}',
    )
    raw = (r.text or '').strip()
    issues = [s.strip() for s in raw.split(',') if s.strip() and s.strip().lower() != 'none']
    return CheckResult(issues=issues)

@ai.flow()
async def check_style(input: AnalysisInput) -> CheckResult:
    r = await ai.generate(
        prompt=f'List style or clarity issues as a short comma-separated line (or "none"): {input.text[:2000]}',
    )
    raw = (r.text or '').strip()
    issues = [s.strip() for s in raw.split(',') if s.strip() and s.strip().lower() != 'none']
    return CheckResult(issues=issues)

@ai.flow()
async def analyze(input: AnalysisInput) -> CombinedAnalysis:
    security, bugs, style = await asyncio.gather(
        check_security(input),
        check_bugs(input),
        check_style(input),
    )
    return CombinedAnalysis(issues=security.issues + bugs.issues + style.issues)


app.include_router(serve_flow(analyze), prefix='/api')  # POST /api/analyze

Structured output endpoint (non-streaming)

class SentimentResult(BaseModel):
    sentiment: str        # positive / negative / neutral
    confidence: float     # 0.0–1.0
    key_phrases: list[str]

@ai.flow()
async def sentiment(input: AnalysisInput) -> SentimentResult:
    response = await ai.generate(
        prompt=f'Analyze sentiment: {input.text}',
        output_format='json',
        output_schema=SentimentResult,
    )
    return response.output


app.include_router(serve_flow(sentiment), prefix='/api')  # POST /api/sentiment

Client calls this without Accept: text/event-stream — gets {"result": {...}} back.


Custom route with handle_genkit_request

When you need your own FastAPI dependencies (auth, tenancy, etc.) and still want the Genkit wire format, call handle_genkit_request from a hand-written route:

from fastapi import Depends, Request
from genkit_fastapi import handle_genkit_request


async def current_user(request: Request) -> dict:
    # Resolve auth however you like.
    return {'uid': request.headers.get('x-user-id', 'anon')}


@app.post('/api/secure-chat')
async def secure_chat(
    request: Request,
    user: dict = Depends(current_user),
):
    return await handle_genkit_request(
        request,
        action=chat,
        context={'auth': user},
    )

Prefer serve_flow / serve_agent with context_dependency= when a single Depends is enough — use handle_genkit_request when the route shape itself needs to be custom.


Run with Dev UI

GEMINI_API_KEY=your-key genkit start -- uv run src/main.py

Leave the process running until the CLI prints something like:

Genkit Developer UI: http://localhost:4000

Open that URL. Port may differ if 4000 is busy.

Python HTTP client (mounted flows)

import httpx, asyncio

async with httpx.AsyncClient(base_url='http://127.0.0.1:18524') as client:
    async def call(path, data):
        r = await client.post(path, json={'data': data})
        r.raise_for_status()
        return r.json()['result']
    a, b = await asyncio.gather(
        call('/api/summarize', {'text': '...'}),
        call('/api/sentiment', {'text': '...'}),
    )

Wire shape is {"data": ...} in, {"result": ...} out (not raw flow args).

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an API key, Needs Python, Needs Node.js

Security

What our scanner noticed· Medium risk

  • Instructions that use the network
  • Downloads piped into a shell

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/developing-genkit-python · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google or Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download developing-genkit-python.zip