Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
398 changes: 394 additions & 4 deletions packages/genkit-fastapi/tests/agent_handler_test.py

Large diffs are not rendered by default.

31 changes: 17 additions & 14 deletions packages/genkit/src/genkit/_ai/_agents/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
render_prompt,
)
from genkit._core._action import Action, ActionKind, BidiAction, BidiFn, get_current_context
from genkit._core._error import ErrorReason, GenkitError
from genkit._core._error import ErrorReason, GenkitError, PublicError
from genkit._core._middleware import Middleware
from genkit._core._model import (
AgentInit,
Expand Down Expand Up @@ -261,7 +261,7 @@ async def bidi_fn(
except GenkitError as e:
return AgentOutput(
finish_reason=AgentFinishReason.FAILED,
error=to_error_details(e),
error=to_error_details(e, agent=name),
state=(init.state if store is None and init.state is not None else None),
)

Expand Down Expand Up @@ -311,9 +311,9 @@ async def snapshot_fn(req: GetSnapshotRequest) -> SessionSnapshot:
# an empty-but-successful read, so surface it as NOT_FOUND instead of a
# null the caller has to re-interpret.
target = sid or sess_id or 'unknown'
raise GenkitError(
status='NOT_FOUND',
message=f'Snapshot {target!r} not found for agent {name!r}.',
raise PublicError(
'NOT_FOUND',
f'Snapshot {target!r} not found for agent {name!r}.',
reason=ErrorReason.SNAPSHOT_NOT_FOUND,
)
return snap
Expand Down Expand Up @@ -507,32 +507,35 @@ def ref_suffix(ref: str | None) -> str:
continue
match = find(tr.name, tr.ref)
if match is None:
raise GenkitError(
status='INVALID_ARGUMENT',
message=(
raise PublicError(
'INVALID_ARGUMENT',
(
f"resume.restart references tool '{tr.name}'{ref_suffix(tr.ref)} "
'which was not found in session history.'
),
reason=ErrorReason.INVALID_RESUME,
)
if tool_input_key(tr.input) != tool_input_key(match.input):
raise GenkitError(
status='INVALID_ARGUMENT',
message=(
raise PublicError(
'INVALID_ARGUMENT',
(
f"resume.restart for tool '{tr.name}'{ref_suffix(tr.ref)} has modified inputs that do not "
'match the original tool request in session history. Restart inputs must exactly match the '
'interrupted tool request.'
),
reason=ErrorReason.INVALID_RESUME,
)

for respond_part in resume.respond or []:
resp = respond_part.tool_response
if resp is None:
continue
if find(resp.name, resp.ref) is None:
raise GenkitError(
status='INVALID_ARGUMENT',
message=(
raise PublicError(
'INVALID_ARGUMENT',
(
f"resume.respond references tool '{resp.name}'{ref_suffix(resp.ref)} "
'which was not found in session history.'
),
reason=ErrorReason.INVALID_RESUME,
)
84 changes: 66 additions & 18 deletions packages/genkit/src/genkit/_ai/_agents/_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@
from genkit._ai._agents._session_stores._util import session_id_of
from genkit._ai._agents._snapshot import walk_back_to_resumable
from genkit._ai._agents._types import ChunkTransform, StateTransform, TurnContext, TurnResult
from genkit._ai._generate import CallScope, generate_action
from genkit._ai._generate import (
CallScope,
generate_action,
log_dropped_failure,
mark_failure_logged,
)
from genkit._ai._json_patch import diff_json
from genkit._core._action import ActionRunContext, get_current_context
from genkit._core._channel import CloseableQueue, QueueShutDown
Expand All @@ -53,7 +58,11 @@
PublicError,
StatusName,
TaskGroupError,
attached_cause,
interrupt_escape_error,
is_logged_failure,
is_public_failure,
mark_public_failure,
)
from genkit._core._logger import get_logger
from genkit._core._model import (
Expand Down Expand Up @@ -105,8 +114,11 @@ def __init__(
get_parent_snapshot_id: Callable[[], str | None] | None = None,
on_begin_turn: Callable[[], Awaitable[None]] | None = None,
on_end_turn: Callable[[AgentFinishReason | None], Awaitable[str | None]] | None = None,
agent_name: str | None = None,
) -> None:
self.session = session
# Names the agent in the server-side log when a turn error is redacted.
self._agent_name = agent_name
self.turn_inputs = turn_inputs
self.store = store
self.get_parent_snapshot_id = get_parent_snapshot_id
Expand Down Expand Up @@ -220,7 +232,7 @@ async def body(span: SpanContext, turn_input: AgentInput = inp, ctx: TurnContext
else:
raise
self.last_turn_finish_reason = AgentFinishReason.FAILED
self.last_turn_error = to_error_details(turn_error)
self.last_turn_error = to_error_details(turn_error, agent=self._agent_name)

if self.on_end_turn is not None:
await self.on_end_turn(AgentFinishReason.FAILED)
Expand Down Expand Up @@ -317,9 +329,9 @@ class AgentInitError(PublicError):

Covers calling an agent with an init that does not match its state-management
mode (e.g. sending ``state`` to a server-managed agent). Recoverable pre-turn
problems (missing snapshot, non-resumable snapshot, invalid custom state)
stay as plain ``GenkitError`` so the caller can absorb them into
``finish_reason='failed'``.
problems (missing or non-resumable snapshot, invalid custom state) are not
subclasses of ``AgentInitError``, so ``define_custom_agent`` absorbs them
into ``finish_reason='failed'``.

It is a ``PublicError``: the message names only the init fields and ids the
caller sent, so a served agent returns its status, message, and
Expand All @@ -335,7 +347,7 @@ def __init__(self, *, status: StatusName, message: str, reason: ErrorReason | No
message: Caller-facing sentence; must not include server-side data.
reason: Stable reason, sent on the wire as ``details.reason``.
"""
super().__init__(status, message, details={'reason': reason.value} if reason is not None else None)
super().__init__(status, message, reason=reason)


def seeded_init_fields(state: SessionState) -> str:
Expand Down Expand Up @@ -406,8 +418,9 @@ async def load_session(
client is validated against it before the session is built.

State-management mismatches raise ``AgentInitError`` (must propagate).
Missing/non-resumable snapshots and invalid custom state raise plain
``GenkitError`` for the caller to turn into ``finish_reason='failed'``.
Missing/non-resumable snapshots raise ``PublicError`` and invalid custom
state raises ``GenkitError``; the agent boundary turns both into
``finish_reason='failed'``.
"""
name = agent_name or 'agent'

Expand All @@ -418,9 +431,9 @@ async def load_session(
if store is not None and init.snapshot_id:
snap = await store.get_snapshot(snapshot_id=init.snapshot_id, context=ctx)
if snap is None:
raise GenkitError(
status='NOT_FOUND',
message=f'Snapshot {init.snapshot_id!r} not found',
raise PublicError(
'NOT_FOUND',
f'Snapshot {init.snapshot_id!r} not found',
reason=ErrorReason.SNAPSHOT_NOT_FOUND,
)
# When init carries both ids, the snapshot id picks the row and the
Expand All @@ -438,9 +451,9 @@ async def load_session(
# A failed/aborted/pending snapshot is kept for inspection but isn't a
# valid place to continue a conversation from.
if snap.status != SnapshotStatus.COMPLETED:
raise GenkitError(
status='INVALID_ARGUMENT',
message=(
raise PublicError(
'INVALID_ARGUMENT',
(
f'Snapshot {init.snapshot_id!r} is not resumable '
f'(status: {snap.status.value if snap.status else "unknown"}). '
"Only 'completed' snapshots can be resumed."
Expand Down Expand Up @@ -523,6 +536,7 @@ def __init__(
get_parent_snapshot_id=lambda: self.last_snapshot.snapshot_id if self.last_snapshot else None,
on_begin_turn=self.reset_custom_patch_turn,
on_end_turn=self.emit_turn_end,
agent_name=name,
)

session.on_custom_changed(self.emit_custom_patch)
Expand Down Expand Up @@ -846,7 +860,7 @@ def finalize(existing: SessionSnapshot | None) -> SessionSnapshot | None:
parent_id=pending_snap.parent_id or '',
status=SnapshotStatus.FAILED if is_failed else SnapshotStatus.COMPLETED,
state=state,
error=(to_error_details(fn_err) if fn_err else turn_err),
error=(to_error_details(fn_err, agent=self.name) if fn_err else turn_err),
finish_reason=finish_reason,
created_at=existing.created_at if existing else now,
)
Expand Down Expand Up @@ -1151,11 +1165,20 @@ def on_chunk(chunk: ModelResponseChunk) -> None:

# Bad JSON is not a dead turn — generate already kept the model text.
if response.error is not None and response.error.reason is not ErrorReason.INVALID_OUTPUT:
raise GenkitError(
if is_public_failure(response.error):
raise PublicError(
response.error.status or 'INTERNAL',
response.error.message,
details=response.error.details,
)
err = GenkitError(
message=response.error.message,
status=response.error.status,
details=response.error.details,
)
if is_logged_failure(response.error):
mark_failure_logged(err)
raise err

# Return the turn result wrapping the model finish reason
finish_reason = to_agent_finish_reason(response.finish_reason) if response.finish_reason is not None else None
Expand All @@ -1167,7 +1190,7 @@ def on_chunk(chunk: ModelResponseChunk) -> None:
# ---------------------------------------------------------------------------


def to_error_details(exc: BaseException) -> Failure:
def to_error_details(exc: BaseException, *, agent: str | None = None) -> Failure:
"""A turn failure as data, with the status classified like Go's ``status.Classified``.

Classifies the top-level exception; Go also walks the wrapped chain
Expand All @@ -1176,12 +1199,31 @@ def to_error_details(exc: BaseException) -> Failure:
Only a GenkitError names its own status. A third-party ``.status``
attribute (aiohttp's ``status=429``) isn't a Genkit status, so it never
leaks through.

The Failure keeps the exception's own text, like JS ``toErrorDetails``
and Go ``convertKeepText``, so in-process callers, the session store and
the Dev UI see what went wrong. A served agent's HTTP caller doesn't:
outside ``GENKIT_ENV=dev``, ``genkit.web`` swaps in a generic message
unless the turn raised a ``PublicError`` (see ``client_safe_failure``). Every non-``PublicError``
failure (except an escaped ``Interrupt``) is logged here unless
``generate`` already logged it, so the server log has what the wire
redacts.

Args:
exc: The exception that ended the turn or invocation.
agent: Agent name for the server-side log line, when known.
"""
status: StatusName
details: dict[str, Any] | None = None
if isinstance(exc, GenkitError):
status = exc.status
message = exc.message
cause = attached_cause(exc)
# interrupt_escape_error's sentence isn't foreign text: the attached
# Interrupt is tool metadata. A prompt agent stamps mark_failure_logged
# on the GenkitError it re-raises when generate already logged it.
escaped_interrupt = cause is not None and interrupt_escape_error(cause) is not None
hides_cause = not isinstance(exc, PublicError) and not escaped_interrupt
if isinstance(exc.details, Mapping) and exc.details:
details = dict(cast(Mapping[str, Any], exc.details))
else:
Expand All @@ -1193,7 +1235,13 @@ def to_error_details(exc: BaseException) -> Failure:
else:
status = 'INTERNAL'
message = str(exc) or 'Internal failure'
return Failure(status=status, message=message, details=details)
hides_cause = True
if hides_cause:
log_dropped_failure(exc, agent=agent, redacted=True)
failure = Failure(status=status, message=message, details=details)
if isinstance(exc, PublicError):
mark_public_failure(failure)
return failure


def to_agent_finish_reason(fr: FinishReason) -> AgentFinishReason:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,26 @@
session_id_of,
subscribe,
)
from genkit._core._error import Failure
from genkit._core._model import SessionSnapshot


def _copy_snapshot(snap: SessionSnapshot) -> SessionSnapshot:
"""Deep-copy ``snap`` without in-process ``Failure`` provenance, matching JSON stores."""
copied = snap.model_copy(deep=True)
if copied.error is not None:
copied = copied.model_copy(
update={
'error': Failure(
status=copied.error.status,
message=copied.error.message,
details=copied.error.details,
)
}
)
return copied


class InMemorySessionStore(SessionStoreLock, SessionStore[StateT], SnapshotSubscriber, Generic[StateT]):
"""In-memory snapshot store. State is lost when the process exits."""

Expand Down Expand Up @@ -69,12 +86,12 @@ async def get_snapshot(
async with self.lock:
if snapshot_id is not None:
snap = self.snapshots.get(snapshot_id)
return snap.model_copy(deep=True) if snap is not None else None
return _copy_snapshot(snap) if snap is not None else None

assert session_id is not None
owned = [snap for snap in self.snapshots.values() if session_id_of(snap) == session_id]
leaf = select_leaf(snapshots=owned, session_id=session_id, reject_ambiguous=self.reject_ambiguous)
return leaf.model_copy(deep=True) if leaf is not None else None
return _copy_snapshot(leaf) if leaf is not None else None

async def save_snapshot(
self,
Expand All @@ -87,10 +104,14 @@ async def save_snapshot(
_ = context
async with self.lock:
existing = self.snapshots.get(snapshot_id)
next_snapshot = apply_save(existing=existing, snapshot_id=snapshot_id, fn=fn)
next_snapshot = apply_save(
existing=_copy_snapshot(existing) if existing is not None else None,
snapshot_id=snapshot_id,
fn=fn,
)
if next_snapshot is None:
return None
self.snapshots[next_snapshot.snapshot_id] = next_snapshot.model_copy(deep=True)
self.snapshots[next_snapshot.snapshot_id] = _copy_snapshot(next_snapshot)
notify(subs=self.subs, snapshot_id=next_snapshot.snapshot_id, status=next_snapshot.status)
return next_snapshot

Expand Down
18 changes: 9 additions & 9 deletions packages/genkit/src/genkit/_ai/_agents/_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from genkit._ai._agents._session import SessionStore
from genkit._ai._agents._types import StateTransform
from genkit._core._action import get_current_context
from genkit._core._error import ErrorReason, GenkitError
from genkit._core._error import ErrorReason, GenkitError, PublicError
from genkit._core._model import SessionSnapshot
from genkit._core._typing import SnapshotStatus

Expand Down Expand Up @@ -71,21 +71,21 @@ def parse_snapshot_lookup_kw(
) -> tuple[str | None, str | None]:
"""Require exactly one of ``snapshot_id`` or ``session_id``.

A bad selector is a caller mistake, so it raises ``INVALID_ARGUMENT`` — over a
transport that surfaces as a 400, not a 500 the way a bare ``ValueError`` would.
A bad selector is a caller mistake, so it raises ``PublicError``
``INVALID_ARGUMENT`` — over a transport that surfaces as a 400, not a 500.
Whitespace-only ids count as empty: they are not usable as document keys.
"""
for name, value in (('snapshot_id', snapshot_id), ('session_id', session_id)):
if value is not None and not value.strip():
raise GenkitError(
status='INVALID_ARGUMENT',
message=f'{name} must not be empty or whitespace-only.',
raise PublicError(
'INVALID_ARGUMENT',
f'{name} must not be empty or whitespace-only.',
reason=(ErrorReason.INVALID_SNAPSHOT_ID if name == 'snapshot_id' else ErrorReason.SESSION_ID_REQUIRED),
)
if bool(snapshot_id) == bool(session_id):
raise GenkitError(
status='INVALID_ARGUMENT',
message=(
raise PublicError(
'INVALID_ARGUMENT',
(
"get_snapshot requires exactly one of 'snapshot_id' or 'session_id' "
f'(got snapshot_id={snapshot_id!r}, session_id={session_id!r}).'
),
Expand Down
Loading
Loading