Repository navigation
chore(py): release Python SDK v0.13.0 - #7093
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
Code Review
This pull request updates the Genkit Python SDK and its packages from version 0.12.0 to 0.13.0, including dependency updates in pyproject.toml files and uv.lock. It also adds a detailed migration guide to help users transition between these versions. The feedback recommends enhancing the namespace lookup helper script in the migration guide by wrapping the dynamic imports in a try-except block to prevent crashes when optional dependencies are missing.
pavelgj
approved these changes
Nov 5, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Genkit Python 0.13 is the last release with major breaking changes, and the last release before 1.0. Yes, there are a lot of breaking changes, and that's on purpose. The SDK we had going in carried many conventions borrowed from Genkit JS and Go. In this release we went through the whole API surface and made it feel native to Python, while keeping it consistent with what you'd expect from the other Genkit SDKs.
We chose clean breaks over deprecation shims and aliases because we want a clean, Pythonic API surface going into 1.0, not one that carries two names for everything. We didn't want to break you a little at a time before 1.0, and we won't break you after it. So everything that wasn't Pythonic comes to light in this one release. This is the API we're sticking with, and you shouldn't expect changes like these going forward.
Upgrading? Follow the 0.12 → 0.13 migration guide, or point your coding agent at it.
Evaluators are the one exception. They still ship in 0.13 and go away in 1.0, the next release, while we redesign them across all the Genkit SDKs. We kept them on purpose. Older plugin releases accepted any version of
genkit, so removing evaluators now could let pip install an oldgenkit-evaluatorsnext to agenkitthat no longer has them. 0.13 adds version bounds to every plugin, andgenkit-evaluatorsnow requiresgenkit<1, so the next release can remove them cleanly (see below).Why upgrade
Feels like Python
Your IDE and type checker now catch Genkit mistakes before you run anything. Contexts are generic, config fields are typed
Literals, and signatures are keyword-only. Cancellation is plainasyncio, and flow input and output are validated by Pydantic.Safe by default
In 0.12, some mistakes failed silently or in surprising places. In 0.13 they fail where you made them, with an error that names the problem.
BaseException, likeasyncio.CancelledError. A tool'sexcept Exception:can no longer turn an approval request into an error and let the turn continue without approval.response.outputisNoneandresponse.errorreportsINVALID_OUTPUT.context.secrets, but some plugins silently dropped or ignored a key left in model config. Every plugin now raises instead.Errors are safe to serve
When you serve flows over HTTP, errors no longer leak. In 0.12, a served flow sent the client the message and details of any
GenkitError, plus the text and stack trace of any other exception. In 0.13, the client sees only what you mark as public, and your own code still sees everything.Provider errors, internal details and stack traces stay on your server, and you decide exactly which messages reach callers (see section 8 below).
Consistent concepts and names
The data types you pass around now share names with the other SDKs, mostly Genkit Go: model and embedder refs (
ModelRef,EmbedderRef,BackgroundModel), model metadata (ModelSupports,ModelStage,GenerationUsage), evaluator results (EvaluatorResponse,ScoreStatus,ScoreDetails),Formatter,ToolContextandMultipartToolResponse. What you read in one SDK's docs maps onto these. The parts you write code against are Python's own: flow and model contexts,FailureandGenkitError, middleware classes, and plugins as classes with keyword arguments and refs likeGoogleAI.gemini(...). Every provider plugin follows the same constructor, config and error conventions, so switching providers is a small, predictable change.Typed config, with one escape hatch:
extraEvery config class now declares its fields and rejects anything else. For provider settings a plugin doesn't model yet, every provider plugin has the same escape hatch,
extra. Its contents go to the provider under the provider's own field names, merged into the request Genkit builds, and they win on conflict.extralands in its request.API changes
Every public API change in 0.13, grouped by area. Each one shows the 0.12 code and what replaces it.
1. One home for every symbol
The public API is now a small set of namespaces. Each one's
__init__.pylists exactly what it exports, each is stripped down to its essentials, and every public symbol lives in exactly one of them. You, and your coding agent, can predict where an import lives without searching.The rule for where a symbol lives follows who uses it:
genkit. Anything an application calls or handles lives there, including types that plugin authors share with apps, such asMessage,PartandDocument. The top level went from 49 names to 27 (feat(py)!: clean up exported symbols on the core API surface #6390, feat(py)!: drop unused and string-helper exports before 1.0 #6669).genkit.model,genkit.embedder,genkit.evaluator,genkit.middlewareorgenkit.formats.genkit.plugin_api.genkit.webfor serving,genkit.telemetryfor tracing backends,genkit.testingfor fake models, andgenkit.expfor experimental APIs.genkit_google_genai.Model helpers also lost their
_modelsuffix:GoogleAI.gemini(...),Anthropic.claude(...). The migration guide lists every symbol that moved and where it went (#6486, #6512, #6550, #6662, #6671, #6682, #6690, #6698, #6699, #6766, #6777).2. Keyword-only arguments
Constructors, and every option after an action's input, are keyword-only. If you see
TypeError: takes N positional arguments, name the argument.Genkit (#6536)
Running actions (#6769)
Plugins (#6684, #6630)
Evaluators (#6672)
3. Config
Every config class now extends
GenkitConfig. Provider config is flat, and an unknown key raises before the model is called. Dict keys may be snake_case or camelCase.Class names (#6506, #6620)
Gemini: thinking, search and voice are flat fields (#6593, #6698)
Anthropic: one flat config (#6596, #6699)
Tool choice moves to generate (#6699)
Provider settings without a field go in extra (#6634, #6644, #6646)
options= is now config=, like generate (#6569)
ai.generatehas always takenconfig=.ai.embedandai.embed_manycalled the same thingoptions=. Now every call that configures a model or embedder usesconfig=.await ai.generate(prompt=p, config={'temperature': 0.2}) # unchanged - await ai.embed(embedder=e, content=doc, options={'task_type': 'RETRIEVAL_DOCUMENT'}) + await ai.embed(embedder=e, content=doc, config={'task_type': 'RETRIEVAL_DOCUMENT'})How config layers combine (#6697, #6712, #6714, #6978)
Config for a call can come from four layers. Later layers win, one key at a time:
GoogleAI.gemini('...', config=...)define_prompt(config=...)or a.promptfileconfig=A layer only overrides the keys it sets. Everything else passes through from the layer below.
Noneis a value. It clears a key inherited from a lower layer. To inherit a key, leave it out.thinking_levelwiththinking_budget, are checked once on the merged config, after middleware runs.Noneon the call, and it's dropped before the new model sees it.Typos raise now (#6587, #6675)
Also removed:
EmbeddingTaskType,VertexAIEvaluationMetricType(pass the string value), Anthropic'sThinkingConfig/OutputConfig/TaskBudget/RequestMetadata/*ToolChoice, andOpenAIConfig.user.4. API keys
Per-request keys already belonged in
context.secrets; Google GenAI read them from there in 0.12. What changes in 0.13 is that every plugin now fails loudly when a key is in model config. Before, Ollama silently dropped it, and Anthropic could ignore it with only a log warning, so a request might quietly run on the wrong key or none at all. Now Google GenAI, OpenAI, Anthropic and Ollama all raise before anything is sent.Vertex AI Model Garden authenticates with ADC and rejects a per-request key.
ai.embed()takes nocontext, so embedders always use the plugin's key (#6595, #6596, #6597, #6643, #6644).5. Typed contexts
ActionRunContextsplits into one typed context per kind of action, and the chunk type moves into the context's type parameter. Genkit finds the context by its annotation.Flows (#6538, #6768, #6986)
Tools (which can now stream too) (#6314)
Models you implement (#6768)
The new contexts subclass
ActionRunContext, so an old annotation still type-checks. Onlyfrom genkit import ActionRunContextbreaks.6. Cancellation
Python already has a cancellation model:
asynciodelivers cancellation to whatever code is running,try/finallycleans up, and every async library follows the same rules. 0.12 layered a second, JS-style mechanism on top that your code had to opt into. 0.13 drops it and uses the one Python developers already know.The generate loop switches back and forth between framework code and code you supply, such as tools and middleware. In 0.12, cancelling it followed the JS pattern: Genkit set an abort signal, and your code had to check it. A tool that didn't check kept running after the caller gave up. Its side effects still happened, and its result was thrown away.
In 0.13, cancellation is native
asynciocancellation. Cancelling a call raisesasyncio.CancelledErrorat whateverawaityour code is paused on, so your tools stop without checking anything.ctx.abort_signalis removed.That changes how you write tools. Instead of polling for an abort, put cleanup in
finally, which runs whether the tool finishes, fails or is cancelled.If you catch
asyncio.CancelledErroryourself, re-raise it. Swallowing it keeps the work running.All of these cancel the whole call, including the model request, any
Retrybackoff, and every running tool:A served flow is also cancelled when the client disconnects from its SSE stream. When one tool in a turn fails, Genkit cancels the other tools in that turn and waits for their
finallyblocks to finish (#6685, #6952, #7001, #7056).7. Errors
There are two kinds of error, and they serve different purposes:
Failureis a returned value. When a generation or agent turn fails at runtime, the call doesn't raise. You get the failure back onres.errorand inspect it.GenkitErroris the exception you catch. When a call raises, you handle it withtry/except GenkitError.Returned failures (#6572, #6767)
Raised errors (#6639, #6767)
Interrupts are no longer Exceptions (#6763)
An interrupt isn't an error. It's a tool pausing to ask for something, such as human approval. Python already uses
BaseExceptionfor signals like this (KeyboardInterrupt,asyncio.CancelledError), so thatexcept Exception:handlers written for failures don't swallow them. Tools often wrap their work inexcept Exception:to report errors back to the model. In 0.12, that same handler also caught the interrupt, so an approval request could turn into an error message and the turn would carry on without approval.If you catch interrupts on purpose, catch
Interruptby name.Plugin exception types are gone (#6710)
8. Errors sent to HTTP clients
When you serve flows over HTTP, with Flask, FastAPI, Django or
genkit.web, errors now cross the wire safely by default. Inside your process, nothing is hidden (#6499).In 0.12, a served flow sent the client the message and details of any
GenkitError, plus the text and stack trace of any other exception. Whoever called your endpoint could see provider error messages, internal details and stack traces.0.13 treats the two audiences differently:
GenkitErrorwithstatus,message,detailsand__cause__, or your own exception, unwrapped. Logs, tests, middleware and the Dev UI see everything.PublicErrorwith a status and a message written for the caller, and the client gets that message with the matching HTTP status, such as 404. Anything else becomes a 500 with{"status": "INTERNAL", "message": "Internal Error"}.A provider failure, such as an expired API key, is
UNAUTHENTICATEDin your process but reaches the client as a 500. A 401 there would hint at your credentials. Streaming endpoints follow the same rule for their error event. APublicErrorraised in a context provider is handled the same way, which is how auth returns a 401 or 403 the caller can act on.Invalid input to a served flow still returns a 400 that names the failing fields, without the values the caller sent. Every failure is still logged on the server with the flow's name: 5xx errors with the full traceback, 4xx errors as warnings. For your own routes,
genkit.web.error_body()anderror_status()apply the same rules.9. Serving and telemetry
Serving types now live in
genkit.web, and the Flask, FastAPI and Django adapters all behave the same way. Telemetry is pluggable OpenTelemetry.Context providers (#6534, #6709)
Google Cloud telemetry (#6591, #6630, #6633)
The
FIREBASE_PROJECT_IDfallback is gone; setproject=orGOOGLE_CLOUD_PROJECT.Custom exporters (#6132)
New in this release:
genkit.web.to_sse()for custom streaming routes,genkit_django_handler, and thegenkit-otelpackage, whoseGenAiInstrumentationemits OpenTelemetry GenAI spans and metrics (#6388, #6655).10. Provider plugins
Each plugin package exposes only its top-level module and takes model names as plain strings. Config changes are in section 3.
Google GenAI (#6300, #6305, #6363, #6826, #7049)
Vertex AI Model Garden (#6500, #6594)
OpenAI (#6512, #6634)
Ollama (#6637, #6643, #6706, #6707)
Ollama no longer reads media from local file paths.
Amazon Bedrock (#6644, #6706, #6977)
Flask (#6631)
# genkit-flask no longer installs genkit-google-genai for you uv add genkit-google-genaiFor every provider, media URLs over 20 MB now fail instead of downloading (#6637).
Evaluators: last release before the redesign (#7029)
We're redesigning evaluators as a concept across all the Genkit SDKs, so 1.0, the next release, removes the current evaluator APIs and the
genkit-evaluatorspackage. We kept them in 0.13 on purpose. Until now, plugins depended ongenkitwith no upper bound, so removing something fromgenkitcould leave pip or uv pairing an older plugin with agenkitit can't run on. 0.13 is the first release where every plugin declares the range ofgenkitversions it supports, andgenkit-evaluators0.13.0 requiresgenkit<1. That gives the removal a clean boundary: installs that pin the 0.13 line keep working, and the next release can drop evaluators without breaking anyone's resolver. If you rely on evaluators, stay on 0.13 until the new design ships.Behavior changes
These run without edits, but they behave differently.
Templates only render in prompts (#6553)
Only complete JSON becomes output (#6573, #7003)
chunk.outputnever raises while streaming.Prompt calls take generate's keyword names (#6539, #6590)
Prompt input is validated,
.promptfile defaults are filled in, and file schemas return the registered class.Flow input and output are validated (#6575)
Actions raise what their body raised (#6576, #6586)
RetryandFallbackonly retry failures a plugin has classified, such asUNAVAILABLE.Smaller changes
await tool(x)returns what the function returned (fix(py)!: a Tool is an Action; await tool(x) returns what the function returned #6681).Messagenested in your own Pydantic model serializes like it does on its own: camelCase, no nulls (fix(py)!: a Message inside your own Pydantic model dumps the same as on its own #6559).thoughtSignaturefor every provider (fix(py)!: thinking signatures use thoughtSignature on every provider #6588).max_turns(fix(py): long generate tool loops return at max_turns #6501).response.outputis typedOutputT | None, for type checkers only (fix(py)!: response.output is typed OutputT | None #6537).Plugin and middleware authors
Skip this if you only call Genkit.
genkit.plugin_apiis now a small surface, and builder functions became classes.Middleware (#6502, #6775)
A middleware's
tools()returnsToolhandles.GenerateMiddleware,MiddlewareRef,MiddlewarePluginandnew_middlewareare gone.Defining models and embedders (#6697, #6757, #6777)
Resolving models (#6574)
Provider errors (#6586, #6710)
Clients, headers and logging (#6674, #6764, #7033)
Tracing (#6132)
Also (#6562, #6689, #6757, #6765, #7049):
Plugin.model()/Plugin.embedder()andSupports.contextare removed.generate_operationreceives only what a background start uses, andBackgroundModelsubclasses the genericBackgroundAction. Custom formatters importFormatter,FormatterConfigandFormatHandlerfromgenkit.formats. New:genkit.evaluator.Evaluator/BatchEvaluator, and fake models ingenkit.testing.Experimental APIs
Anything under an
expmodule can change in any release, and it stays experimental after 1.0 (#6549, #6571, #6649).AgentErroris gone: a failed turn returnsres.error(aFailure), and a call that produces no turn raisesGenkitError. A detached turn is cancelled withawait task.abort().