Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
1caceff
fix(py): export missing public types, require input on typed actions,…
huangjeff5 Nov 12, 2026
fec5037
fix(py/exp): type SessionSnapshot by state_schema and export missing …
huangjeff5 Nov 12, 2026
1363fb4
fix(py): keep ActionResponse out of genkit.plugin_api
huangjeff5 Nov 12, 2026
0df3bdc
docs(py): clarify why ref config TypeVars default to Any
huangjeff5 Nov 12, 2026
18cff5d
chore(py): remove unused CheckOpFn and CancelOpFn aliases
huangjeff5 Nov 12, 2026
43c4f81
Merge remote-tracking branch 'origin/main' into HEAD
huangjeff5 Nov 16, 2026
0d36862
chore(py): unquote ActionContext annotation after merge
huangjeff5 Nov 16, 2026
3bdcf41
fix(py): drop Tool.__new__ overloads so copy and subclassing work again
huangjeff5 Nov 16, 2026
047575f
fix(py): keep ModelFn and McpServerEntry out of the public exports
huangjeff5 Nov 16, 2026
74676ca
fix(py): restore typed GenerationUsage.from_messages signature
huangjeff5 Nov 16, 2026
fd66387
fix(py): keep McpServerEntry exported for mcp_servers built in a vari…
huangjeff5 Nov 16, 2026
756770e
fix(py): let flows and tools with a defaulted input run with no input
huangjeff5 Nov 16, 2026
2d3806a
fix(py): make action input contravariant
huangjeff5 Nov 16, 2026
c31cc69
fix(py)!: tools treat an explicit None as a value, like flows
huangjeff5 Nov 16, 2026
848b91d
fix(py)!: type defaulted flows and tools as DefaultedFlow / Defaulted…
huangjeff5 Nov 16, 2026
62ac92f
fix(py): type a defaulted input followed by a context
huangjeff5 Nov 16, 2026
fbcbdee
fix(py): add a catch-all handler overload and pin every shape in cont…
huangjeff5 Nov 16, 2026
d4f9c0c
fix(py): reject keyword-only handler params and drop the catch-all ov…
huangjeff5 Nov 16, 2026
54115f8
test(py): separate an omitted input from an explicit None in the shap…
huangjeff5 Nov 16, 2026
ec7d06d
fix(py): accept a ref picked between providers when no config is passed
huangjeff5 Nov 16, 2026
d784714
test(py): note the ty overload-order bug behind the define_prompt pin
huangjeff5 Nov 16, 2026
0300410
Merge remote-tracking branch 'origin/fix/py-1.0-pr2-static-typing' in…
huangjeff5 Nov 16, 2026
7dd221f
Merge remote-tracking branch 'origin/main' into HEAD
huangjeff5 Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 35 additions & 42 deletions packages/genkit/src/genkit/_ai/_agents/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from dataclasses import dataclass, field
from typing import Any, Generic, Protocol, TypeVar, cast

from pydantic import BaseModel, ValidationError, field_validator
from pydantic import BaseModel, ValidationError
from typing_extensions import TypeVar as TypeVarExt

from genkit._ai._agents._runtime import AgentInitError, seeded_init_fields
Expand All @@ -51,11 +51,10 @@
Message,
Part,
Resume,
SessionSnapshot as SessionSnapshotVeneer,
SessionState as SessionStateVeneer,
SessionSnapshot,
SessionState,
as_message,
as_part,
as_session_state,
resume_options_to_resume,
)
from genkit._core._typing import (
Expand Down Expand Up @@ -98,25 +97,25 @@ class _TurnCheckpoint:
resume_snapshot_id: str | None


class SessionState(SessionStateVeneer, Generic[StateT]):
"""Session state generic over custom state."""
def _typed_snapshot(
raw: SessionSnapshot | None,
state_schema: type[StateT] | None,
) -> SessionSnapshot[StateT] | None:
"""Re-read a stored snapshot with ``state.custom`` validated as ``state_schema``.

custom: StateT | None = None


class SessionSnapshot(SessionSnapshotVeneer, Generic[StateT]):
"""Session snapshot generic over custom state."""

# Narrows the wire model's plain SessionState to the typed one so snap.state.custom
# reads as the declared model; the runtime shape is identical (same JSON fields).
state: SessionState[StateT] | None = None # pyright: ignore[reportIncompatibleVariableOverride] # pyrefly: ignore[bad-override]

@field_validator('state', mode='before')
@classmethod
def _wrap_state(cls, v: object) -> object:
if v is None:
return v
return SessionState.model_validate(as_session_state(v).model_dump(mode='json', by_alias=True))
A settled snapshot whose state doesn't fit raises; a pending one keeps the
raw value, since the turn may still be writing it.
"""
if raw is None:
return None
snap = SessionSnapshot[StateT].model_validate_json(raw.model_dump_json(by_alias=True))
if snap.state is not None and snap.state.custom is not None and state_schema is not None:
try:
snap.state.custom = state_schema.model_validate(snap.state.custom)
except Exception:
if snap.status is not None and snap.status in TERMINAL_SNAPSHOT_STATUSES:
raise
return snap


# ===========================================================================
Expand Down Expand Up @@ -158,7 +157,7 @@ async def get_snapshot(
*,
snapshot_id: str | None = None,
session_id: str | None = None,
) -> SessionSnapshotVeneer | None:
) -> SessionSnapshot | None:
"""Retrieves a session snapshot from the server store."""
...

Expand Down Expand Up @@ -568,7 +567,7 @@ async def get_snapshot(
*,
snapshot_id: str | None = None,
session_id: str | None = None,
) -> SessionSnapshotVeneer | None:
) -> SessionSnapshot[StateT] | None:
"""Reads a stored snapshot without starting a session.

Pass exactly one of ``snapshot_id`` or ``session_id``. A session
Expand Down Expand Up @@ -678,15 +677,17 @@ async def get_snapshot(
*,
snapshot_id: str | None = None,
session_id: str | None = None,
) -> SessionSnapshotVeneer | None:
) -> SessionSnapshot[StateT] | None:
"""Reads a stored snapshot without starting a session.

Pass exactly one of ``snapshot_id`` or ``session_id``. A session
lookup returns the newest row even when that turn failed or was
aborted. ``chat(session_id=)`` is how you continue from the last
good turn.
good turn. With ``state_schema``, ``state.custom`` comes back as
that model.
"""
return await self._transport.get_snapshot(snapshot_id=snapshot_id, session_id=session_id)
raw = await self._transport.get_snapshot(snapshot_id=snapshot_id, session_id=session_id)
return _typed_snapshot(raw, self._state_schema)

async def abort(self, snapshot_id: str) -> SnapshotStatus | None:
"""Aborts a running snapshot on the server.
Expand Down Expand Up @@ -1240,11 +1241,12 @@ def resume_stream(
wire = resume_options_to_resume(resume_respond=respond, resume_restart=restart, resume_metadata=metadata)
return self.send_stream(AgentInput(resume=wire or Resume(metadata=metadata)))

async def get_snapshot(self) -> SessionSnapshotVeneer | None:
async def get_snapshot(self) -> SessionSnapshot[StateT] | None:
"""Reads the current snapshot from the server store, if store-backed."""
if not self._snapshot_id:
return None
return await self._transport.get_snapshot(snapshot_id=self._snapshot_id)
raw = await self._transport.get_snapshot(snapshot_id=self._snapshot_id)
return _typed_snapshot(raw, self._state_schema)

async def detach(self, input: str | AgentInput) -> DetachedTask[StateT]: # noqa: A002
"""Runs a turn in the background on the server and returns a poll handle."""
Expand Down Expand Up @@ -1315,13 +1317,13 @@ async def abort(self) -> SnapshotStatus | None:
# Internal (transport / runtime wiring)
# ------------------------------------------------------------------

def _load_from_snapshot(self, snapshot: SessionSnapshotVeneer) -> None:
def _load_from_snapshot(self, snapshot: SessionSnapshot) -> None:
self._snapshot_id = snapshot.snapshot_id
self._resume_snapshot_id = snapshot.snapshot_id
if snapshot.state is not None:
self._set_state(snapshot.state)

def _set_state(self, state: SessionStateVeneer) -> None:
def _set_state(self, state: SessionState) -> None:
snapshot = state.model_copy(deep=True)
self._session_id = snapshot.session_id
self._messages = list(snapshot.messages or [])
Expand Down Expand Up @@ -1570,17 +1572,8 @@ def __init__(
self._transport = transport
self._state_schema = state_schema

def _parse_snapshot(self, raw: SessionSnapshotVeneer | None) -> SessionSnapshot[StateT] | None:
if raw is None:
return None
snap = SessionSnapshot[StateT].model_validate_json(raw.model_dump_json(by_alias=True))
if snap.state is not None and snap.state.custom is not None and self._state_schema is not None:
try:
snap.state.custom = self._state_schema.model_validate(snap.state.custom)
except Exception:
if snap.status is not None and snap.status in TERMINAL_SNAPSHOT_STATUSES:
raise
return snap
def _parse_snapshot(self, raw: SessionSnapshot | None) -> SessionSnapshot[StateT] | None:
return _typed_snapshot(raw, self._state_schema)

async def poll(self, interval: float = 1.0) -> AsyncIterator[SessionSnapshot[StateT]]:
"""Yields the task's snapshot every ``interval`` seconds until it settles.
Expand Down
24 changes: 18 additions & 6 deletions packages/genkit/src/genkit/_core/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1419,12 +1419,21 @@ def count_parts(parts: Sequence[Part]) -> tuple[int, int, int, int]:
}


class SessionState(GenkitModel):
"""Session state whose conversation uses Message and Artifact."""
# Custom session state type. Defaults to Any so a bare SessionState /
# SessionSnapshot is the untyped wire shape.
SessionStateT = TypeVar('SessionStateT', default=Any)


class SessionState(GenkitModel, Generic[SessionStateT]):
"""Session state whose conversation uses Message and Artifact.

``SessionState[CartState]`` validates ``custom`` as ``CartState``; a bare
``SessionState`` leaves it as the stored JSON value.
"""

session_id: str | None = None
messages: list[Message] | None = None
custom: Any | None = Field(default=None)
custom: SessionStateT | None = Field(default=None)
artifacts: list[Artifact] | None = None
usage: GenerationUsage | None = None

Expand Down Expand Up @@ -1455,8 +1464,11 @@ def as_session_state(value: object) -> SessionState:
return SessionState.model_validate(value)


class SessionSnapshot(GenkitModel):
"""Snapshot whose state uses the public SessionState type."""
class SessionSnapshot(GenkitModel, Generic[SessionStateT]):
"""Snapshot whose state uses the public SessionState type.

``SessionSnapshot[CartState]`` types ``state.custom`` as ``CartState``.
"""

snapshot_id: str
session_id: str | None = None
Expand All @@ -1467,7 +1479,7 @@ class SessionSnapshot(GenkitModel):
status: SnapshotStatus | None = None
finish_reason: AgentFinishReason | None = None
error: Failure | None = None
state: SessionState | None = None
state: SessionState[SessionStateT] | None = None

@field_validator('state', mode='before')
@classmethod
Expand Down
5 changes: 2 additions & 3 deletions packages/genkit/src/genkit/exp/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,17 @@
define_prompt_agent,
)
from genkit._ai._agents._runtime import AgentFn
from genkit._ai._agents._session import SessionStore, StateT, get_current_session
from genkit._ai._agents._session import Session, SessionStore, StateT, get_current_session
from genkit._ai._agents._types import ChunkTransform, StateTransform
from genkit._ai._aio import Genkit as StableGenkit
from genkit._core._action import Action, ActionKind
from genkit._core._error import ErrorReason, GenkitError
from genkit._core._middleware import Middleware
from genkit._core._model import ModelConfigDict, ModelRef, ModelRefConfigT, Part
from genkit._core._protocols import SessionLike
from genkit._core._tool import Tool


def current_session() -> SessionLike | None:
def current_session() -> Session[Any] | None:
"""Return the active agent session, or None if not inside a session."""
return get_current_session()

Expand Down
4 changes: 4 additions & 0 deletions packages/genkit/src/genkit/exp/agent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
apply_save,
iterate_statuses,
require_one_selector,
select_leaf,
session_id_of,
)
from genkit._ai._agents._transports._http import HttpAgentTransport, remote_agent
Expand All @@ -68,6 +69,7 @@
TurnResult,
)
from genkit._ai._json_patch import apply_json_patch, diff_json
from genkit._core._action import BidiConnection
from genkit._core._model import (
AgentInit,
AgentInput,
Expand Down Expand Up @@ -99,6 +101,7 @@
'AgentResponse',
'DetachedTask',
'AgentTransport',
'BidiConnection',
'HttpAgentTransport',
'remote_agent',
# Agent function protocol
Expand All @@ -121,6 +124,7 @@
'apply_save',
'iterate_statuses',
'require_one_selector',
'select_leaf',
'session_id_of',
# JSON Patch helpers
'apply_json_patch',
Expand Down
7 changes: 5 additions & 2 deletions packages/genkit/src/genkit/web/_sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import json
import logging
from collections.abc import AsyncGenerator, AsyncIterator, Awaitable
from typing import Protocol
from typing import Any, Protocol

from pydantic_core import to_jsonable_python

Expand Down Expand Up @@ -71,7 +71,10 @@ def _frame_value(obj: object) -> object:
# A failed turn is a 200 with the failure as data, so error_body never
# sees it. Apply the same rule here: only a PublicError's text leaves.
if isinstance(obj, (AgentOutput, SessionSnapshot)) and obj.error is not None:
obj = obj.model_copy(update={'error': client_safe_failure(obj.error)})
# Typed as Any-valued: ty narrows to Top[SessionSnapshot[Any]], whose
# model_copy(update=) would otherwise only accept Mapping[str, Never].
update: dict[str, Any] = {'error': client_safe_failure(obj.error)}
obj = obj.model_copy(update=update)
# NaN/Infinity go out as null, the same as tool outputs and model
# messages (mode='json'), instead of crashing allow_nan=False with a 500.
return to_jsonable_python(obj, by_alias=True, exclude_none=True, inf_nan_mode='null')
Expand Down
36 changes: 36 additions & 0 deletions packages/genkit/tests/genkit/ai/agent_snapshot_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from datetime import datetime, timedelta, timezone

import pytest
from pydantic import BaseModel

from genkit import Genkit, Part
from genkit._ai._agents._base import define_custom_agent
Expand Down Expand Up @@ -365,3 +366,38 @@ async def handle_turn(inp: AgentInput, _: TurnContext) -> TurnResult | None:
out = await resumed.send('still there?')
assert out.finish_reason == AgentFinishReason.STOP
assert resumed.snapshot_id not in (None, task.snapshot_id)


class _CartState(BaseModel):
items: list[str]


@pytest.mark.asyncio
async def test_get_snapshot_hydrates_state_schema() -> None:
"""With state_schema set, agent.get_snapshot and chat.get_snapshot validate state.custom."""
ai = Genkit()
store = InMemorySessionStore()

async def fn(session_runner: SessionRunner[_CartState], _: AgentContext) -> AgentResult:
async def handle_turn(_inp: AgentInput, _tc: TurnContext) -> TurnResult | None:
await session_runner.update_custom(lambda _: _CartState(items=['tartine']))
await session_runner.add_messages([Message(role='model', content=[Part.from_text('added')])])
return TurnResult(finish_reason=AgentFinishReason.STOP)

await session_runner.run(handle_turn)
return await session_runner.result()

agent = define_custom_agent(ai, 'cartAgent', fn, store=store, state_schema=_CartState)
chat = agent.chat()
await chat.send('add tartine')
assert chat.session_id is not None

from_chat: SessionSnapshot[_CartState] | None = await chat.get_snapshot()
assert from_chat is not None and from_chat.state is not None
assert isinstance(from_chat.state.custom, _CartState)
assert from_chat.state.custom.items == ['tartine']

from_client: SessionSnapshot[_CartState] | None = await agent.get_snapshot(session_id=chat.session_id)
assert from_client is not None and from_client.state is not None
assert isinstance(from_client.state.custom, _CartState)
assert from_client.state.custom.items == ['tartine']
14 changes: 14 additions & 0 deletions packages/genkit/tests/genkit/core/public_types_runtime_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,20 @@ def test_generation_usage_from_messages_counts_characters() -> None:
assert usage.output_characters == len('Booked')


@pytest.mark.parametrize(
('module', 'names'),
[
('genkit.exp.agent', ['BidiConnection', 'DetachedTask', 'AgentInitError', 'select_leaf']),
],
)
def test_signature_types_are_exported(module: str, names: list[str]) -> None:
"""Types that appear in public signatures import from their canonical module."""
mod = importlib.import_module(module)
for name in names:
assert name in mod.__all__, f'{module}.{name}'
assert hasattr(mod, name)


@pytest.mark.parametrize(
('module', 'names'),
[
Expand Down
Loading