diff --git a/docs/migrating-from-0.12.md b/docs/migrating-from-0.12.md index 4507cc64f..ac953dd2d 100644 --- a/docs/migrating-from-0.12.md +++ b/docs/migrating-from-0.12.md @@ -383,11 +383,11 @@ ai = Genkit(plugins=[OpenAI(api_key=os.environ['OPENAI_API_KEY'])]) await ai.generate(model=m, prompt=p, context={'secrets': {'api_key': user_key}}) ``` -Vertex AI Model Garden authenticates with ADC and rejects a per-request key. `ai.embed()` takes no `context`, so embedders always use the plugin's key. +Vertex AI Model Garden authenticates with ADC and rejects a per-request key. `ai.embed(..., context={'secrets': {'api_key': user_key}})` passes the same per-request key to embedder handlers via `EmbedContext`. ## Flow contexts -`ActionRunContext` is replaced by a typed context for each kind of action. The chunk type moves from `@ai.flow(chunk_type=...)` into the context's type parameter. +`ActionRunContext` is replaced by `ActionContext` (in `genkit.plugin_api`) and a typed context for each kind of action (`FlowContext`, `ToolContext`, `ModelContext`, `EmbedContext`, `AgentContext`). The chunk type moves from `@ai.flow(chunk_type=...)` into the context's type parameter. **Old:** diff --git a/packages/genkit-google-genai/src/genkit_google_genai/_google.py b/packages/genkit-google-genai/src/genkit_google_genai/_google.py index 6653be097..459908cc9 100644 --- a/packages/genkit-google-genai/src/genkit_google_genai/_google.py +++ b/packages/genkit-google-genai/src/genkit_google_genai/_google.py @@ -65,8 +65,8 @@ from pydantic import BaseModel import genkit_google_genai._constants as const -from genkit import FlowContext, GenkitError, ModelResponse, Operation -from genkit.embedder import Embedder, EmbedderRef, EmbedRequest, EmbedResponse +from genkit import GenkitError, ModelResponse, Operation +from genkit.embedder import EmbedContext, Embedder, EmbedderRef, EmbedRequest, EmbedResponse from genkit.model import ( BackgroundModel, Model, @@ -365,7 +365,7 @@ def _create_embedder_action( is_vertex=(plugin_name == VERTEXAI_PLUGIN_NAME), ) - async def _run(request: EmbedRequest[EmbeddingConfig], ctx: FlowContext[Any]) -> EmbedResponse: + async def _run(request: EmbedRequest[EmbeddingConfig], ctx: EmbedContext) -> EmbedResponse: embedder_client = GoogleEmbedder( version=name, client=client_getter(ctx.context), diff --git a/packages/genkit-ollama/src/genkit_ollama/_plugin.py b/packages/genkit-ollama/src/genkit_ollama/_plugin.py index 1d3c7297c..73b118947 100644 --- a/packages/genkit-ollama/src/genkit_ollama/_plugin.py +++ b/packages/genkit-ollama/src/genkit_ollama/_plugin.py @@ -31,6 +31,7 @@ from genkit import GenkitError, ModelResponse, get_logger from genkit.embedder import ( + EmbedContext, Embedder, EmbedderInfo, EmbedderSupports, @@ -472,10 +473,12 @@ def _create_embedder_action(self, name: str) -> Action: base_url = self.base_url - async def _run(request: EmbedRequest) -> EmbedResponse: + async def _run(request: EmbedRequest, ctx: EmbedContext | None = None) -> EmbedResponse: + api_key = context_api_key(ctx.context) if ctx is not None else None # Embedding requests never fetch media, so the whole SDK call is wrapped. - async with wrap_connection_errors(base_url): - return await embedder.embed(request) + async with self._client_for_request(api_key=api_key) as client: + async with wrap_connection_errors(base_url): + return await embedder.embed(request, client=client) return Embedder( ollama_name(name), diff --git a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py index db0fdcf48..396fd345b 100644 --- a/packages/genkit-openai/src/genkit_openai/_openai_plugin.py +++ b/packages/genkit-openai/src/genkit_openai/_openai_plugin.py @@ -27,8 +27,9 @@ from openai.types import Model as OpenAIModelEntry from pydantic import BaseModel -from genkit import Embedding, FlowContext, GenkitError, ModelResponse +from genkit import Embedding, GenkitError, ModelResponse from genkit.embedder import ( + EmbedContext, Embedder, EmbedderInfo, EmbedderSupports, @@ -566,7 +567,7 @@ def _create_embedder_action(self, name: str) -> Action: }, ) - async def embed_fn(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedResponse: + async def embed_fn(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: """Embedder function that calls OpenAI embeddings API.""" # Extract text from document content texts = [] diff --git a/packages/genkit-openai/tests/openai_plugin_test.py b/packages/genkit-openai/tests/openai_plugin_test.py index 34ebcb4d4..8b6d56491 100644 --- a/packages/genkit-openai/tests/openai_plugin_test.py +++ b/packages/genkit-openai/tests/openai_plugin_test.py @@ -34,8 +34,8 @@ from openai.types import Model from openai.types.chat import ChatCompletion -from genkit import Document, FlowContext, Genkit, GenkitError, Message, ModelResponse, Part, Role -from genkit.embedder import EmbedRequest, EmbedResponse +from genkit import Document, Genkit, GenkitError, Message, ModelResponse, Part, Role +from genkit.embedder import EmbedContext, EmbedRequest, EmbedResponse from genkit.model import ConstrainedSupport, ModelSupports from genkit.plugin_api import Action, ActionKind, loop_local_client @@ -330,7 +330,7 @@ def _embedding_client(embedding: list[float] | None = None) -> MagicMock: async def _run_embedder(client: MagicMock, options: dict[str, Any] | None = None) -> EmbedResponse: """Run the embedder action function against a stub client.""" action = _plugin_with(client)._create_embedder_action('text-embedding-3-small') - return await action._fn(EmbedRequest(input=[Document.from_text('hello')], options=options or {}), FlowContext()) + return await action._fn(EmbedRequest(input=[Document.from_text('hello')], options=options or {}), EmbedContext()) @pytest.mark.asyncio @@ -625,6 +625,6 @@ def resolve(context: dict[str, Any]) -> MagicMock: plugin._embed_client = resolve # type: ignore[method-assign] action = plugin._create_embedder_action('text-embedding-3-small') tenant = {'secrets': {'api_key': 'sk-tenant'}} - await action._fn(EmbedRequest(input=[Document.from_text('hello')], options={}), FlowContext(context=tenant)) + await action._fn(EmbedRequest(input=[Document.from_text('hello')], options={}), EmbedContext(context=tenant)) assert seen == [tenant] diff --git a/packages/genkit/src/genkit/_ai/_agents/_runtime.py b/packages/genkit/src/genkit/_ai/_agents/_runtime.py index 632034c27..a1ad1ed3e 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_runtime.py +++ b/packages/genkit/src/genkit/_ai/_agents/_runtime.py @@ -47,7 +47,7 @@ mark_failure_logged, ) from genkit._ai._json_patch import diff_json -from genkit._core._action import ActionRunContext, get_current_context +from genkit._core._action import ActionContext, get_current_context from genkit._core._channel import CloseableQueue, QueueShutDown from genkit._core._compat import await_unchained, cancelling from genkit._core._error import ( @@ -277,7 +277,7 @@ async def update_custom(self, fn: Callable[[StateT | None], StateT]) -> None: await self.session.update_custom(fn) -class AgentContext(ActionRunContext[AgentStreamChunk]): +class AgentContext(ActionContext[AgentStreamChunk]): """Execution context passed to a custom agent function. Provides ``ctx.send_chunk(chunk)`` for streaming :class:`AgentStreamChunk` diff --git a/packages/genkit/src/genkit/_ai/_embedding.py b/packages/genkit/src/genkit/_ai/_embedding.py index b3214f678..9880b0db6 100644 --- a/packages/genkit/src/genkit/_ai/_embedding.py +++ b/packages/genkit/src/genkit/_ai/_embedding.py @@ -24,7 +24,7 @@ from pydantic.alias_generators import to_camel from typing_extensions import Never, TypeVar -from genkit._core._action import Action, ActionKind, FlowContext, get_func_description, with_request_annotation +from genkit._core._action import Action, ActionKind, EmbedContext, get_func_description, with_request_annotation from genkit._core._model import EmbedRequest, check_ref_config, check_ref_info from genkit._core._registry import Registry from genkit._core._schema import custom_options_schema, fixed_json_schema @@ -85,7 +85,7 @@ def __post_init__(self) -> None: EmbedderFn = ( Callable[[EmbedRequest[Any]], Awaitable[EmbedResponse]] - | Callable[[EmbedRequest[Any], FlowContext[Any]], Awaitable[EmbedResponse]] + | Callable[[EmbedRequest[Any], EmbedContext], Awaitable[EmbedResponse]] ) @@ -97,7 +97,8 @@ class Embedder(Action[EmbedRequest, EmbedResponse, Never]): The options class comes from ``config_schema`` or the fn's ``EmbedRequest[Cfg]`` annotation; given both, they must be the same class. - An unannotated fn still gets an ``EmbedRequest``. + An unannotated fn still gets an ``EmbedRequest``, typed by ``config_schema`` + when that is a Pydantic class. """ def __init__( @@ -142,10 +143,19 @@ def __init__( embedder_meta: dict[str, object] = metadata.copy() if metadata else {} embedder_meta['embedder'] = embedder_info + # An unannotated request gets EmbedRequest[Cfg] when config_schema is a + # Pydantic class, so options arrive as Cfg on every call path (ai.embed, + # Dev UI, CLI); an explicit ``request: EmbedRequest`` annotation keeps + # dict options. Built at runtime, so checkers can't read + # EmbedRequest[options_class] as a type. + from genkit._ai._model import python_config_schema # noqa: PLC0415 + + options_class = python_config_schema(config_schema) + request_type = cast(Any, EmbedRequest)[options_class] if options_class is not None else EmbedRequest super().__init__( kind=ActionKind.EMBEDDER, name=name, - fn=with_request_annotation(fn, EmbedRequest, kind=ActionKind.EMBEDDER), + fn=with_request_annotation(fn, request_type, kind=ActionKind.EMBEDDER), metadata=embedder_meta, description=get_func_description(fn, description), config_schema=config_schema, diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 3cde867b1..5c1380820 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -62,8 +62,8 @@ from genkit._core._action import ( GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR, Action, + ActionContext, ActionKind, - ActionRunContext, _action_context, # pyright: ignore[reportPrivateUsage] create_action_key, get_current_context, @@ -859,7 +859,7 @@ def define_generate_action(ai: _aio.Genkit) -> None: async def generate_action_fn( input: GenerateActionOptions, - ctx: ActionRunContext, + ctx: ActionContext, ) -> ModelResponse: on_chunk = cast(Callable[[ModelResponseChunk], None], ctx.streaming_callback) if ctx.is_streaming else None response = await run_generate( diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 3fc59abc1..2ce3f2d92 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -42,7 +42,7 @@ from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError from pydantic.alias_generators import to_camel from pydantic.errors import PydanticInvalidForJsonSchema, PydanticSchemaGenerationError, PydanticUserError -from typing_extensions import Self, TypeVar +from typing_extensions import Never, Self, TypeVar from genkit._core._channel import Channel, CloseableQueue, StoppableStream, _stop_scope from genkit._core._compat import StrEnum @@ -342,7 +342,7 @@ def parse_plugin_name_from_action_name(name: str) -> str | None: # async def ping(ctx: FlowContext) -> str: ... # no input # # Rules for the function: -# - The context is the parameter annotated ActionRunContext or a subclass +# - The context is the parameter annotated ActionContext or a subclass # (FlowContext, ToolContext, ModelContext, AgentContext). # - Any other parameter is the input, so there's only one. Put more fields # on one input model. @@ -372,7 +372,7 @@ def call( self, fn: Callable[..., _CallT], input: object, # noqa: A002 - ctx: 'ActionRunContext', + ctx: 'ActionContext', ) -> _CallT: """Call ``fn`` with ``input`` and ``ctx`` passed by parameter name. @@ -416,15 +416,21 @@ def _public_context_name(kind: ActionKind) -> str: """The public context type a handler of this kind annotates its ctx with. ToolContext for tools, ModelContext (genkit.model) for model and - background-model ops, AgentContext (genkit.exp.agent) for agents, and - FlowContext for flows, embedders, evaluators, and custom actions. + background-model ops, EmbedContext (genkit.embedder) for embedders, + AgentContext (genkit.exp.agent) for agents, ActionContext + (genkit.plugin_api) for custom/background actions, and FlowContext for + flows and evaluators. """ if kind in (ActionKind.TOOL, ActionKind.TOOL_V2): return 'ToolContext' if kind in _MODEL_CONTEXT_KINDS: return 'ModelContext' + if kind == ActionKind.EMBEDDER: + return 'EmbedContext' if kind == ActionKind.AGENT: return 'AgentContext' + if kind == ActionKind.CUSTOM: + return 'ActionContext' return 'FlowContext' @@ -507,10 +513,17 @@ def known_annotation_names(kind: ActionKind, *, context_kind: ActionKind | None if kind == ActionKind.BACKGROUND_MODEL: return {'ModelRequest': ModelRequest, 'Operation': Operation, 'ModelContext': ModelContext} if kind in (ActionKind.CHECK_OPERATION, ActionKind.CANCEL_OPERATION): - ctx_cls = ModelContext if effective_context_kind in _MODEL_CONTEXT_KINDS else FlowContext + ctx_cls = ModelContext if effective_context_kind in _MODEL_CONTEXT_KINDS else ActionContext return {'Operation': Operation, ctx_cls.__name__: ctx_cls} if kind == ActionKind.EMBEDDER: - return {'EmbedRequest': EmbedRequest, 'EmbedResponse': EmbedResponse, 'FlowContext': FlowContext} + return { + 'EmbedRequest': EmbedRequest, + 'EmbedResponse': EmbedResponse, + 'EmbedContext': EmbedContext, + 'FlowContext': FlowContext, + } + if kind == ActionKind.CUSTOM: + return {'ActionContext': ActionContext, 'Operation': Operation} return {} @@ -694,8 +707,8 @@ def _resolve_one(annotation: object, module_globals: dict[str, Any]) -> object: def _is_context_annotation(annotation: object) -> bool: """True if ``annotation`` marks the run-context parameter. - That's ActionRunContext or any subclass (FlowContext, ToolContext, - ModelContext, AgentContext), written any of these ways: ``ToolContext``, + That's ActionContext or any subclass (FlowContext, ToolContext, + ModelContext, EmbedContext, AgentContext), written any of these ways: ``ToolContext``, ``FlowContext[str]``, ``ToolContext | None``, or as a string (see _string_names_context). """ @@ -711,13 +724,12 @@ def _is_context_annotation(annotation: object) -> bool: return any(_is_context_annotation(arg) for arg in get_args(annotation)) # FlowContext[str] -> FlowContext cls = origin if origin is not None else annotation - return isinstance(cls, type) and issubclass(cls, ActionRunContext) + return isinstance(cls, type) and issubclass(cls, ActionContext) -# Public run-context subclasses of ActionRunContext. ToolContext and -# AgentContext live in submodules that may not be imported yet when -# ActionRunContext.__subclasses__() runs, so list all four explicitly. -_CONTEXT_ALIAS_NAMES = frozenset({'FlowContext', 'ToolContext', 'AgentContext', 'ModelContext'}) +# ToolContext and AgentContext live in submodules that may not be imported yet +# when ActionContext.__subclasses__() runs, so list them explicitly. +_CONTEXT_ALIAS_NAMES = frozenset({'ToolContext', 'AgentContext'}) def _string_names_context(annotation: str) -> bool: @@ -727,9 +739,9 @@ def _string_names_context(annotation: str) -> bool: 'FlowContext[str]' and 'genkit.ToolContext' all do. """ # The annotation couldn't be resolved to a class, so match by name against - # the public context classes, ActionRunContext, and every subclass defined so far. + # the public context classes, ActionContext, and every subclass defined so far. context_names: set[str] = set(_CONTEXT_ALIAS_NAMES) - classes: list[type] = [ActionRunContext] + classes: list[type] = [ActionContext] while classes: cls = classes.pop() context_names.add(cls.__name__) @@ -740,7 +752,7 @@ def _string_names_context(annotation: str) -> bool: for prefix in ('Optional[', 'typing.Optional['): if name.startswith(prefix) and name.endswith(']'): name = name[len(prefix) : -1].strip() # Optional[X] -> X - name = name.split('[', 1)[0] # ActionRunContext[str] -> ActionRunContext + name = name.split('[', 1)[0] # ActionContext[str] -> ActionContext name = name.rsplit('.', 1)[-1] # genkit.ToolContext -> ToolContext if name in context_names: return True @@ -874,11 +886,14 @@ def input_from_json(value: object) -> object: return NO_INPUT if value is None else value -class ActionRunContext(Generic[ChunkT]): +class ActionContext(Generic[ChunkT]): """Base execution context for a running action: request context and chunk streaming. - Subclassed publicly as ``genkit.FlowContext``, ``genkit.ToolContext``, - ``genkit.model.ModelContext``, and ``genkit.exp.agent.AgentContext``. + Exported in ``genkit.plugin_api`` for custom actions and + ``BackgroundAction`` handlers, and subclassed publicly as + ``genkit.FlowContext``, ``genkit.ToolContext``, + ``genkit.model.ModelContext``, ``genkit.embedder.EmbedContext``, and + ``genkit.exp.agent.AgentContext``. ``ChunkT`` is the type ``send_chunk`` accepts. @ai.flow @@ -935,8 +950,8 @@ def _current_context() -> dict[str, Any] | None: return _action_context.get(None) -class FlowContext(ActionRunContext[ChunkT]): - """Execution context passed to flow, embedder, evaluator, and custom action functions. +class FlowContext(ActionContext[ChunkT]): + """Execution context passed to flow functions. Provides ``ctx.send_chunk(chunk)`` for streaming ``ChunkT`` chunks and ``ctx.context`` for caller context data. @@ -965,7 +980,7 @@ async def check_allergies(dish: str, ctx: ToolContext) -> str: """ -class ModelContext(ActionRunContext[ModelResponseChunk]): +class ModelContext(ActionContext[ModelResponseChunk]): """Execution context passed to model and background-model functions. - ``ctx.send_chunk(chunk)`` streams a :class:`~genkit.ModelResponseChunk` to the caller. @@ -974,16 +989,45 @@ class ModelContext(ActionRunContext[ModelResponseChunk]): """ -def _context_cls_for_kind(kind: ActionKind) -> type[ActionRunContext[Any]]: +class EmbedContext(ActionContext[Never]): + """Execution context passed to embedder functions. + + ``ctx.context`` holds the caller's context dict. Embedders return one + response and never emit chunks, so ``send_chunk`` accepts nothing. + ``ctx.is_streaming`` still reports whether the caller asked to stream + (``Embedder.stream()``, a Dev UI run with ``stream=true``). + + A per-tenant key passed on ``embed`` reaches the embedder here: + + # 1. Read the tenant's key from the call's context + async def embed_menu(req: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: + api_key = ctx.context['secrets']['api_key'] + return await crm_embeddings(req.input, api_key=api_key) + + ai.define_embedder(name='bistro/menu-embedder', fn=embed_menu) + + # 2. Each call carries its own tenant's key + await ai.embed( + embedder='bistro/menu-embedder', + content=Document.from_text('Smoked Salmon Tartine'), + context={'secrets': {'api_key': tenant_key}}, + ) + # => [Embedding(embedding=[0.12, -0.03, ...])] + """ + + +def _context_cls_for_kind(kind: ActionKind) -> type[ActionContext[Any]]: """The context class ``Action._run`` constructs before invoking ``self._fn``.""" if kind in _MODEL_CONTEXT_KINDS: return ModelContext + if kind == ActionKind.EMBEDDER: + return EmbedContext # Tools and agents wrap or replace this base context in the AI layer: # call_tool_fn wraps it into ToolContext (adding resumed_metadata and # original_input) for both the tool and its tool.v2 envelope, and # BidiAction hands init/stream to AgentRuntime.run, which builds AgentContext. - if kind in (ActionKind.TOOL, ActionKind.TOOL_V2, ActionKind.AGENT): - return ActionRunContext + if kind in (ActionKind.TOOL, ActionKind.TOOL_V2, ActionKind.AGENT, ActionKind.CUSTOM): + return ActionContext return FlowContext @@ -1010,7 +1054,7 @@ def __init__( self._kind: ActionKind = kind self._name: str = name context_kind = _context_kind if _context_kind is not None else kind - self._context_cls: type[ActionRunContext[Any]] = _context_cls_for_kind(context_kind) + self._context_cls: type[ActionContext[Any]] = _context_cls_for_kind(context_kind) # Flows treat None as a real value and check the return against the # annotation. Other actions still treat a missing/None input as omitted # and leave the return unchecked. @@ -1260,7 +1304,7 @@ async def _run( inside_token = _inside_action.set(True) streaming_cb = cast(StreamingCallback, on_chunk) if on_chunk else None - action_ctx: ActionRunContext[Any] = self._context_cls( + action_ctx: ActionContext[Any] = self._context_cls( context=_action_context.get(None), streaming_callback=streaming_cb, init=init, @@ -1519,10 +1563,12 @@ def _layer_config_defaults(self, input: InputT | None) -> InputT | None: request validation fills defaults and checks values. - Untyped fn: non-None defaults < the request's config, folded to the keys the class accepts and validated against the class, so a bad - value raises INVALID_ARGUMENT the same as through ai.*. The fn gets - the merged dict as written, not pydantic's coerced values: + value raises INVALID_ARGUMENT the same as through ai.*. For models, + the fn gets the merged dict as written, not pydantic's coerced values: ModelConfig declares ``temperature`` as a float, and an untyped - plugin should still send the caller's ``1``, not ``1.0``. + plugin should still send the caller's ``1``, not ``1.0``. (Embedders + with an unannotated request parameter are upgraded to + ``EmbedRequest[Cfg]`` via ``with_request_annotation``.) An explicit None in the config is a value: it wins over the default and goes to validation. @@ -1641,7 +1687,7 @@ def _validate_input(self, input: InputT | None) -> InputT | None: async def _run_with_telemetry( self, input: object | None, - ctx: ActionRunContext, + ctx: ActionContext, on_trace_start: Callable[[str, str], Awaitable[None]] | None, telemetry_labels: dict[str, object] | None, *, @@ -1752,7 +1798,7 @@ def _validate_output(self, output: object) -> OutputT: reason=ErrorReason.INVALID_OUTPUT, ) from e - async def _invoke(self, input: object | None, ctx: ActionRunContext) -> OutputT: + async def _invoke(self, input: object | None, ctx: ActionContext) -> OutputT: """Call ``self._fn`` with the input and context. A missing input stays ``NO_INPUT`` so a defaulted parameter gets its @@ -1877,7 +1923,7 @@ def __init__( input_schema=input_schema, ) - async def action_fn(self, input: InputT, ctx: ActionRunContext) -> OutputT: # noqa: A002 + async def action_fn(self, input: InputT, ctx: ActionContext) -> OutputT: # noqa: A002 """Adapt the bidi fn to the plain Action fn shape. The bidi fn reads its per-turn inputs from an async stream and emits diff --git a/packages/genkit/src/genkit/_core/_background.py b/packages/genkit/src/genkit/_core/_background.py index 3bc1e0970..86046a8b5 100644 --- a/packages/genkit/src/genkit/_core/_background.py +++ b/packages/genkit/src/genkit/_core/_background.py @@ -33,9 +33,8 @@ from genkit._core._action import ( Action, + ActionContext, ActionKind, - ActionRunContext, - FlowContext, get_current_context, set_action_name, ) @@ -53,9 +52,9 @@ # Annotation-only aliases. Operation[OutT] is a concrete pydantic class at # runtime, so CheckOpFn[X] can't be subscripted outside an annotation; spell # the Callable out when you need a runtime alias. -StartOpFn = Callable[[InT, FlowContext], Awaitable[Operation]] -CheckOpFn = Callable[[Operation[OutT], FlowContext], Awaitable[Operation]] -CancelOpFn = Callable[[Operation[OutT], FlowContext], Awaitable[Operation]] +StartOpFn = Callable[[InT, ActionContext], Awaitable[Operation]] +CheckOpFn = Callable[[Operation[OutT], ActionContext], Awaitable[Operation]] +CancelOpFn = Callable[[Operation[OutT], ActionContext], Awaitable[Operation]] def _make_action_key(action_type: ActionKind | str, name: str) -> str: @@ -208,11 +207,11 @@ class ReportJob(BackgroundAction[RenderRequest, Report]): pass - async def start(request: RenderRequest, ctx: FlowContext) -> Operation: + async def start(request: RenderRequest, ctx: ActionContext) -> Operation: return Operation(id=await renderer.submit(request.quarter)) - async def check(op: Operation[Report], ctx: FlowContext) -> Operation: + async def check(op: Operation[Report], ctx: ActionContext) -> Operation: return await renderer.poll(op.id) @@ -493,7 +492,7 @@ def _operation_action( # wraps keeps fn's annotations on the wrapper, e.g. ModelRequest[VeoConfig]. @wraps(fn) - async def run_and_stamp(input: object, ctx: ActionRunContext) -> Operation: # noqa: A002 + async def run_and_stamp(input: object, ctx: ActionContext) -> Operation: # noqa: A002 if isinstance(input, Operation): # check/cancel: the caller's handle, often reloaded from storage. input = validate_operation(input, output_type=output_type, name=action.name, status='INVALID_ARGUMENT') # noqa: A001 diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index a210c44fb..2bee1b80a 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -315,19 +315,20 @@ def reject_config_api_key(config: object) -> None: # Bound to BaseModel so ModelRef is always parameterized with a concrete Pydantic config schema. # Covariant so ModelRef[GeminiConfig] is assignable to ModelRef[BaseModel] or ModelRef[Any]. ModelRefConfigT = TypeVar('ModelRefConfigT', bound=BaseModel, covariant=True) -# ModelRequest[X], EmbedRequest[X] and the evaluator requests take a pydantic -# model class; __class_getitem__ rejects the rest. Not bound to BaseModel: type -# checkers would then reject the common bare ModelRequest(config={...}), where -# the config is solved as a dict. Invariant: config is writable, so +# ModelRequest[X] and EmbedRequest[X] take a pydantic model class; +# __class_getitem__ rejects the rest. Not bound to BaseModel: type checkers +# would then reject the common bare ModelRequest(config={...}), where the +# config is solved as a dict. Invariant: config is writable, so # ModelRequest[GeminiConfig] is not a ModelRequest[ModelConfig] you can assign -# a ModelConfig into. Defaults to Any so bare ModelRequest means -# ModelRequest[Any], and Callable[[ModelRequest], ...] accepts a fn typed -# ModelRequest[GeminiConfig]. +# a ModelConfig into. +# +# Both default to Any, the way a bare generic does in Python (list is +# list[Any]). A helper annotated with bare ModelRequest or EmbedRequest then +# accepts a typed request, and Callable[[ModelRequest], ...] accepts a fn +# typed ModelRequest[GeminiConfig]. At runtime an untyped request still gets +# its config / options as a dict (see check_options_value). ModelRequestConfigT = TypeVar('ModelRequestConfigT', default=Any) -# Bare EmbedRequest / evaluator request options are always a dict at runtime, so the -# default says so. Fn aliases take EmbedRequest[Any] / EvaluatorRequest[Any] so a fn -# typed EmbedRequest[CrmEmbedConfig] still fits them. -RequestOptionsT = TypeVar('RequestOptionsT', default=dict[str, Any]) +RequestOptionsT = TypeVar('RequestOptionsT', default=Any) def declared_config_type(cls: type) -> type[BaseModel] | None: @@ -1164,8 +1165,17 @@ def _untyped_options_schema(schema: JsonDict, cls: type) -> None: class EmbedRequest(GenkitModel, Generic[RequestOptionsT]): """Embed request whose documents are the public Document type. - Bare ``EmbedRequest`` gives the fn ``options`` as a dict. - ``EmbedRequest[CrmEmbedConfig]`` gives it a validated ``CrmEmbedConfig``. + What ``options`` holds depends on how the embedder annotates ``request``: + + * **No annotation**: Genkit infers ``EmbedRequest[Cfg]`` from the + embedder's Pydantic ``config_schema``, so ``options`` is a ``Cfg``. + * ``EmbedRequest[CrmEmbedConfig]``: ``options`` is a validated + ``CrmEmbedConfig``. + * Bare ``EmbedRequest``: ``options`` is a ``dict``. An explicit annotation + is honored as written, the same as ``ModelRequest``. + + Bare ``EmbedRequest`` means ``EmbedRequest[Any]`` to type checkers, so a + helper annotated with it accepts any typed request. """ model_config: ClassVar[ConfigDict] = ConfigDict(json_schema_extra=_untyped_options_schema) diff --git a/packages/genkit/src/genkit/_core/_registry.py b/packages/genkit/src/genkit/_core/_registry.py index 439df8af6..7cd211adc 100644 --- a/packages/genkit/src/genkit/_core/_registry.py +++ b/packages/genkit/src/genkit/_core/_registry.py @@ -31,6 +31,7 @@ from genkit._core._action import ( GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR, Action, + ActionContext, ActionKind, ActionName, FlowContext, @@ -84,6 +85,7 @@ ActionFn = ( Callable[[], OutputT | Awaitable[OutputT]] | Callable[[InputT], OutputT | Awaitable[OutputT]] + | Callable[[InputT, ActionContext], OutputT | Awaitable[OutputT]] | Callable[[InputT, FlowContext], OutputT | Awaitable[OutputT]] | Callable[[InputT, ModelContext], OutputT | Awaitable[OutputT]] ) diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index f8e7578e9..94038dae7 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -30,8 +30,8 @@ from genkit._core._action import ( Action, + ActionContext, ActionKind, - ActionRunContext, get_func_description, resolve_type_hints, ) @@ -241,7 +241,7 @@ def model_schema_from_return_annotation( return to_json_schema(cast(type | dict[str, Any] | str, inner)) -class ToolContext(ActionRunContext[ChunkT]): +class ToolContext(ActionContext[ChunkT]): """What a tool sees while it runs: request context, streaming, and resume state. Annotate a tool parameter with it to receive it: @@ -282,7 +282,7 @@ async def refund_order(order_id: str, ctx: ToolContext) -> str: def __init__( self, - ctx: ActionRunContext[ChunkT], + ctx: ActionContext[ChunkT], *, resumed_metadata: dict[str, Any] | None = None, original_input: Any = None, # noqa: ANN401 - prior tool_request.input when replacing on restart @@ -314,7 +314,7 @@ async def call_tool_fn( tool: Action[Any, Any, Any, Any], func: Callable[..., Awaitable[OutputT]], raw_input: object, - ctx: ActionRunContext[Any], + ctx: ActionContext[Any], ) -> OutputT: """Call a tool function with a ``ToolContext`` carrying resume state. @@ -464,7 +464,7 @@ async def lookup_price(sku: str) -> str: typed_func: Callable[..., Awaitable[OutputT]] = func self._wire_action = None - async def tool_fn(raw_input: object, ctx: ActionRunContext[Any]) -> OutputT: + async def tool_fn(raw_input: object, ctx: ActionContext[Any]) -> OutputT: return await call_tool_fn(self, typed_func, raw_input, ctx) super().__init__( @@ -478,7 +478,7 @@ async def tool_fn(raw_input: object, ctx: ActionRunContext[Any]) -> OutputT: model_schema = model_schema_from_return_annotation(func, inferred=self.output_schema) self.metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] = model_schema - async def wire_fn(raw_input: object, ctx: ActionRunContext[Any]) -> MultipartToolResponse[Any]: + async def wire_fn(raw_input: object, ctx: ActionContext[Any]) -> MultipartToolResponse[Any]: raw = await call_tool_fn(self, typed_func, raw_input, ctx) return as_multipart_tool_response(raw, tool_name=self.name) @@ -542,7 +542,7 @@ def definition(self) -> ToolDefinition: output_schema=self.model_output_schema, ) - async def _invoke(self, input: object | None, ctx: ActionRunContext) -> OutputT: + async def _invoke(self, input: object | None, ctx: ActionContext) -> OutputT: """Run the function, then check its result the way generate would send it to a model. A value the model couldn't receive (unserializable output or metadata, diff --git a/packages/genkit/src/genkit/embedder/__init__.py b/packages/genkit/src/genkit/embedder/__init__.py index 2356ab9fa..e9692a10a 100644 --- a/packages/genkit/src/genkit/embedder/__init__.py +++ b/packages/genkit/src/genkit/embedder/__init__.py @@ -21,6 +21,7 @@ Example: from genkit.embedder import ( + EmbedContext, EmbedRequest, EmbedResponse, Embedder, @@ -34,11 +35,13 @@ EmbedderRef, EmbedderSupports, ) +from genkit._core._action import EmbedContext from genkit._core._model import EmbedRequest from genkit._core._typing import EmbedResponse __all__ = [ - # Request/Response types + # Request/Response/Context types + 'EmbedContext', 'EmbedRequest', 'EmbedResponse', # Action class diff --git a/packages/genkit/src/genkit/plugin_api/__init__.py b/packages/genkit/src/genkit/plugin_api/__init__.py index 5e7fea6d9..12b677ceb 100644 --- a/packages/genkit/src/genkit/plugin_api/__init__.py +++ b/packages/genkit/src/genkit/plugin_api/__init__.py @@ -17,7 +17,7 @@ """Framework primitives for plugin authors.""" # Base class and framework primitives -from genkit._core._action import Action, ActionKind +from genkit._core._action import Action, ActionContext, ActionKind from genkit._core._background import BackgroundAction from genkit._core._base import GenkitConfig from genkit._core._compat import StrEnum @@ -34,6 +34,7 @@ 'Plugin', 'GenkitConfig', 'Action', + 'ActionContext', 'BackgroundAction', 'ActionKind', 'DynamicActionProvider', diff --git a/packages/genkit/tests/genkit/ai/agent_context_test.py b/packages/genkit/tests/genkit/ai/agent_context_test.py index 723013c5b..48bd4d130 100644 --- a/packages/genkit/tests/genkit/ai/agent_context_test.py +++ b/packages/genkit/tests/genkit/ai/agent_context_test.py @@ -8,7 +8,7 @@ import pytest from genkit import Message, ModelResponseChunk, Part, Role -from genkit._core._action import ActionRunContext +from genkit._core._action import ActionContext from genkit.exp import Genkit from genkit.exp.agent import ( AgentContext, @@ -24,15 +24,15 @@ def test_agent_context_is_subclass_of_action_run_context() -> None: - """`AgentContext` subclasses `ActionRunContext[AgentStreamChunk]` so `isinstance(ctx, AgentContext)` works.""" - assert issubclass(AgentContext, ActionRunContext) + """`AgentContext` subclasses `ActionContext[AgentStreamChunk]` so `isinstance(ctx, AgentContext)` works.""" + assert issubclass(AgentContext, ActionContext) orig_bases = cast(tuple[Any, ...], getattr(AgentContext, '__orig_bases__', ())) assert len(orig_bases) == 1 - assert get_origin(orig_bases[0]) is ActionRunContext + assert get_origin(orig_bases[0]) is ActionContext assert get_args(orig_bases[0]) == (AgentStreamChunk,) ctx = AgentContext() assert isinstance(ctx, AgentContext) - assert isinstance(ctx, ActionRunContext) + assert isinstance(ctx, ActionContext) def _send_status(ctx: AgentContext) -> None: diff --git a/packages/genkit/tests/genkit/ai/background_action_test.py b/packages/genkit/tests/genkit/ai/background_action_test.py index e7d7e7a6e..7268148e8 100644 --- a/packages/genkit/tests/genkit/ai/background_action_test.py +++ b/packages/genkit/tests/genkit/ai/background_action_test.py @@ -21,14 +21,14 @@ import pytest from pydantic import BaseModel -from genkit import FlowContext, Genkit, Message, ModelResponse, Operation, Part +from genkit import Genkit, Message, ModelResponse, Operation, Part from genkit._ai._background_model import lookup_background_model from genkit._core._action import Action from genkit._core._error import GenkitError from genkit._core._schema import to_json_schema from genkit._core._typing import Role from genkit.model import BackgroundModel, ModelContext, ModelInfo, ModelRequest -from genkit.plugin_api import ActionKind, BackgroundAction +from genkit.plugin_api import ActionContext, ActionKind, BackgroundAction class RenderRequest(BaseModel): @@ -59,12 +59,12 @@ def _reply(text: str) -> ModelResponse: def _register_report_job(ai: Genkit) -> ReportJob: - async def start(request: RenderRequest, ctx: FlowContext) -> Operation: - assert isinstance(ctx, FlowContext) + async def start(request: RenderRequest, ctx: ActionContext) -> Operation: + assert isinstance(ctx, ActionContext) return Operation(id=f'render-{request.quarter}', done=False) - async def check(op: Operation[Report], ctx: FlowContext) -> Operation: - assert isinstance(ctx, FlowContext) + async def check(op: Operation[Report], ctx: ActionContext) -> Operation: + assert isinstance(ctx, ActionContext) return Operation(id=op.id, done=True, output={'url': f'https://reports.example/{op.id}.pdf', 'pages': 12}) job = ReportJob('render-report', start, check, kind=ActionKind.CUSTOM) @@ -159,11 +159,11 @@ def test_check_and_cancel_carry_start_metadata() -> None: assert each.metadata['team'] == 'finance' -async def _noop_start(request: RenderRequest, ctx: FlowContext) -> Operation: +async def _noop_start(request: RenderRequest, ctx: ActionContext) -> Operation: return Operation(id='noop') -async def _noop_check(op: Operation, ctx: FlowContext) -> Operation: +async def _noop_check(op: Operation, ctx: ActionContext) -> Operation: return op diff --git a/packages/genkit/tests/genkit/ai/config_pipeline_test.py b/packages/genkit/tests/genkit/ai/config_pipeline_test.py index b773f8598..6d70187ea 100644 --- a/packages/genkit/tests/genkit/ai/config_pipeline_test.py +++ b/packages/genkit/tests/genkit/ai/config_pipeline_test.py @@ -33,7 +33,7 @@ from genkit import FinishReason, Genkit, GenkitError from genkit._ai._embedding import EmbedderInfo, EmbedderRef -from genkit._core._action import ActionRunContext +from genkit._core._action import ActionContext from genkit._core._error import get_reflection_json from genkit._core._middleware import Middleware from genkit._core._model import ( @@ -99,7 +99,7 @@ def _embedding() -> EmbedResponse: def test_model_annotation_and_config_schema_must_agree() -> None: ai = Genkit() - async def bistro(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest[TableConfig], ctx: ActionContext) -> ModelResponse: return _ok() with pytest.raises(GenkitError, match=r"model 'bistro': config_schema is .*MenuOnlyConfig, but the function"): @@ -109,10 +109,10 @@ async def bistro(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> M def test_background_model_annotation_and_config_schema_must_agree() -> None: ai = Genkit() - async def start(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> Operation: + async def start(request: ModelRequest[TableConfig], ctx: ActionContext) -> Operation: raise NotImplementedError - async def check(operation: Operation, ctx: ActionRunContext) -> Operation: + async def check(operation: Operation, ctx: ActionContext) -> Operation: raise NotImplementedError with pytest.raises(GenkitError, match='config_schema is .*MenuOnlyConfig'): @@ -132,7 +132,7 @@ async def crm_search(request: EmbedRequest[CrmEmbedConfig]) -> EmbedResponse: def test_same_class_in_annotation_and_config_schema_is_fine() -> None: ai = Genkit() - async def bistro(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest[TableConfig], ctx: ActionContext) -> ModelResponse: return _ok() action = ai.define_model(name='bistro', fn=bistro, config_schema=TableConfig) @@ -143,7 +143,7 @@ async def bistro(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> M def test_annotation_alone_sets_config_schema_and_dev_ui_form() -> None: ai = Genkit() - async def bistro(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest[TableConfig], ctx: ActionContext) -> ModelResponse: return _ok() async def crm_search(request: EmbedRequest[CrmEmbedConfig]) -> EmbedResponse: @@ -208,7 +208,7 @@ def _pipeline_app(config_schema: type[BaseModel] = TableConfig) -> tuple[Genkit, ai = Genkit() seen: dict[str, Any] = {} - async def bistro(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest, ctx: ActionContext) -> ModelResponse: seen['model'] = request.config return _ok() @@ -285,7 +285,7 @@ async def test_typed_fns_see_the_class_with_defaults() -> None: ai = Genkit() seen: dict[str, Any] = {} - async def bistro(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest[TableConfig], ctx: ActionContext) -> ModelResponse: seen['model'] = request.config return _ok() @@ -314,7 +314,7 @@ async def test_typed_fn_always_gets_an_instance_even_with_all_none_defaults() -> ai = Genkit() seen: list[Any] = [] - async def bistro(request: ModelRequest[NotSetConfig], ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest[NotSetConfig], ctx: ActionContext) -> ModelResponse: seen.append(request.config) return _ok() @@ -335,7 +335,7 @@ async def test_typed_class_that_cannot_build_from_defaults_raises() -> None: ai = Genkit() seen: list[Any] = [] - async def booking(request: ModelRequest[ReservationConfig], ctx: ActionRunContext) -> ModelResponse: + async def booking(request: ModelRequest[ReservationConfig], ctx: ActionContext) -> ModelResponse: seen.append(request.config) return _ok() @@ -369,7 +369,7 @@ async def test_explicit_none_overrides_ref_and_default_for_an_optional_field() - ai_typed = Genkit() typed_seen: list[Any] = [] - async def kitchen(request: ModelRequest[KitchenConfig], ctx: ActionRunContext) -> ModelResponse: + async def kitchen(request: ModelRequest[KitchenConfig], ctx: ActionContext) -> ModelResponse: typed_seen.append(request.config) return _ok() @@ -408,7 +408,7 @@ async def test_untyped_fn_without_a_class_receives_none() -> None: ai = Genkit() seen: list[Any] = [] - async def bistro(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest, ctx: ActionContext) -> ModelResponse: seen.append(request.config) return _ok() @@ -470,7 +470,7 @@ def _typed_app() -> tuple[Genkit, dict[str, Any]]: ai = Genkit() seen: dict[str, Any] = {} - async def bistro(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest[TableConfig], ctx: ActionContext) -> ModelResponse: seen['model'] = request.config return _ok() @@ -670,7 +670,7 @@ def _alias_only_app() -> tuple[Genkit, dict[str, Any]]: ai = Genkit() seen: dict[str, Any] = {} - async def bistro(request: ModelRequest[AliasOnlyConfig], ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest[AliasOnlyConfig], ctx: ActionContext) -> ModelResponse: seen['model'] = request.config return _ok() @@ -792,11 +792,11 @@ async def test_background_model_start_gets_schema_defaults() -> None: ai = Genkit() seen: list[Any] = [] - async def start(request: ModelRequest, ctx: ActionRunContext) -> Operation: + async def start(request: ModelRequest, ctx: ActionContext) -> Operation: seen.append(request.config) return Operation(id='op-1', done=False) - async def check(operation: Operation, ctx: ActionRunContext) -> Operation: + async def check(operation: Operation, ctx: ActionContext) -> Operation: return operation ai.define_background_model(name='video', start=start, check=check, config_schema=TableConfig) @@ -822,11 +822,11 @@ async def test_middleware_sees_config_before_the_boundary() -> None: untyped_seen: list[object] = [] typed_seen: list[object] = [] - async def untyped(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def untyped(request: ModelRequest, ctx: ActionContext) -> ModelResponse: untyped_seen.append(request.config) return _ok() - async def typed(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> ModelResponse: + async def typed(request: ModelRequest[TableConfig], ctx: ActionContext) -> ModelResponse: typed_seen.append(request.config) return _ok() @@ -852,11 +852,11 @@ async def test_alias_forbid_class_takes_field_names_on_every_path() -> None: ai = Genkit() seen: dict[str, Any] = {} - async def typed(request: ModelRequest[AliasForbidConfig], ctx: ActionRunContext) -> ModelResponse: + async def typed(request: ModelRequest[AliasForbidConfig], ctx: ActionContext) -> ModelResponse: seen['typed'] = request.config return _ok() - async def untyped(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def untyped(request: ModelRequest, ctx: ActionContext) -> ModelResponse: seen['untyped'] = request.config return _ok() @@ -880,10 +880,10 @@ async def test_missing_required_field_fails_the_same_way_typed_or_untyped() -> N """Nothing fills party_size: a failed turn from generate, a raise from a direct run, same message.""" ai = Genkit() - async def typed(request: ModelRequest[ReservationConfig], ctx: ActionRunContext) -> ModelResponse: + async def typed(request: ModelRequest[ReservationConfig], ctx: ActionContext) -> ModelResponse: return _ok() - async def untyped(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def untyped(request: ModelRequest, ctx: ActionContext) -> ModelResponse: return _ok() ai.define_model(name='booking', fn=typed) @@ -959,7 +959,7 @@ async def test_untyped_fn_gets_enum_defaults_as_their_values() -> None: def test_model_json_schema_next_to_typed_annotation_raises() -> None: ai = Genkit() - async def bistro(request: ModelRequest[TableConfig], ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest[TableConfig], ctx: ActionContext) -> ModelResponse: return _ok() with pytest.raises( @@ -987,7 +987,7 @@ async def crm_search(request: EmbedRequest[CrmEmbedConfig]) -> EmbedResponse: def test_json_schema_with_untyped_fn_is_still_fine() -> None: ai = Genkit() - async def bistro(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def bistro(request: ModelRequest, ctx: ActionContext) -> ModelResponse: return _ok() action = ai.define_model(name='bistro', fn=bistro, config_schema=TABLE_JSON_SCHEMA) @@ -1010,7 +1010,7 @@ class ChefConfig(BaseModel): async def test_bad_config_names_each_problem_once_on_every_kind() -> None: ai = Genkit() - async def chef(request: ModelRequest[ChefConfig], ctx: ActionRunContext) -> ModelResponse: + async def chef(request: ModelRequest[ChefConfig], ctx: ActionContext) -> ModelResponse: return _ok() async def crm_search(request: EmbedRequest[ChefConfig]) -> EmbedResponse: @@ -1042,7 +1042,7 @@ async def test_config_out_of_bounds_says_got_once() -> None: """The bounds message already names the value; the config check doesn't append it again.""" ai = Genkit() - async def chef(request: ModelRequest[_KitchenConfig], ctx: ActionRunContext) -> ModelResponse: + async def chef(request: ModelRequest[_KitchenConfig], ctx: ActionContext) -> ModelResponse: return _ok() ai.define_model(name='chef', fn=chef, config_schema=_KitchenConfig) diff --git a/packages/genkit/tests/genkit/ai/embedding_test.py b/packages/genkit/tests/genkit/ai/embedding_test.py index 5bd1c2e2a..d19d91dd5 100644 --- a/packages/genkit/tests/genkit/ai/embedding_test.py +++ b/packages/genkit/tests/genkit/ai/embedding_test.py @@ -28,6 +28,7 @@ from genkit._core._schema import to_json_schema from genkit._core._typing import ActionMetadata, Embedding, EmbedResponse from genkit.embedder import ( + EmbedContext, Embedder, EmbedderInfo, EmbedderRef, @@ -831,7 +832,7 @@ async def test_embed_and_embed_many_pass_context_to_embedder() -> None: ai = Genkit() seen: list[dict[str, Any]] = [] - async def menu_embedder(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedResponse: + async def menu_embedder(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: seen.append(ctx.context) return EmbedResponse(embeddings=[Embedding(embedding=[0.1]) for _ in request.input]) @@ -843,3 +844,43 @@ async def menu_embedder(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedRe await ai.embed(embedder='menu', content='no context') assert seen == [tenant, tenant, {}] + + +@pytest.mark.asyncio +async def test_embedder_annotated_with_flow_context_still_runs() -> None: + """ctx: FlowContext is still accepted at runtime; Genkit passes an EmbedContext.""" + ai = Genkit() + seen: list[object] = [] + + async def menu_embedder(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedResponse: + seen.append(ctx) + return EmbedResponse(embeddings=[Embedding(embedding=[0.1]) for _ in request.input]) + + ai.define_embedder('menu', cast(Any, menu_embedder)) + await ai.embed(embedder='menu', content='Smoked Salmon Tartine', context={'table': 4}) + + ctx = seen[0] + assert type(ctx) is EmbedContext + assert ctx.context == {'table': 4} + + +@pytest.mark.asyncio +async def test_unannotated_embedder_with_config_schema_gets_typed_options() -> None: + """Every call path (ai.embed, Dev UI, CLI) hands an unannotated embedder its options as config_schema.""" + + class MenuEmbedConfig(BaseModel): + dimensions: int = 8 + + seen: list[object] = [] + + async def menu_embedder(request) -> EmbedResponse: # noqa: ANN001 # pyright: ignore[reportMissingParameterType] + seen.append(request.options) + return EmbedResponse(embeddings=[Embedding(embedding=[0.1]) for _ in request.input]) + + ai = Genkit() + embedder = ai.define_embedder('menu', menu_embedder, config_schema=MenuEmbedConfig) + + await ai.embed(embedder='menu', content='tartine', config={'dimensions': 4}) + await embedder.run(cast(Any, {'input': [{'content': [{'text': 'tartine'}]}], 'options': {'dimensions': 6}})) + + assert seen == [MenuEmbedConfig(dimensions=4), MenuEmbedConfig(dimensions=6)] diff --git a/packages/genkit/tests/genkit/ai/generate_loop_test.py b/packages/genkit/tests/genkit/ai/generate_loop_test.py index d4f006869..1a72437fb 100644 --- a/packages/genkit/tests/genkit/ai/generate_loop_test.py +++ b/packages/genkit/tests/genkit/ai/generate_loop_test.py @@ -23,7 +23,7 @@ ) from genkit._ai._generate import CallScope, augment_with_context, generate_action, resolved_interrupt_part from genkit._core import _tool as tool_mod -from genkit._core._action import ActionRunContext +from genkit._core._action import ActionContext from genkit._core._error import ErrorReason, GenkitError from genkit._core._model import GenerateActionOptions, ModelRequest, MultipartToolResponse, reject_unanswered_interrupts from genkit._core._typing import FinishReason, Role, ToolRequest @@ -254,14 +254,14 @@ async def test_child_flows_get_their_own_copy_of_the_context() -> None: seen: dict[str, object] = {} @ai.flow() - async def tag_order(table: str, ctx: ActionRunContext) -> str: + async def tag_order(table: str, ctx: ActionContext) -> str: ctx.context['table'] = table await asyncio.sleep(0.01) seen[table] = ctx.context['table'] return table @ai.flow() - async def seat_party(n: int, ctx: ActionRunContext) -> list[str]: + async def seat_party(n: int, ctx: ActionContext) -> list[str]: tables = await asyncio.gather(*(tag_order(f't{i}') for i in range(n))) seen['parent'] = ctx.context.get('table') return list(tables) @@ -481,7 +481,7 @@ async def wrap_model( return await next_fn(params, ctx) @ai.flow() - async def parent_flow(ctx: ActionRunContext) -> dict[str, object]: + async def parent_flow(ctx: ActionContext) -> dict[str, object]: await ai.generate(prompt='hi', use=[RewriteTenant(), ReadCurrentContext()]) return dict(ctx.context) diff --git a/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py b/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py index 866795c82..7b3150261 100644 --- a/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py +++ b/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py @@ -22,7 +22,7 @@ Role, ToolContext, ) -from genkit._core._action import ActionRunContext +from genkit._core._action import ActionContext from genkit._core._compat import cancelling from genkit._core._model import ModelRequest from genkit.exp.agent import AgentContext @@ -80,7 +80,7 @@ async def settle(aw: Awaitable[T]) -> T: async def test_contexts_do_not_expose_abort_signal() -> None: """Action, flow, tool, model, agent, and middleware contexts omit abort_signal.""" ai = Genkit() - action_ctx: ActionRunContext[str] = ActionRunContext() + action_ctx: ActionContext[str] = ActionContext() flow_ctx: FlowContext[str] = FlowContext() tool_ctx: ToolContext[str] = ToolContext(action_ctx) model_ctx: ModelContext = ModelContext() diff --git a/packages/genkit/tests/genkit/ai/model_test.py b/packages/genkit/tests/genkit/ai/model_test.py index d28cb44d6..2ad51b00e 100644 --- a/packages/genkit/tests/genkit/ai/model_test.py +++ b/packages/genkit/tests/genkit/ai/model_test.py @@ -13,7 +13,7 @@ from genkit import FinishReason, Media, Message, ModelResponse, ModelResponseChunk, Part, Role from genkit._ai._model import text_from_content from genkit._core import _typing as wire -from genkit._core._action import ActionRunContext +from genkit._core._action import ActionContext from genkit._core._error import ErrorReason, GenkitError from genkit._core._model import ABNORMAL_FINISH_REASONS, OutputConfig, SessionState, chunk_for_stream from genkit._core._schema import InvalidOutputSchemaError, to_json_schema @@ -442,7 +442,7 @@ def test_chunk_media_is_first_media_part() -> None: def test_model_action_metadata() -> None: """Test for Model(...)._action_metadata().""" - async def fn(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def fn(request: ModelRequest, ctx: ActionContext) -> ModelResponse: return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) action_metadata = Model( @@ -461,7 +461,7 @@ async def fn(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: def test_model_action_metadata_label_defaults_to_name() -> None: """With no label, the listed model shows its action name.""" - async def fn(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def fn(request: ModelRequest, ctx: ActionContext) -> ModelResponse: return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) action_metadata = Model('bistro/menu-writer', fn)._action_metadata() @@ -486,7 +486,7 @@ async def fn(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: def test_model_action_metadata_matches_model(info: ModelInfo | None, config_schema: type[BaseModel] | None) -> None: """Model(...)._action_metadata() carries identical metadata and schemas to the Model instance.""" - async def menu_writer(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def menu_writer(request: ModelRequest, ctx: ActionContext) -> ModelResponse: return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('Smoked Salmon Tartine')])) resolved = Model('bistro/menu-writer', menu_writer, info=info, config_schema=config_schema) @@ -501,7 +501,7 @@ async def menu_writer(request: ModelRequest, ctx: ActionRunContext) -> ModelResp def test_model_rejects_long_running() -> None: """A model action can't claim longRunning; that's a background model.""" - async def fn(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: + async def fn(request: ModelRequest, ctx: ActionContext) -> ModelResponse: return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) with pytest.raises(GenkitError, match='longRunning'): diff --git a/packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py b/packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py index ef5a4fa2f..07b120204 100644 --- a/packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py +++ b/packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py @@ -43,7 +43,7 @@ ) from genkit._ai._agents._client import StreamedMessageAccumulator from genkit._ai._tools import define_tool -from genkit._core._action import Action, ActionKind, ActionRunContext +from genkit._core._action import Action, ActionContext, ActionKind from genkit._core._registry import Registry from genkit.exp import Genkit as ExpGenkit from genkit.exp.agent import AgentStreamChunk @@ -1332,11 +1332,11 @@ async def test_generate_stream_raw_action_and_tool_from_action_emit_partial_chun ai = Genkit(model='scriptedModel') pm, _ = define_scripted_model(ai) - async def scan_fridge(_req: dict[str, Any], ctx: ActionRunContext[Step]) -> str: + async def scan_fridge(_req: dict[str, Any], ctx: ActionContext[Step]) -> str: ctx.send_chunk(Step(stage='top_shelf', percent=50)) return 'stocked' - async def check_grill(_req: dict[str, Any], ctx: ActionRunContext[str]) -> str: + async def check_grill(_req: dict[str, Any], ctx: ActionContext[str]) -> str: ctx.send_chunk('heating') return 'hot' @@ -1390,7 +1390,7 @@ async def sear_station(req: dict[str, Any], ctx: ToolContext[Step]) -> str: ctx.send_chunk(Step(stage=f'searing:{req["dish"]}', percent=60)) return f'seared:{req["dish"]}' - async def plate_station(req: dict[str, Any], ctx: ActionRunContext[Step]) -> str: + async def plate_station(req: dict[str, Any], ctx: ActionContext[Step]) -> str: ctx.send_chunk(Step(stage=f'plating:{req["dish"]}', percent=95)) return f'plated:{req["dish"]}' diff --git a/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py b/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py index 20e4cc90e..6ed9115ba 100644 --- a/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py +++ b/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py @@ -9,7 +9,7 @@ - ModelResponseChunk.output constructing the output schema from extracted JSON with optional defaults filled, closed subtrees validated, and missing required fields set to None -- ActionRunContext genericity over the chunk type +- ActionContext genericity over the chunk type - End-to-end generate_stream with output_schema producing typed chunks """ @@ -24,7 +24,7 @@ from genkit import Genkit, Message, ModelResponse, ModelResponseChunk, Part from genkit._core import _partial -from genkit._core._action import ActionRunContext +from genkit._core._action import ActionContext from genkit._core._model import chunk_for_stream from genkit._core._typing import Role from genkit.formats import FormatHandler, Formatter, FormatterConfig @@ -401,23 +401,23 @@ def test_list_quoted_unknown_name_stays_dicts(self) -> None: assert out.items[0] == {'name': 'x'} -class TestActionRunContextGenerics: - """ActionRunContext is generic over the chunk type, with a default.""" +class TestActionContextGenerics: + """ActionContext is generic over the chunk type, with a default.""" def test_unparameterized_usage_still_works(self) -> None: received: list[object] = [] - ctx = ActionRunContext(streaming_callback=received.append) + ctx = ActionContext(streaming_callback=received.append) ctx.send_chunk({'anything': 1}) assert received == [{'anything': 1}] def test_parameterized_usage_works_at_runtime(self) -> None: received: list[Recipe] = [] - ctx: ActionRunContext[Recipe] = ActionRunContext(streaming_callback=received.append) + ctx: ActionContext[Recipe] = ActionContext(streaming_callback=received.append) ctx.send_chunk(Recipe(title='t', steps=[])) assert received[0].title == 't' def test_class_is_subscriptable(self) -> None: - assert ActionRunContext[Recipe] is not None + assert ActionContext[Recipe] is not None @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/core/action_signature_test.py b/packages/genkit/tests/genkit/core/action_signature_test.py index 5c6737bcb..db75b65cc 100644 --- a/packages/genkit/tests/genkit/core/action_signature_test.py +++ b/packages/genkit/tests/genkit/core/action_signature_test.py @@ -1,7 +1,7 @@ # Copyright 2026 Google LLC # SPDX-License-Identifier: Apache-2.0 -"""Every action takes at most one input; the context goes to the parameter annotated ActionRunContext.""" +"""Every action takes at most one input; the context goes to the parameter annotated ActionContext.""" import sys import types @@ -11,9 +11,9 @@ import pytest from pydantic import TypeAdapter -from genkit import Document, FlowContext, Genkit, GenkitError, Message, ModelResponse, Operation, Part +from genkit import Document, Genkit, GenkitError, Message, ModelResponse, Operation, Part from genkit._ai._background_model import CheckModelOpFn, StartModelOpFn -from genkit._core._action import Action, ActionKind, ActionRunContext +from genkit._core._action import Action, ActionContext, ActionKind from genkit._core._typing import Role from genkit.model import ModelRequest from genkit.plugin_api import Plugin @@ -26,7 +26,7 @@ async def test_model_with_context_first_gets_request_and_context() -> None: """A model fn `(ctx, request)` gets each by annotation, not by position.""" seen: list[object] = [] - async def chef(ctx: ActionRunContext, request: ModelRequest) -> ModelResponse: + async def chef(ctx: ActionContext, request: ModelRequest) -> ModelResponse: seen.extend([type(request), ctx.context]) return _REPLY @@ -39,12 +39,12 @@ async def chef(ctx: ActionRunContext, request: ModelRequest) -> ModelResponse: @pytest.mark.asyncio async def test_action_with_optional_context_union_gets_context() -> None: - """`ctx: ActionRunContext | None` and `Optional[ActionRunContext]` both mark the context.""" + """`ctx: ActionContext | None` and `Optional[ActionContext]` both mark the context.""" - async def by_pipe(order: str, ctx: ActionRunContext | None = None) -> str: + async def by_pipe(order: str, ctx: ActionContext | None = None) -> str: return f'{order} for table {ctx.context["table"] if ctx else "?"}' - async def by_optional(ctx: Optional[ActionRunContext], order: str) -> str: # noqa: UP045 - the old spelling is the case under test + async def by_optional(ctx: Optional[ActionContext], order: str) -> str: # noqa: UP045 - the old spelling is the case under test return f'{order} for table {ctx.context["table"] if ctx else "?"}' for fn in (by_pipe, by_optional): @@ -59,16 +59,18 @@ async def test_action_with_postponed_context_annotations_gets_context() -> None: seen: list[object] = [] # Postponed annotations are stored as these strings. - async def plain(order: str, ctx: 'ActionRunContext') -> None: + async def plain(order: str, ctx: 'ActionContext') -> None: seen.append(type(ctx)) - async def parameterized(ctx: 'ActionRunContext[str]', order: str) -> None: + async def parameterized(ctx: 'ActionContext[str]', order: str) -> None: seen.append(type(ctx)) for fn in (plain, parameterized): await Action(ActionKind.CUSTOM, fn.__name__, fn).run('soup') - assert seen == [FlowContext, FlowContext] + from genkit.plugin_api import ActionContext + + assert seen == [ActionContext, ActionContext] # A user module that imports its context type only for type checkers, so the @@ -97,7 +99,7 @@ async def test_action_with_unresolvable_context_subclass_union_gets_context() -> """An unresolvable `'ToolContext | None'` still marks the context, by class name.""" module_globals: dict[str, object] = {} exec(_TYPE_CHECKING_CONTEXT_MODULE, module_globals) # noqa: S102 - builds a module with postponed annotations - plate = cast(Callable[[str, ActionRunContext], Awaitable[str]], module_globals['plate']) + plate = cast(Callable[[str, ActionContext], Awaitable[str]], module_globals['plate']) result = await Action(ActionKind.CUSTOM, 'plate', plate).run('soup', context={'table': 4}) @@ -109,7 +111,7 @@ async def test_action_with_agent_context_string_annotation_gets_context() -> Non """An unresolvable `'AgentContext'` annotation marks the context parameter rather than a second input.""" module_globals: dict[str, object] = {} exec(_TYPE_CHECKING_CONTEXT_MODULE, module_globals) # noqa: S102 - builds a module with postponed annotations - serve = cast(Callable[[str, ActionRunContext], Awaitable[str]], module_globals['serve']) + serve = cast(Callable[[str, ActionContext], Awaitable[str]], module_globals['serve']) action = Action(ActionKind.CUSTOM, 'serve', serve) result = await action.run('soup', context={'table': 4}) @@ -126,7 +128,7 @@ async def test_action_with_type_checking_only_context_runs_without_future_import module_globals: dict[str, object] = {} source = _TYPE_CHECKING_CONTEXT_MODULE.replace('from __future__ import annotations\n', '') exec(source, module_globals) # noqa: S102 - builds a module whose annotations are evaluated lazily - plate = cast(Callable[[str, ActionRunContext], Awaitable[str]], module_globals['plate']) + plate = cast(Callable[[str, ActionContext], Awaitable[str]], module_globals['plate']) result = await Action(ActionKind.CUSTOM, 'plate', plate).run('soup', context={'table': 4}) @@ -137,7 +139,7 @@ async def test_action_with_type_checking_only_context_runs_without_future_import async def test_action_with_defaulted_input_after_context_uses_default() -> None: """Running without an input leaves a defaulted input out, even when it comes after the context.""" - async def special(ctx: ActionRunContext, dish: str = 'risotto') -> str: + async def special(ctx: ActionContext, dish: str = 'risotto') -> str: return dish assert (await Action(ActionKind.CUSTOM, 'special', special).run()).response == 'risotto' @@ -147,7 +149,7 @@ async def special(ctx: ActionRunContext, dish: str = 'risotto') -> str: async def test_custom_action_allows_unannotated_input() -> None: """Only tools and flows require an input annotation; other actions accept anything.""" - async def echo(order, ctx: ActionRunContext) -> object: # noqa: ANN001 + async def echo(order, ctx: ActionContext) -> object: # noqa: ANN001 return order action = Action(ActionKind.CUSTOM, 'echo', echo) @@ -178,13 +180,13 @@ async def chef(request: ModelRequest, ctx) -> ModelResponse: # noqa: ANN001 (ActionKind.TOOL, 'ToolContext'), (ActionKind.TOOL_V2, 'ToolContext'), (ActionKind.AGENT, 'AgentContext'), - (ActionKind.EMBEDDER, 'FlowContext'), + (ActionKind.EMBEDDER, 'EmbedContext'), (ActionKind.EVALUATOR, 'FlowContext'), - (ActionKind.CUSTOM, 'FlowContext'), + (ActionKind.CUSTOM, 'ActionContext'), ], ) def test_signature_error_names_public_context_for_kind(kind: ActionKind, expected: str) -> None: - """The fix-it hint names the public context for each kind, never the internal ActionRunContext.""" + """The fix-it hint names the public context for each kind, never ActionRunContext.""" async def handler(order: str, extra: str) -> str: return order @@ -198,7 +200,7 @@ async def handler(order: str, extra: str) -> str: def test_action_with_positional_only_parameter_raises_type_error() -> None: """A positional-only parameter can't be passed by name, so it raises at definition.""" - async def chef(request: ModelRequest, /, ctx: ActionRunContext) -> ModelResponse: + async def chef(request: ModelRequest, /, ctx: ActionContext) -> ModelResponse: return _REPLY with pytest.raises(TypeError, match="model 'chef' parameter 'request' is positional-only"): @@ -211,11 +213,11 @@ async def test_background_model_with_context_first_start_gets_both() -> None: ai = Genkit() seen: list[object] = [] - async def start(ctx: ActionRunContext, request: ModelRequest) -> Operation: + async def start(ctx: ActionContext, request: ModelRequest) -> Operation: seen.extend([type(request), ctx.context]) return Operation(id='render-1', done=False) - async def check(op: Operation, ctx: ActionRunContext) -> Operation: + async def check(op: Operation, ctx: ActionContext) -> Operation: return op # StartModelOpFn types (request, ctx) positionally; the runtime takes either order. @@ -233,10 +235,10 @@ async def test_background_model_with_context_first_check_gets_operation() -> Non ai = Genkit() seen: list[object] = [] - async def start(request: ModelRequest, ctx: ActionRunContext) -> Operation: + async def start(request: ModelRequest, ctx: ActionContext) -> Operation: return Operation(id='render-1', done=False) - async def check(ctx: ActionRunContext, op: Operation) -> Operation: + async def check(ctx: ActionContext, op: Operation) -> Operation: seen.extend([op.id, ctx.context]) return op @@ -252,10 +254,10 @@ def test_background_model_actions_lists_start_check_and_cancel() -> None: """`actions` is every action a background model registers; cancel only when given.""" ai = Genkit() - async def start(request: ModelRequest, ctx: ActionRunContext) -> Operation: + async def start(request: ModelRequest, ctx: ActionContext) -> Operation: return Operation(id='render-1') - async def check(op: Operation, ctx: ActionRunContext) -> Operation: + async def check(op: Operation, ctx: ActionContext) -> Operation: return op video = ai.define_background_model(name='menu-video', start=start, check=check, cancel=check) @@ -268,7 +270,7 @@ async def check(op: Operation, ctx: ActionRunContext) -> Operation: def test_action_params_names_input_and_context() -> None: """`Action.params` exposes which parameter gets the input and which gets the context.""" - async def chef(ctx: ActionRunContext, request: ModelRequest) -> ModelResponse: + async def chef(ctx: ActionContext, request: ModelRequest) -> ModelResponse: return _REPLY params = Action(ActionKind.MODEL, 'chef', chef).params diff --git a/packages/genkit/tests/genkit/core/action_test.py b/packages/genkit/tests/genkit/core/action_test.py index 94c386023..22bc38b20 100644 --- a/packages/genkit/tests/genkit/core/action_test.py +++ b/packages/genkit/tests/genkit/core/action_test.py @@ -17,8 +17,8 @@ from genkit import FlowContext, Genkit, Message, Part, PublicError from genkit._core._action import ( Action, + ActionContext, ActionKind, - ActionRunContext, BidiAction, DapQualifiedName, create_action_key, @@ -165,14 +165,14 @@ async def async_foo(input: str) -> str: async def test_define_async_action_with_input_and_context() -> None: """Define and run async action with input and context.""" - async def async_foo(input: str, ctx: ActionRunContext) -> str: + async def async_foo(input: str, ctx: ActionContext) -> str: """An async action that returns 'syncFoo' with an input and context.""" return f'syncFoo {input} {ctx.context["foo"]}' action = Action(name='syncFoo', kind=ActionKind.CUSTOM, fn=async_foo) assert (await action.run('foo', context={'foo': 'bar'})).response == 'syncFoo foo bar' - assert (await async_foo('foo', ActionRunContext(context={'foo': 'bar'}))) == 'syncFoo foo bar' + assert (await async_foo('foo', ActionContext(context={'foo': 'bar'}))) == 'syncFoo foo bar' @pytest.mark.asyncio @@ -181,7 +181,7 @@ async def test_streaming_action_with_callback() -> None: async def foo( input: str, - ctx: ActionRunContext, + ctx: ActionContext, ) -> int: ctx.send_chunk('1') ctx.send_chunk('2') @@ -202,7 +202,7 @@ async def test_streaming_action_with_stream_method() -> None: async def foo( input: str, - ctx: ActionRunContext, + ctx: ActionContext, ) -> int: ctx.send_chunk('1') ctx.send_chunk('2') @@ -222,7 +222,7 @@ async def foo( def test_action_stream_does_not_accept_timeout() -> None: """action.stream has no timeout=; the async for waits until the run finishes.""" - async def foo(input: str, ctx: ActionRunContext) -> int: + async def foo(input: str, ctx: ActionContext) -> int: return 1 action = Action(name='foo', kind=ActionKind.CUSTOM, fn=foo) @@ -241,7 +241,7 @@ def test_parse_plugin_name_from_action_name() -> None: async def test_propagates_context_via_contextvar() -> None: """Context is properly propagated via contextvar.""" - async def foo(_: str | None, ctx: ActionRunContext) -> str: + async def foo(_: str | None, ctx: ActionContext) -> str: return json.dumps(ctx.context) foo_action = cast(Action[str | None, str], Action(name='foo', kind=ActionKind.CUSTOM, fn=foo)) @@ -267,7 +267,7 @@ async def baz() -> str: async def test_action_raises_errors() -> None: """Action.run raises the exception the body raised.""" - async def foo(_: str | None, ctx: ActionRunContext) -> None: + async def foo(_: str | None, ctx: ActionContext) -> None: raise Exception('oops') action = Action(name='fooAction', kind=ActionKind.CUSTOM, fn=foo) @@ -284,7 +284,7 @@ async def foo(_: str | None, ctx: ActionRunContext) -> None: async def test_action_error_has_no_trace_id_when_instrumented(hex_ids) -> None: """Tracing on doesn't change the raised exception; the trace id stays on the span.""" - async def foo(_: str | None, ctx: ActionRunContext) -> None: + async def foo(_: str | None, ctx: ActionContext) -> None: raise Exception('oops') action = Action(name='fooAction', kind=ActionKind.CUSTOM, fn=foo) @@ -360,7 +360,7 @@ async def test_action_context_isolation_sequential_and_nested() -> None: """Action context is isolated and does not bleed sequentially or permanently override in nested runs.""" # 1. Sequential isolation test - async def get_context(_: None, ctx: ActionRunContext) -> dict[str, object] | None: + async def get_context(_: None, ctx: ActionContext) -> dict[str, object] | None: return ctx.context tool_action = Action(name='getContext', kind=ActionKind.TOOL, fn=get_context) @@ -374,12 +374,12 @@ async def get_context(_: None, ctx: ActionRunContext) -> dict[str, object] | Non assert res2.response == {} # Bleeding check # 2. Nested isolation test (parent calls child with overrides) - async def child_fn(_: None, ctx: ActionRunContext) -> dict[str, object] | None: + async def child_fn(_: None, ctx: ActionContext) -> dict[str, object] | None: return ctx.context child_action = Action(name='childAction', kind=ActionKind.CUSTOM, fn=child_fn) - async def parent_fn(_: None, ctx: ActionRunContext) -> tuple[dict[str, object] | None, dict[str, object] | None]: + async def parent_fn(_: None, ctx: ActionContext) -> tuple[dict[str, object] | None, dict[str, object] | None]: # Run child action with different context child_res = await child_action.run(context={'auth': 'child_secret'}) # Return parent context (which should still be parent's original context!) @@ -420,7 +420,7 @@ async def greet(name: str = 'world') -> str: async def test_run_defaulted_input_arg_allows_none_with_ctx() -> None: """Same as above but for 2-arg (input + ctx) actions.""" - async def greet(name: str = 'world', ctx: ActionRunContext | None = None) -> str: + async def greet(name: str = 'world', ctx: ActionContext | None = None) -> str: return f'hi {name}' action = Action(name='greet_ctx', kind=ActionKind.CUSTOM, fn=greet) diff --git a/packages/genkit/tests/genkit/core/context_types_test.py b/packages/genkit/tests/genkit/core/context_types_test.py index dc8839067..a91499dac 100644 --- a/packages/genkit/tests/genkit/core/context_types_test.py +++ b/packages/genkit/tests/genkit/core/context_types_test.py @@ -14,7 +14,7 @@ # # SPDX-License-Identifier: Apache-2.0 -"""FlowContext, ToolContext, ModelContext, and AgentContext: subclasses of ActionRunContext.""" +"""FlowContext, ToolContext, ModelContext, and AgentContext: subclasses of ActionContext.""" import types from typing import Any, cast, get_args, get_origin @@ -23,6 +23,7 @@ from pydantic import BaseModel import genkit +import genkit.embedder import genkit.exp.agent import genkit.model import genkit.plugin_api @@ -39,8 +40,8 @@ Role, ToolContext, ) -from genkit._core._action import ActionKind, ActionRunContext, find_input_and_context -from genkit.embedder import EmbedRequest, EmbedResponse +from genkit._core._action import ActionKind, find_input_and_context +from genkit.embedder import EmbedContext, EmbedRequest, EmbedResponse from genkit.exp import Genkit as ExpGenkit from genkit.exp.agent import ( AgentContext, @@ -53,15 +54,15 @@ TurnResult, ) from genkit.model import ModelContext, ModelInfo, ModelRequest, ModelSupports -from genkit.plugin_api import BackgroundAction +from genkit.plugin_api import ActionContext, BackgroundAction def test_public_contexts_are_distinct_subclasses_of_action_run_context() -> None: - """FlowContext, ModelContext, ToolContext, and AgentContext are distinct subclasses of ActionRunContext.""" - public_classes = (FlowContext, ModelContext, ToolContext, AgentContext) + """Each public context class is a distinct subclass of ActionContext.""" + public_classes = (FlowContext, ModelContext, EmbedContext, ToolContext, AgentContext) for cls in public_classes: - assert cls is not ActionRunContext - assert issubclass(cls, ActionRunContext) + assert cls is not ActionContext + assert issubclass(cls, ActionContext) for cls_a in public_classes: for cls_b in public_classes: @@ -70,12 +71,12 @@ def test_public_contexts_are_distinct_subclasses_of_action_run_context() -> None def test_model_context_is_exported_from_genkit_model() -> None: - """`ModelContext` subclasses `ActionRunContext[ModelResponseChunk]` and is exported from `genkit.model`.""" + """`ModelContext` subclasses `ActionContext[ModelResponseChunk]` and is exported from `genkit.model`.""" assert 'ModelContext' in genkit.model.__all__ - assert issubclass(ModelContext, ActionRunContext) + assert issubclass(ModelContext, ActionContext) orig_bases = cast(tuple[Any, ...], getattr(ModelContext, '__orig_bases__', ())) assert len(orig_bases) == 1 - assert get_origin(orig_bases[0]) is ActionRunContext + assert get_origin(orig_bases[0]) is ActionContext assert get_args(orig_bases[0]) == (ModelResponseChunk,) @@ -90,15 +91,15 @@ def test_model_context_has_one_definition() -> None: def test_isinstance_works_and_distinguishes_each_context_class() -> None: """`isinstance` works at runtime for every context class without raising `TypeError`.""" - instances: list[tuple[ActionRunContext[Any], type[ActionRunContext[Any]]]] = [ + instances: list[tuple[ActionContext[Any], type[ActionContext[Any]]]] = [ (FlowContext(), FlowContext), (ModelContext(), ModelContext), - (ToolContext(ActionRunContext()), ToolContext), + (ToolContext(ActionContext()), ToolContext), (AgentContext(), AgentContext), ] for ctx, expected_cls in instances: - assert isinstance(ctx, ActionRunContext) + assert isinstance(ctx, ActionContext) assert isinstance(ctx, expected_cls) for _, other_cls in instances: if other_cls is not expected_cls: @@ -136,14 +137,17 @@ async def check_allergies(dish: str, ctx: ToolContext) -> str: assert not isinstance(AgentContext(), (FlowContext, ToolContext)) -def test_action_run_context_is_not_publicly_exported() -> None: - """`ActionRunContext` stays internal; public packages export only concrete subclasses.""" - assert 'ActionRunContext' not in genkit.__all__ - assert not hasattr(genkit, 'ActionRunContext') - assert 'ActionRunContext' not in genkit.plugin_api.__all__ - assert not hasattr(genkit.plugin_api, 'ActionRunContext') - assert 'ActionRunContext' not in genkit.model.__all__ - assert 'ActionRunContext' not in genkit.exp.agent.__all__ +def test_action_context_is_exported_in_plugin_api_only() -> None: + """`ActionContext` lives in `genkit.plugin_api`, and `EmbedContext` lives in `genkit.embedder`.""" + assert 'ActionContext' not in genkit.__all__ + assert not hasattr(genkit, 'ActionContext') + assert 'ActionContext' in genkit.plugin_api.__all__ + assert hasattr(genkit.plugin_api, 'ActionContext') + assert 'ActionContext' not in genkit.model.__all__ + assert 'ActionContext' not in genkit.exp.agent.__all__ + assert 'EmbedContext' in genkit.embedder.__all__ + assert hasattr(genkit.embedder, 'EmbedContext') + assert 'EmbedContext' not in genkit.__all__ def test_contexts_subscript_at_runtime() -> None: @@ -224,15 +228,15 @@ class Report(BaseModel): class ReportJob(BackgroundAction[RenderRequest, Report]): pass - async def start_report(request: RenderRequest, ctx: FlowContext) -> Operation: + async def start_report(request: RenderRequest, ctx: ActionContext) -> Operation: seen['custom_bg_start'] = ctx return Operation(id=f'report-{request.quarter}', done=False) - async def check_report(op: Operation[Report], ctx: FlowContext) -> Operation: + async def check_report(op: Operation[Report], ctx: ActionContext) -> Operation: seen['custom_bg_check'] = ctx return Operation(id=op.id, done=True, output=Report(url=f'https://reports.example/{op.id}.pdf')) - async def cancel_report(op: Operation[Report], ctx: FlowContext) -> Operation: + async def cancel_report(op: Operation[Report], ctx: ActionContext) -> Operation: seen['custom_bg_cancel'] = ctx return Operation(id=op.id, done=True) @@ -246,7 +250,7 @@ async def cancel_report(op: Operation[Report], ctx: FlowContext) -> Operation: for each in report_job.actions: ai._registry.register_action_from_instance(each) - async def menu_embedder(request: EmbedRequest, ctx: FlowContext) -> EmbedResponse: + async def menu_embedder(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: seen['embedder'] = ctx return EmbedResponse(embeddings=[Embedding(embedding=[0.25, 0.75]) for _ in request.input]) @@ -278,24 +282,24 @@ async def menu_embedder(request: EmbedRequest, ctx: FlowContext) -> EmbedRespons assert isinstance(seen['bg_cancel'], ModelContext) assert type(seen['bg_cancel']) is ModelContext - # 4. Custom BackgroundAction (start / check / cancel -> FlowContext) + # 4. Custom BackgroundAction (start / check / cancel -> ActionContext) report_op = await report_job.start(RenderRequest(quarter='q3')) checked_report = await ai.check_operation(report_op) assert checked_report.done is True cancelled_report = await ai.cancel_operation(report_op) assert cancelled_report.done is True - assert isinstance(seen['custom_bg_start'], FlowContext) - assert type(seen['custom_bg_start']) is FlowContext - assert isinstance(seen['custom_bg_check'], FlowContext) - assert type(seen['custom_bg_check']) is FlowContext - assert isinstance(seen['custom_bg_cancel'], FlowContext) - assert type(seen['custom_bg_cancel']) is FlowContext + assert isinstance(seen['custom_bg_start'], ActionContext) + assert type(seen['custom_bg_start']) is ActionContext + assert isinstance(seen['custom_bg_check'], ActionContext) + assert type(seen['custom_bg_check']) is ActionContext + assert isinstance(seen['custom_bg_cancel'], ActionContext) + assert type(seen['custom_bg_cancel']) is ActionContext # 5. Embedder embeddings = await ai.embed(embedder='bistro/menu-embedder', content=Document.from_text('Smoked Salmon Tartine')) assert embeddings[0].embedding == [0.25, 0.75] - assert isinstance(seen['embedder'], FlowContext) - assert type(seen['embedder']) is FlowContext + assert isinstance(seen['embedder'], EmbedContext) + assert type(seen['embedder']) is EmbedContext # 6. Custom Agent exp_ai = ExpGenkit() @@ -323,17 +327,21 @@ async def handle_turn(_: AgentInput, __: TurnContext) -> TurnResult | None: 'FlowContext', 'ToolContext', 'ModelContext', + 'EmbedContext', 'AgentContext', - 'ActionRunContext', + 'ActionContext', 'FlowContext[str]', 'ToolContext[int]', 'FlowContext | None', 'ModelContext | None', + 'EmbedContext | None', 'AgentContext | None', 'Optional[ToolContext]', 'Optional[ModelContext]', + 'Optional[EmbedContext]', 'genkit.FlowContext', 'genkit.model.ModelContext', + 'genkit.embedder.EmbedContext', 'genkit.exp.agent.AgentContext', 'genkit.ToolContext[int] | None', ], @@ -419,7 +427,7 @@ async def start_report(request: RenderRequest, ctx: FlowContext) -> Operation: async def bad_check_report(op: Operation[Report], extra: int) -> Operation: return op - with pytest.raises(TypeError, match="annotate 'extra' as FlowContext"): + with pytest.raises(TypeError, match="annotate 'extra' as ActionContext"): ReportJob('render-report', start_report, cast(Any, bad_check_report), kind=ActionKind.CUSTOM) async def start_video(request: ModelRequest, ctx: ModelContext) -> Operation: @@ -439,11 +447,12 @@ async def bad_check_video(op: Operation[ModelResponse], extra: int) -> Operation from pydantic import BaseModel -from genkit import FlowContext as RuntimeFlowContext, Operation as RuntimeOperation -from genkit.plugin_api import ActionKind, BackgroundAction +from genkit import Operation as RuntimeOperation +from genkit.plugin_api import ActionContext as RuntimeActionContext, ActionKind, BackgroundAction if TYPE_CHECKING: - from genkit import FlowContext, Operation + from genkit import Operation + from genkit.plugin_api import ActionContext class RenderRequest(BaseModel): @@ -458,25 +467,25 @@ class ReportJob(BackgroundAction[RenderRequest, Report]): pass -async def start_report(request: RenderRequest, ctx: FlowContext) -> Operation: - assert type(ctx) is RuntimeFlowContext +async def start_report(request: RenderRequest, ctx: ActionContext) -> Operation: + assert type(ctx) is RuntimeActionContext return RuntimeOperation(id=f'report-{request.quarter}', done=False) -async def check_report(op: Operation[Report], ctx: FlowContext) -> Operation: - assert type(ctx) is RuntimeFlowContext +async def check_report(op: Operation[Report], ctx: ActionContext) -> Operation: + assert type(ctx) is RuntimeActionContext return RuntimeOperation(id=op.id, done=True, output=Report(url=f'https://reports.example/{op.id}.pdf')) -async def cancel_report(op: Operation[Report], ctx: FlowContext) -> Operation: - assert type(ctx) is RuntimeFlowContext +async def cancel_report(op: Operation[Report], ctx: ActionContext) -> Operation: + assert type(ctx) is RuntimeActionContext return RuntimeOperation(id=op.id, done=True) """ @pytest.mark.asyncio -async def test_future_annotations_custom_background_job_receives_flow_context() -> None: - """`from __future__ import annotations` on a custom `BackgroundAction` resolves `Operation` and `FlowContext`.""" +async def test_future_annotations_custom_background_job_receives_action_context() -> None: + """`from __future__ import annotations` on a custom `BackgroundAction` resolves `Operation` and `ActionContext`.""" module = types.ModuleType('future_bg_job') exec(_FUTURE_BACKGROUND_JOB_MODULE, module.__dict__) # noqa: S102 - builds a module with postponed annotations diff --git a/packages/genkit/tests/genkit/core/reflection_v2_test.py b/packages/genkit/tests/genkit/core/reflection_v2_test.py index c151b5a58..10d0d11ea 100644 --- a/packages/genkit/tests/genkit/core/reflection_v2_test.py +++ b/packages/genkit/tests/genkit/core/reflection_v2_test.py @@ -45,7 +45,7 @@ from websockets.asyncio.server import serve from genkit import Genkit, Interrupt -from genkit._core._action import Action, ActionKind, ActionRunContext, BidiAction +from genkit._core._action import Action, ActionContext, ActionKind, BidiAction from genkit._core._error import StatusCodes from genkit._core._middleware import Middleware from genkit._core._model import AgentInit, AgentInput, ModelConfig @@ -593,7 +593,7 @@ async def refund_order(order_id: str) -> str: async def test_reflection_server_v2_streaming_run_action(fake_manager: FakeReflectionManager) -> None: registry = Registry() - async def stream_inc(x: int, ctx: ActionRunContext) -> int: + async def stream_inc(x: int, ctx: ActionContext) -> int: for i in range(x): ctx.send_chunk(i) return x @@ -1048,11 +1048,11 @@ async def test_reflection_server_v2_run_action_context_reaches_flow_and_subflow( caller = {'auth': {'uid': 'u_42', 'tier': 'gold'}, 'locale': 'en-US'} @ai.flow() - async def allergy_check(dish: str, ctx: ActionRunContext) -> dict[str, Any]: + async def allergy_check(dish: str, ctx: ActionContext) -> dict[str, Any]: return dict(ctx.context) @ai.flow() - async def order_dish(dish: str, ctx: ActionRunContext) -> dict[str, Any]: + async def order_dish(dish: str, ctx: ActionContext) -> dict[str, Any]: return {'flow': dict(ctx.context), 'subflow': await allergy_check(dish)} client, task = await _run_client_lifecycle(ai._registry, fake_manager) diff --git a/packages/genkit/tests/genkit/core/registry_test.py b/packages/genkit/tests/genkit/core/registry_test.py index bed9f87a4..a0344ba96 100644 --- a/packages/genkit/tests/genkit/core/registry_test.py +++ b/packages/genkit/tests/genkit/core/registry_test.py @@ -15,7 +15,7 @@ from structlog.testing import capture_logs from genkit import Genkit -from genkit._core._action import Action, ActionKind, ActionRunContext, create_action_key +from genkit._core._action import Action, ActionContext, ActionKind, create_action_key from genkit._core._dap import DapValue from genkit._core._model import ModelRequest, ModelResponse from genkit._core._operation import Operation @@ -499,11 +499,11 @@ def test_registry_satisfies_registry_like() -> None: assert isinstance(Registry(None), RegistryLike) -async def _bg_start(_request: ModelRequest, _ctx: ActionRunContext) -> Operation: +async def _bg_start(_request: ModelRequest, _ctx: ActionContext) -> Operation: return Operation(id='bg-op', done=False) -async def _bg_check(op: Operation, _ctx: ActionRunContext) -> Operation: +async def _bg_check(op: Operation, _ctx: ActionContext) -> Operation: return op @@ -524,7 +524,7 @@ async def test_resolve_model_finds_background_model() -> None: async def test_resolve_model_prefers_foreground_when_both_exist() -> None: """A normal model of the same name wins. The fallback is only for names that have no MODEL.""" - async def fg(_request: ModelRequest, _ctx: ActionRunContext) -> ModelResponse: + async def fg(_request: ModelRequest, _ctx: ActionContext) -> ModelResponse: return ModelResponse() ai = Genkit() diff --git a/packages/genkit/tests/genkit/core/run_in_new_span_test.py b/packages/genkit/tests/genkit/core/run_in_new_span_test.py index e1883cbdd..5674230fb 100644 --- a/packages/genkit/tests/genkit/core/run_in_new_span_test.py +++ b/packages/genkit/tests/genkit/core/run_in_new_span_test.py @@ -14,7 +14,7 @@ from pydantic import BaseModel from genkit import Genkit, Interrupt, Message, ModelResponse, Part, Role, ToolContext -from genkit._core._action import Action, ActionRunContext +from genkit._core._action import Action, ActionContext from genkit._core._telemetry._attrs import metadata_key from genkit._core._telemetry._http import ActiveSpan from genkit._core._telemetry._instrumentation import ( @@ -439,7 +439,7 @@ async def test_action_context_telemetry_redacts_auth_and_secrets(exporter) -> No """The Context panel hides identity and keys. The live action still sees them.""" seen: dict[str, object] = {} - async def peek(_input: object, ctx: ActionRunContext) -> str: + async def peek(_input: object, ctx: ActionContext) -> str: seen['secrets'] = ctx.context['secrets'] seen['auth'] = ctx.context['auth'] return 'ok' @@ -478,7 +478,7 @@ async def peek(_input: object, ctx: ActionRunContext) -> str: async def test_action_context_telemetry_whole_bag_redaction(exporter) -> None: """Top-level auth and secrets bags are replaced in full regardless of key names.""" - async def noop(_input: object, _ctx: ActionRunContext) -> str: + async def noop(_input: object, _ctx: ActionContext) -> str: return 'ok' action = Action( diff --git a/packages/genkit/tests/typecheck/context_contract_test.py b/packages/genkit/tests/typecheck/context_contract_test.py index 9f134b321..3157396db 100644 --- a/packages/genkit/tests/typecheck/context_contract_test.py +++ b/packages/genkit/tests/typecheck/context_contract_test.py @@ -14,7 +14,7 @@ # # SPDX-License-Identifier: Apache-2.0 -"""Type-checker contract for FlowContext, ToolContext, ModelContext, and AgentContext. +"""Type-checker contract for FlowContext, ToolContext, ModelContext, EmbedContext, and AgentContext. pyright, pyrefly, and ty include ``packages/*/tests/typecheck/`` with strict argument and overload checks enabled, so any signature mismatch here fails CI. @@ -40,8 +40,7 @@ Tool, ToolContext, ) -from genkit._core._action import ActionRunContext -from genkit.embedder import EmbedRequest, EmbedResponse +from genkit.embedder import EmbedContext, EmbedRequest, EmbedResponse from genkit.exp import Genkit as ExpGenkit from genkit.exp.agent import ( AgentContext, @@ -55,7 +54,7 @@ TurnResult, ) from genkit.model import ModelContext, ModelRequest -from genkit.plugin_api import ActionKind, BackgroundAction +from genkit.plugin_api import ActionContext, ActionKind, BackgroundAction class RenderRequest(BaseModel): @@ -71,27 +70,27 @@ class ReportJob(BackgroundAction[RenderRequest, Report]): def test_context_subclasses_satisfy_action_run_context() -> None: - """Each public context subclass satisfies ``ActionRunContext[ChunkT]``.""" + """Each public context subclass satisfies ``ActionContext[ChunkT]``.""" - def stream_step(ctx: ActionRunContext[int]) -> ActionRunContext[int]: + def stream_step(ctx: ActionContext[int]) -> ActionContext[int]: ctx.send_chunk(3) return ctx - def stream_model_chunk(ctx: ActionRunContext[ModelResponseChunk]) -> ActionRunContext[ModelResponseChunk]: + def stream_model_chunk(ctx: ActionContext[ModelResponseChunk]) -> ActionContext[ModelResponseChunk]: return ctx - def stream_agent_chunk(ctx: ActionRunContext[AgentStreamChunk]) -> ActionRunContext[AgentStreamChunk]: + def stream_agent_chunk(ctx: ActionContext[AgentStreamChunk]) -> ActionContext[AgentStreamChunk]: return ctx flow_ctx: FlowContext[int] = FlowContext[int]() - tool_ctx: ToolContext[int] = ToolContext(ActionRunContext[int]()) + tool_ctx: ToolContext[int] = ToolContext(ActionContext[int]()) model_ctx: ModelContext = ModelContext() agent_ctx: AgentContext = AgentContext() - assert_type(stream_step(flow_ctx), ActionRunContext[int]) - assert_type(stream_step(tool_ctx), ActionRunContext[int]) - assert_type(stream_model_chunk(model_ctx), ActionRunContext[ModelResponseChunk]) - assert_type(stream_agent_chunk(agent_ctx), ActionRunContext[AgentStreamChunk]) + assert_type(stream_step(flow_ctx), ActionContext[int]) + assert_type(stream_step(tool_ctx), ActionContext[int]) + assert_type(stream_model_chunk(model_ctx), ActionContext[ModelResponseChunk]) + assert_type(stream_agent_chunk(agent_ctx), ActionContext[AgentStreamChunk]) assert_type(flow_ctx.context, dict[str, Any]) assert_type(tool_ctx.is_resumed(), bool) assert_type(model_ctx.is_streaming, bool) @@ -99,7 +98,7 @@ def stream_agent_chunk(ctx: ActionRunContext[AgentStreamChunk]) -> ActionRunCont def test_registration_overloads_accept_public_and_internal_contexts() -> None: - """Registration APIs accept handlers annotated with public subclasses or internal ActionRunContext.""" + """Registration APIs accept handlers annotated with public subclasses or internal ActionContext.""" ai = Genkit() exp_ai = ExpGenkit() @@ -109,7 +108,7 @@ async def plate_dish(dish: str, ctx: FlowContext[str]) -> str: return dish @ai.flow - async def plate_dish_internal(dish: str, ctx: ActionRunContext[str]) -> str: + async def plate_dish_internal(dish: str, ctx: ActionContext[str]) -> str: ctx.send_chunk('plating') return dish @@ -141,7 +140,7 @@ async def chef(req: ModelRequest, ctx: ModelContext) -> ModelResponse: assert_type(ctx.is_streaming, bool) return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) - async def chef_internal(req: ModelRequest, ctx: ActionRunContext[ModelResponseChunk]) -> ModelResponse: + async def chef_internal(req: ModelRequest, ctx: ActionContext[ModelResponseChunk]) -> ModelResponse: del req, ctx return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) @@ -167,22 +166,22 @@ async def cancel_video(op: Operation[ModelResponse], ctx: ModelContext) -> Opera cancel=cancel_video, ) - async def start_report(req: RenderRequest, ctx: FlowContext) -> Operation: + async def start_report(req: RenderRequest, ctx: ActionContext) -> Operation: del ctx return Operation(id=f'report-{req.quarter}', done=False) - async def check_report(op: Operation[Report], ctx: FlowContext) -> Operation: + async def check_report(op: Operation[Report], ctx: ActionContext) -> Operation: del ctx return op - async def cancel_report(op: Operation[Report], ctx: FlowContext) -> Operation: + async def cancel_report(op: Operation[Report], ctx: ActionContext) -> Operation: del ctx return op job = ReportJob('render-report', start_report, check_report, kind=ActionKind.CUSTOM, cancel=cancel_report) assert job.name == 'render-report' - async def embed_menu(req: EmbedRequest, ctx: FlowContext) -> EmbedResponse: + async def embed_menu(req: EmbedRequest, ctx: EmbedContext) -> EmbedResponse: del ctx return EmbedResponse(embeddings=[Embedding(embedding=[0.5]) for _ in req.input]) @@ -229,14 +228,14 @@ async def serve_order(dish: str, ctx: FlowContext[str]) -> str: @pytest.mark.asyncio async def test_user_id_helper_accepts_flow_and_tool_contexts() -> None: - """``def user_id(ctx: FlowContext | ToolContext)`` accepts both contexts; ``ActionRunContext`` stays private.""" + """``def user_id(ctx: FlowContext | ToolContext)`` accepts both contexts; ``ActionContext`` stays private.""" ai = Genkit() def user_id(ctx: FlowContext | ToolContext) -> str: return ctx.context['auth']['uid'] flow_ctx: FlowContext = FlowContext(context={'auth': {'uid': 'diner-42'}}) - tool_ctx: ToolContext = ToolContext(ActionRunContext(context={'auth': {'uid': 'diner-7'}})) + tool_ctx: ToolContext = ToolContext(ActionContext(context={'auth': {'uid': 'diner-7'}})) assert_type(user_id(flow_ctx), str) assert_type(user_id(tool_ctx), str) assert user_id(flow_ctx) == 'diner-42' diff --git a/packages/genkit/tests/typecheck/init_kwonly_contract_test.py b/packages/genkit/tests/typecheck/init_kwonly_contract_test.py index 510227b6c..035714766 100644 --- a/packages/genkit/tests/typecheck/init_kwonly_contract_test.py +++ b/packages/genkit/tests/typecheck/init_kwonly_contract_test.py @@ -29,7 +29,7 @@ import pytest from genkit import ErrorReason, FlowContext, Genkit, Prompt, PublicError, ToolContext -from genkit._core._action import ActionRunContext, BidiAction +from genkit._core._action import ActionContext, BidiAction from genkit.exp.agent import AgentContext from genkit.middleware import MiddlewareContext from genkit.model import ModelContext @@ -79,7 +79,7 @@ def test_keyword_only_constructors_accept_documented_shapes() -> None: ) assert prompt.ref['name'] == 'menu_summary.dinner' - run_ctx = ActionRunContext(context={'table': 4}) + run_ctx = ActionContext(context={'table': 4}) flow_ctx = FlowContext(context={'table': 4}) model_ctx: ModelContext = ModelContext(context={'table': 4}) agent_ctx: AgentContext = AgentContext(context={'table': 4}) @@ -122,7 +122,7 @@ def test_positional_arguments_past_star_fail_type_checkers_and_runtime() -> None Prompt(ai, 'dinner') # pyright: ignore[reportCallIssue] # pyrefly: ignore[bad-argument-count] # ty: ignore[too-many-positional-arguments] with pytest.raises(TypeError, match='positional argument'): - ActionRunContext({'table': 4}) # pyright: ignore[reportCallIssue] # pyrefly: ignore[bad-argument-count] # ty: ignore[too-many-positional-arguments] + ActionContext({'table': 4}) # pyright: ignore[reportCallIssue] # pyrefly: ignore[bad-argument-count] # ty: ignore[too-many-positional-arguments] with pytest.raises(TypeError, match='positional argument'): FlowContext({'table': 4}) # pyright: ignore[reportCallIssue] # pyrefly: ignore[bad-argument-count] # ty: ignore[too-many-positional-arguments] @@ -149,7 +149,7 @@ def test_positional_arguments_past_star_fail_type_checkers_and_runtime() -> None (Action, ['self', 'kind', 'name', 'fn']), (BidiAction, ['self', 'kind', 'name', 'bidi_fn']), (Prompt, ['self', 'ai']), - (ActionRunContext, ['self']), + (ActionContext, ['self']), (ToolContext, ['self', 'ctx']), (MiddlewareContext, ['self', 'ai']), (PublicError, ['self', 'status', 'message', 'details']), diff --git a/packages/genkit/tests/typecheck/request_default_contract_test.py b/packages/genkit/tests/typecheck/request_default_contract_test.py new file mode 100644 index 000000000..45a0b60dc --- /dev/null +++ b/packages/genkit/tests/typecheck/request_default_contract_test.py @@ -0,0 +1,93 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +# pyright: reportUnnecessaryTypeIgnoreComment=true + +"""Typed contract of bare ``ModelRequest`` / ``EmbedRequest`` annotations. + +A bare request means ``Request[Any]``, the way bare ``list`` means +``list[Any]``. A helper annotated with the bare type must accept a typed +request in pyright, pyrefly and ty with no suppressions; an unneeded ignore +here fails CI. +""" + +from typing import Any + +from pydantic import BaseModel +from typing_extensions import assert_type + +from genkit import Document, Message, Part, Role +from genkit.embedder import EmbedRequest +from genkit.model import ModelConfig, ModelRequest + + +class MenuEmbedConfig(BaseModel): + """Options for a menu embedder.""" + + dimensions: int = 8 + + +class KitchenConfig(ModelConfig): + """Config for a kitchen model.""" + + spice_level: int = 1 + + +def count_dishes(request: EmbedRequest) -> int: + """A shared helper annotated with bare ``EmbedRequest``.""" + return len(request.input) + + +def count_turns(request: ModelRequest) -> int: + """A shared helper annotated with bare ``ModelRequest``.""" + return len(request.messages) + + +def count_batch(requests: list[EmbedRequest]) -> int: + """A helper over a list of bare ``EmbedRequest``.""" + return sum(len(r.input) for r in requests) + + +def test_bare_embed_request_helper_accepts_typed_request() -> None: + """``EmbedRequest[Cfg]`` passes to a helper typed with bare ``EmbedRequest``.""" + typed = EmbedRequest[MenuEmbedConfig](input=[Document.from_text('Smoked Salmon Tartine')]) + + assert count_dishes(typed) == 1 + assert count_batch([typed, typed]) == 2 + + +def test_bare_model_request_helper_accepts_typed_request() -> None: + """``ModelRequest[Cfg]`` passes to a helper typed with bare ``ModelRequest``.""" + typed = ModelRequest[KitchenConfig]( + messages=[Message(role=Role.USER, content=[Part.from_text('Plate the tartine')])] + ) + + assert count_turns(typed) == 1 + + +def read_options(request: EmbedRequest) -> object: + """A bare annotation: the default type argument applies here.""" + assert_type(request.options, Any) + return request.options + + +def test_bare_embed_request_options_is_any_statically_and_dict_at_runtime() -> None: + """Bare options is ``Any`` to checkers and a ``dict`` at runtime.""" + bare = EmbedRequest(input=[Document.from_text('tartine')], options={'dimensions': 4}) + + options = read_options(bare) + assert options == {'dimensions': 4} + assert isinstance(options, dict)