diff --git a/packages/genkit/src/genkit/_ai/_agents/_client.py b/packages/genkit/src/genkit/_ai/_agents/_client.py index 39f89a9e0..4c0d7857a 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_client.py +++ b/packages/genkit/src/genkit/_ai/_agents/_client.py @@ -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 @@ -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 ( @@ -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 # =========================================================================== @@ -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.""" ... @@ -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 @@ -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. @@ -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.""" @@ -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 []) @@ -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. diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index 477b7fd0b..99984ce74 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -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 @@ -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 @@ -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 diff --git a/packages/genkit/src/genkit/exp/_api.py b/packages/genkit/src/genkit/exp/_api.py index e689039ef..c7f508bcd 100644 --- a/packages/genkit/src/genkit/exp/_api.py +++ b/packages/genkit/src/genkit/exp/_api.py @@ -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() diff --git a/packages/genkit/src/genkit/exp/agent/__init__.py b/packages/genkit/src/genkit/exp/agent/__init__.py index fc82acc45..b7ec07a19 100644 --- a/packages/genkit/src/genkit/exp/agent/__init__.py +++ b/packages/genkit/src/genkit/exp/agent/__init__.py @@ -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 @@ -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, @@ -99,6 +101,7 @@ 'AgentResponse', 'DetachedTask', 'AgentTransport', + 'BidiConnection', 'HttpAgentTransport', 'remote_agent', # Agent function protocol @@ -121,6 +124,7 @@ 'apply_save', 'iterate_statuses', 'require_one_selector', + 'select_leaf', 'session_id_of', # JSON Patch helpers 'apply_json_patch', diff --git a/packages/genkit/src/genkit/web/_sse.py b/packages/genkit/src/genkit/web/_sse.py index b8dc01003..9ad875803 100644 --- a/packages/genkit/src/genkit/web/_sse.py +++ b/packages/genkit/src/genkit/web/_sse.py @@ -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 @@ -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') diff --git a/packages/genkit/tests/genkit/ai/agent_snapshot_test.py b/packages/genkit/tests/genkit/ai/agent_snapshot_test.py index 48f6cd902..9baf8d841 100644 --- a/packages/genkit/tests/genkit/ai/agent_snapshot_test.py +++ b/packages/genkit/tests/genkit/ai/agent_snapshot_test.py @@ -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 @@ -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'] diff --git a/packages/genkit/tests/genkit/core/public_types_runtime_test.py b/packages/genkit/tests/genkit/core/public_types_runtime_test.py index 6ceffd996..57fb8b283 100644 --- a/packages/genkit/tests/genkit/core/public_types_runtime_test.py +++ b/packages/genkit/tests/genkit/core/public_types_runtime_test.py @@ -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'), [