Skill files18 files

references/

SKILL.md236 lines
1
---
2
name: developing-genkit-python
3
description: >-
4
Provides guidance on developing AI-powered applications using Genkit Python
5
(0.13) and migrating Genkit Python 0.12 projects to 0.13. Use when building AI
6
agents, flows, tools, structured outputs, or FastAPI routes in Python,
7
upgrading from Genkit 0.12, or debugging Genkit imports, config errors, or
8
traces. Don't use for Genkit in JavaScript/TypeScript, Go, or Dart.
9
metadata:
10
version: "1.0.0"
11
category: AiAndMachineLearning
12
---
13
14
# Genkit Python
15
16
Build AI features in Python — generation, structured output, streaming, tools,
17
flows, and multi-turn agents — with Genkit Python 0.13.
18
19
- **New project?** See [Setup](references/setup.md) and
20
[Examples](references/examples.md).
21
- **Upgrading from 0.12 or fixing broken 0.12 imports/signatures?** Read
22
[Migrating from 0.12 to 0.13](references/migrating-from-0.12.md) first.
23
24
## Prerequisites
25
26
- Python **3.10+** and **`uv`**
27
([install](https://docs.astral.sh/uv/getting-started/installation/))
28
- Genkit CLI: `npm install -g genkit-cli` if `genkit --version` is missing
29
30
## Hello World
31
32
```python
33
from genkit import Genkit
34
from genkit_google_genai import GoogleAI
35
36
ai = Genkit(
37
plugins=[GoogleAI()],
38
model=GoogleAI.gemini('gemini-flash-latest'),
39
)
40
41
42
async def main() -> None:
43
response = await ai.generate(prompt='Suggest one seasonal pasta dish.')
44
if response.error:
45
raise RuntimeError(response.error.message)
46
print(response.text)
47
# => Lemony tagliatelle with asparagus, sweet peas, and herb ricotta
48
49
50
if __name__ == '__main__':
51
ai.run_main(main())
52
```
53
54
`ai.generate` does not raise when the provider rejects or fails a call
55
(`INVALID_ARGUMENT`, `UNAVAILABLE`, rate limits). It returns `response.error`
56
(`Failure` with `.status` and `.message`), `finish_reason == 'failed'`, and
57
empty text. Problems caught before the call raise: `GoogleAI()` raises
58
`ValueError` without `GEMINI_API_KEY`; an unknown model, invalid key, or unknown
59
config field raises `GenkitError`. See
60
[Common Errors](references/common-errors.md).
61
62
## Agents (Experimental)
63
64
Multi-turn chats with history, typed state, human approval, branching, and
65
background work live under `genkit.exp` and `genkit.exp.agent`. Start here:
66
[Agents](references/agents.md).
67
68
```python
69
from genkit.exp import Genkit
70
from genkit.exp.agent import InMemorySessionStore
71
from genkit_google_genai import GoogleAI
72
73
ai = Genkit(plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'))
74
agent = ai.define_agent(
75
name='concierge',
76
system='You are a concise hotel concierge.',
77
store=InMemorySessionStore(),
78
)
79
80
chat = agent.chat()
81
res = await chat.send('Recommend a quiet dinner spot.') # AgentResponse
82
print(res.text)
83
# => Try Osteria Lume on 5th; it has booths and low music.
84
85
turn = chat.send_stream('Is it open past 10pm?') # AgentTurn
86
async for chunk in turn.stream:
87
if chunk.text:
88
print(chunk.text, end='')
89
final = await turn.response # AgentResponse
90
```
91
92
More: [sessions](references/agents-sessions.md) ·
93
[HITL](references/agents-human-in-the-loop.md) ·
94
[branching](references/agents-branching.md) ·
95
[background](references/agents-background.md) ·
96
[state](references/agents-state.md) ·
97
[artifacts](references/agents-artifacts.md) ·
98
[custom](references/agents-custom.md) ·
99
[HTTP](references/agents-http.md)
100
101
## Imports
102
103
Every symbol lives in one public module (never import private `_` submodules;
104
see [Migrating from 0.12 to 0.13](references/migrating-from-0.12.md) if a 0.12
105
symbol moved):
106
107
- **Core app**: `from genkit import Genkit, FlowContext, ToolContext, Message, Part, Role, Media, Document, MultipartToolResponse, PublicError, GenkitError, Failure, ErrorReason`
108
- **Google GenAI & Vertex AI**: `from genkit_google_genai import GoogleAI, VertexAI, GeminiConfig, GeminiImageConfig, GeminiTtsConfig`
109
- **Other providers**: `from genkit_vertexai import ModelGarden` ·
110
`from genkit_anthropic import Anthropic, AnthropicConfig` ·
111
`from genkit_openai import OpenAI, OpenAIConfig` ·
112
`from genkit_ollama import Ollama, OllamaConfig` ·
113
`from genkit_amazon_bedrock import Bedrock, BedrockConfig`
114
- **Built-in middleware**: `from genkit_middleware import Middleware, Retry, Fallback, ToolApproval, Skills, Filesystem` (plus `from genkit_middleware.exp import Artifacts` for agent sessions)
115
- **Writing custom middleware**:
116
`from genkit.middleware import Middleware, MiddlewareContext`
117
- **FastAPI & HTTP**:
118
`from genkit_fastapi import serve_flow, genkit_fastapi_handler,
119
handle_genkit_request` · `from genkit_fastapi.exp import serve_agent` ·
120
`from genkit.web import RequestData, to_sse, error_body, error_status`
121
- **Agents (experimental)**: `from genkit.exp import Genkit, current_session` · `from genkit.exp.agent import Agent, Session, InMemorySessionStore, FileSessionStore, remote_agent`
122
- **Telemetry**: `from genkit_google_cloud import enable_google_cloud_telemetry`
123
· `from genkit.telemetry import configure_instrumentation` ·
124
`from genkit_otel import GenAiInstrumentation`
125
- **MCP (Client & Host)**: `from genkit_mcp import define_mcp_client, define_mcp_host, McpClient, McpHost`
126
- **Testing & Mocks**: `from genkit.testing import define_echo_model, define_scripted_model, EchoModel, ScriptedModel`
127
- **Evaluators (0.13 only; cut from 1.0, additive later)**:
128
`from genkit_evaluators import register_genkit_evaluators` ·
129
`from genkit.evaluator import BaseDataPoint, EvaluatorResponse, Score,
130
ScoreDetails, ScoreStatus`
131
132
## Workflow
133
134
1. **Agent or flow?** Use `ai.define_agent` (on `genkit.exp.Genkit`, see
135
[Agents](references/agents.md)) for multi-turn chats, state, or
136
human-in-the-loop approval instead of hand-rolling a message loop inside a
137
flow. Use `@ai.flow()` on `genkit.Genkit` for stateless request/response or
138
streaming pipelines.
139
2. **Configure credentials & model refs.** Set **`GEMINI_API_KEY`**. Prefer
140
typed refs (`GoogleAI.gemini('gemini-flash-latest')`) and typed flat configs
141
(`GeminiConfig(...)`) so your type checker validates fields before runtime.
142
Prefixed strings (`'googleai/gemini-flash-latest'`) also work.
143
3. **Enter via `ai.run_main(main())`** for standalone scripts and CLI apps so
144
the process stays up for the Dev UI under `genkit start`. FastAPI apps skip
145
`run_main`; uvicorn keeps the process alive:
146
`genkit start -- uv run uvicorn main:app --reload`.
147
4. **Run with [Dev Workflow](references/dev-workflow.md)** (`genkit start` + Dev
148
UI) and type-check with `pyright`, `mypy`, or `ty`.
149
5. **Verify with traces**, not a blind `uv run`. See
150
[Genkit CLI](#genkit-cli-recommended).
151
6. **Stuck?** Check [Gotchas](#gotchas),
152
[Common Errors](references/common-errors.md), or
153
[Migrating from 0.12 to 0.13](references/migrating-from-0.12.md).
154
155
## Gotchas
156
157
- **Agents need `genkit.exp`**: `from genkit.exp import Genkit`. Stable
158
`genkit.Genkit` has no `define_agent`.
159
- **Tools are async**: `@ai.tool()` raises `TypeError` on a plain `def`; use
160
`async def`.
161
- **Check `response.error`**: provider failures come back on the response, not
162
as exceptions (see [Hello World](#hello-world)).
163
- **Gemini thinking levels**: `GeminiConfig(thinking_level='MINIMAL')` fails on
164
`gemini-flash-latest`; use `'LOW'`, `'MEDIUM'`, or `'HIGH'`.
165
- **Vertex AI model IDs**: Vertex does not serve `-latest` aliases. Pass a
166
pinned model ID to `VertexAI.gemini(...)`.
167
- **Logging**: `genkit.get_logger` is structlog-based.
168
`enable_google_cloud_telemetry()` injects trace context for GCP log-trace
169
correlation.
170
- **Cloud telemetry auth**: call `enable_google_cloud_telemetry()` with
171
Application Default Credentials or explicit `credentials=` (service account
172
dict or `Credentials` instance).
173
174
## Genkit CLI (recommended)
175
176
`genkit start` wraps any Python program that uses Genkit, capturing traces from
177
every action while forwarding stdio cleanly. Running `uv run` directly skips
178
trace capture.
179
180
**Primary pattern (persistent server + Dev UI):**
181
```bash
182
genkit start -- uv run src/main.py
183
genkit start --noui -- uv run src/main.py # persistent runtime without opening the Dev UI
184
```
185
`genkit start` runs until stopped with Ctrl+C (even with `--noui`). Do **not**
186
run `genkit start` as a blocking step in automated/non-interactive scripts; use
187
`flow:run` instead.
188
189
**Non-interactive use (agents/CI):** pass `--non-interactive` before `--` so the
190
CLI never blocks on prompts:
191
```bash
192
genkit start --non-interactive -- uv run src/main.py
193
```
194
195
**One-shot flow execution (`flow:run`):** spins up the runtime, invokes one
196
`@ai.flow()` by name, prints a `Trace ID`, and exits:
197
```bash
198
genkit flow:run myFlow '{"data": "input"}' -- uv run src/main.py
199
```
200
Note: `flow:run` invokes flows (`@ai.flow()`), not agents (`ai.define_agent`).
201
Wrap a single agent turn in a helper flow to exercise it via `flow:run` (see
202
[Agents](references/agents.md)).
203
204
**Inspecting traces:**
205
```bash
206
genkit trace:list # list recent trace IDs
207
genkit trace:get <traceId> # human-readable trace inspection
208
genkit trace:get <traceId> --format json # machine-readable JSON for jq / scripts
209
```
210
Always pass `--format json` when piping into `jq` or other parsers.
211
212
See [Dev Workflow](references/dev-workflow.md) for the full pre-run checklist
213
and Dev UI walkthrough.
214
215
## References
216
217
- [Migrating from 0.12 to 0.13](references/migrating-from-0.12.md):
218
Deterministic 0.12 -> 0.13 renames, config flattening, `PublicError`, and
219
`exp` moves.
220
- [Examples](references/examples.md): Structured output, streaming, media parts,
221
flows, tools, interrupts, cancellation, embeddings.
222
- [Setup](references/setup.md): Project bootstrap with `uv`, version alignment,
223
and provider plugins.
224
- [Common Errors](references/common-errors.md): Fast fixes for 0.13 validation
225
errors, HTTP 500 redaction, streaming, and sessions.
226
- [FastAPI](references/fastapi.md): `serve_flow`, `serve_agent`, `PublicError`,
227
SSE streaming, and parallel flows.
228
- [Dotprompt](references/dotprompt.md): `.prompt` files, schema validation,
229
variants, partials, and helpers.
230
- [Evals](references/evals.md): 0.13 evaluator syntax (deprecated; removed in
231
1.0).
232
- [Dev Workflow](references/dev-workflow.md): `genkit start`, Dev UI, and trace
233
verification checklist.
234
- [Agents (Experimental)](references/agents.md): Multi-turn stateful agents
235
(`genkit.exp`).
236

© Google LLC · Apache 2.0 · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…