Skip to content

fix(py): static typing overloads and public signature exports - #7137

Closed
huangjeff5 wants to merge 10 commits into
mainfrom
fix/py-1.0-pr2-static-typing
Closed

huangjeff5 wants to merge 10 commits into
mainfrom
fix/py-1.0-pr2-static-typing

Conversation

@huangjeff5

Copy link
Copy Markdown
Contributor

Fixes static typing overloads across core and satellite packages for clean pyright, pyrefly, and ty checks.

Main Changes

  • Exported public types: Exported types referenced in public API signatures from genkit namespace.
  • Parameterized output_schema overloads: Cleaned generate and generate_stream overload signatures so pyright infers exact return types.
  • Unified agent session types: Unified SessionSnapshot and SessionState generic bounds.

resolve_json_schema_refs inlined every local $ref with no visited set, so
output_format='array' or 'jsonl' on a self-referencing item model raised
RecursionError. Refs already being expanded on the current path are now left
in place; the root $defs stay in the output so they still resolve.

The array format's schema error also named the 'items' format instead of
'array'.
…oads

The untyped overloads annotated output_schema as bare `type | dict | None`.
pyright strict reads bare dict as dict[Unknown, Unknown] and flags every
ai.generate()/generate_stream() call with reportUnknownMemberType. They also
left out `str`, which names a registered schema and works at runtime.

Now `type[Any] | dict[str, Any] | str | None`.
ModelResponseChunk.output used @cached_property on a generic pydantic
model. ty loses OutputT through that descriptor and types every
chunk.output as None. It's now a plain @Property over a private cache, so
it still parses once per chunk.

Tool(fn) specialized only through self-typed __init__ overloads, which ty
ignores, so it inferred Tool[Any, Any, Any]. Matching __new__ overloads give
ty the same answer pyright, mypy and pyrefly already get.
… input

@ai.flow, ai.flow(...) and Flow(...) ended with a Callable[..., Awaitable[T]]
overload. Under mypy --strict and ty, any flow with an Any-bearing parameter
(dict[str, Any], Any) matched it ambiguously and collapsed to
Flow[Any, Any, Any]. It also accepted 3-arg functions that raise TypeError at
definition. _ToolDecorator never had it; the flow overloads now match.

A context-only tool, (ctx: ToolContext[C]) -> T, now types as
Tool[None, T, C] like a context-only flow, instead of Tool[Any, T, C].
Action.__call__/run/stream declared `input: InputT | None = NO_INPUT`, so
`await create_invoice()` and `create_invoice(None)` on a
Flow[OrderReq, Invoice] passed every checker and failed at runtime with
INVALID_ARGUMENT. Hover also showed the private NO_INPUT default.

They now overload on self: an Action[None, ...] (zero-input flow or tool,
or an untyped Action[Any, ...]) takes an optional input; every other action
requires one. Prompt.__call__/stream split the same way: a prompt with
input_schema takes that input or a dict of template variables. Prompt
config= also lists ModelConfigDict for dict-literal autocomplete. Runtime
defaults are unchanged.
ModelRefConfigT and EmbedderRefConfigT were covariant. Given
generate(model=ModelRef[T], config=T), checkers widened T to BaseModel, so
config=VeoConfig(...) or any other model class passed on a
ModelRef[GeminiConfig]. Invariant T is solved from the ref.

"Any ref" annotations move from ModelRef[BaseModel] to ModelRef[Any] (incl.
ModelArg), and bare EmbedderRef now defaults to EmbedderRef[Any], so typed
refs still fit them. Dict configs keep the Mapping fallback.
genkit.exp.agent exported the non-generic core SessionSnapshot and
SessionState, while DetachedTask.wait()/poll() returned a private generic
subclass from _client. `SessionSnapshot[CartState]` failed every checker
and raised TypeError at runtime, and AgentClient.get_snapshot() dropped
StateT.

The core classes are now generic over the custom state (default Any, so a
bare SessionSnapshot is the wire shape) and the private subclasses are gone.
AgentClient.get_snapshot() and AgentChat.get_snapshot() return
SessionSnapshot[StateT] with state.custom validated by state_schema, the
same way DetachedTask already did.

Also exports BidiConnection (Agent.stream_bidi's return type) and
select_leaf, and types genkit.exp.current_session() as the public
Session[Any] instead of the private SessionLike protocol.
…able

typing.get_type_hints() raised on three public signatures, which breaks
FastAPI/Pydantic introspection:

- BackgroundAction.__init__: `check: CheckOpFn[OutT]` subscripts an alias
  whose Operation[OutT] is a concrete pydantic class at runtime. Spelled
  out as a Callable.
- BackgroundAction.lookup / BackgroundModel.lookup: `registry: Registry`
  named a TYPE_CHECKING-only import. _registry imports _background at
  runtime, so it binds the name back once Registry is defined.
- GenerationUsage.from_messages: annotated with _model.Message and Sequence,
  neither importable in _typing at runtime. It now takes the wire
  MessageData (Message's base) and converts with as_message. The generator
  emits the change; _typing.py is regenerated.
Strict consumers hit reportPrivateImportUsage, or had no import path at
all, when annotating values that public APIs return or accept:

- genkit: ActionResponse (Flow.run/Tool.run), ModelConfig, ModelConfigDict
  (generate/prompt config=), ModelStreamingCallback (on_chunk=),
  StoppableStream (.stream), Resource (Part.resource), ToolRequest,
  ToolResponse (Part fields), StatusName (GenkitError.status).
- genkit.middleware: MiddlewareRef (Prompt use=).
- genkit.model: ModelFn (define_model fn=).
- genkit.plugin_api: ActionMetadata, ActionResponse, ActionRunContext,
  GenkitModel, custom_options_schema.
- genkit_mcp: McpServerEntry (define_mcp_host/McpHost).
- genkit_openai: PromptCacheRetention, ReasoningEffort, ServiceTier,
  Verbosity (OpenAIConfig fields).
content was `list[str] | list[Document]`, so a tuple, a Sequence[Document]
from a retriever, or a mixed list failed type checking even though the body
only iterates. It's now `Sequence[str | Document]`. A bare str is also a
Sequence[str] to the checker, so embed_many raises TypeError for one instead
of embedding each character.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors and enhances the Python SDK's type safety, public exports, and runtime type resolution. Key changes include making SessionState and SessionSnapshot generic over custom state types, adding overloads to Prompt and Action call/stream methods to properly handle None inputs, and ensuring that public annotations resolve correctly at runtime with typing.get_type_hints. Additionally, it prevents infinite recursion in JSON schema reference resolution for self-referencing models and adds safety checks to embed_many to reject bare strings. Feedback on these changes suggests optimizing the _typed_snapshot helper by using model_copy(deep=True) instead of a computationally expensive JSON dump and parse cycle for deep copying validated snapshots.

"""
if raw is None:
return None
snap = SessionSnapshot[StateT].model_validate_json(raw.model_dump_json(by_alias=True))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Dumping the entire snapshot to JSON and parsing it back with model_validate_json is computationally expensive, especially for large session histories. Since raw is already a validated SessionSnapshot instance, you can use model_copy(deep=True) to perform a deep copy much more efficiently.

Suggested change
snap = SessionSnapshot[StateT].model_validate_json(raw.model_dump_json(by_alias=True))
snap = cast(SessionSnapshot[StateT], raw.model_copy(deep=True))

@huangjeff5

Copy link
Copy Markdown
Contributor Author

Closing: migrated to standalone repository genkit-ai/genkit-python (PR #46): genkit-ai/genkit-python#46

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant