diff --git a/packages/genkit/src/genkit/_ai/_agents/_client.py b/packages/genkit/src/genkit/_ai/_agents/_client.py index eafe6e82..39f89a9e 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_client.py +++ b/packages/genkit/src/genkit/_ai/_agents/_client.py @@ -196,10 +196,13 @@ def __init__( name: str, ref: str | None, input_data: InputT, + metadata: dict[str, Any] | None = None, ) -> None: self.name = name self.ref = ref self.input = input_data + # What the tool passed to ``Interrupt(...)``: approval reason, amount, etc. + self.metadata = metadata def respond(self, output: OutputT) -> Part: """Tool response for ``chat.resume(respond=[...])``. @@ -404,6 +407,11 @@ def error_from_exception(e: Exception) -> GenkitError: return GenkitError(status=status, message=message, cause=e) +def interrupt_payload(part: Part) -> dict[str, Any] | None: + payload = (part.metadata or {}).get('interrupt') + return cast(dict[str, Any], payload) if isinstance(payload, dict) else None + + def agent_interrupts_from_message(message: Message | None) -> list[AgentInterrupt[Any, Any]]: if message is None: return [] @@ -418,6 +426,7 @@ def agent_interrupts_from_message(message: Message | None) -> list[AgentInterrup name=req.name, ref=req.ref, input_data=req.input, + metadata=interrupt_payload(part), ) ) return interrupts diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 4cc00f95..95b50da8 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -2062,31 +2062,40 @@ def current_context() -> dict[str, Any] | None: async def run( self, - *, name: str, fn: Callable[[], Awaitable[T]], + *, metadata: dict[str, Any] | None = None, ) -> T: - """Run a coroutine function as a discrete traced step within a flow. + """Run a function as a discrete traced step within a flow. - ``fn`` is a zero-argument ``async def`` function; each call creates its - own ``flowStep`` span in the trace. + ``fn`` takes no arguments and returns an awaitable, so ``async def`` + functions, ``lambda: fetch(i)``, and callables with an ``async def + __call__`` all work. Same shape as JS ``ai.run('step', fn)``. Example: ```python - # 1. Wrap a step in an async def and pass it with name= and fn= - async def fetch_menu() -> list[str]: - return await load_daily_specials() + # 1. Each fan-out step gets its own span in the trace + menus = await asyncio.gather(*[ai.run(f'fetch-{i}', lambda i=i: fetch_menu(i)) for i in range(3)]) - - menu = await ai.run(name='fetch-menu', fn=fetch_menu) + # 2. Keyword form still works + total = await ai.run(name='sum', fn=lambda: sum_prices(menus)) ``` """ - if not inspect.iscoroutinefunction(fn): - raise TypeError('fn must be a coroutine function') + if not callable(fn): + raise TypeError(f'fn must be callable, got {type(fn).__name__}') + not_awaitable = ( + 'fn must return an awaitable: pass an async def, a lambda returning a coroutine, ' + 'or wrap blocking work in asyncio.to_thread' + ) async def body(_span: object) -> T: - return await fn() + result = fn() + if not inspect.isawaitable(result): + # Steps stay async like tools and flows; blocking work goes + # through asyncio.to_thread. + raise TypeError(not_awaitable) + return await result attributes = {metadata_key(k): str(v) for k, v in (metadata or {}).items()} return await run_in_new_span(name, body, action_type='flowStep', attributes=attributes) diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 7194dd3f..2376be34 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -64,6 +64,7 @@ Action, ActionKind, ActionRunContext, + _action_context, # pyright: ignore[reportPrivateUsage] create_action_key, get_current_context, parse_action_key, @@ -722,6 +723,10 @@ def augment_with_context( if context_idx >= 0: meta = user_message.content[context_idx].metadata or {} if not meta.get('pending'): + logger.warning( + 'docs= not injected: the last user message already has a context part', + docs=len(request.docs), + ) return request # Render all documents as a single formatted text string @@ -927,69 +932,76 @@ async def run_generate( on_chunk=on_chunk, ) - mw_pipeline: MiddlewarePipeline | None = None - if middleware: - mw_pipeline = prepare_middleware(middleware, ctx=ctx, caller_stopped=caller_stopped) - mw_tools: list[Tool] = [] - for mw in mw_pipeline.middleware: - mw_tools.extend(mw.tools(mw_pipeline.ctx)) - - if mw_tools: - existing = list(options.tools) if options.tools else [] - declared = set(existing) - contributed_names: list[str] = [] - for t in mw_tools: - name = t.name - if name in declared or name in contributed_names: - raise GenkitError( - status='INVALID_ARGUMENT', - message=(f"tool '{name}' is contributed by middleware but already declared elsewhere"), - reason=ErrorReason.INVALID_INPUT, - ) - registry.register_action_from_instance(t) - contributed_names.append(name) - options = options.model_copy() - options.tools = existing + contributed_names - else: - mw_pipeline = MiddlewarePipeline(middleware=[], ctx=ctx, caller_stopped=caller_stopped) + # Bind the generate-scoped copy so middleware and hooks calling + # Genkit.current_context() see ctx.context (including earlier mutations) + # without mutating an enclosing flow's context. + context_token = _action_context.set(ctx.context) + try: + mw_pipeline: MiddlewarePipeline | None = None + if middleware: + mw_pipeline = prepare_middleware(middleware, ctx=ctx, caller_stopped=caller_stopped) + mw_tools: list[Tool] = [] + for mw in mw_pipeline.middleware: + mw_tools.extend(mw.tools(mw_pipeline.ctx)) + + if mw_tools: + existing = list(options.tools) if options.tools else [] + declared = set(existing) + contributed_names: list[str] = [] + for t in mw_tools: + name = t.name + if name in declared or name in contributed_names: + raise GenkitError( + status='INVALID_ARGUMENT', + message=(f"tool '{name}' is contributed by middleware but already declared elsewhere"), + reason=ErrorReason.INVALID_INPUT, + ) + registry.register_action_from_instance(t) + contributed_names.append(name) + options = options.model_copy() + options.tools = existing + contributed_names + else: + mw_pipeline = MiddlewarePipeline(middleware=[], ctx=ctx, caller_stopped=caller_stopped) - call = GenerateRun(messages=list(options.messages or []), caller_stopped=caller_stopped) + call = GenerateRun(messages=list(options.messages or []), caller_stopped=caller_stopped) - if is_debug_enabled(logger): - resolved: dict[str, object] = { - 'model': options.model, - 'messages': len(options.messages), - 'tools': len(options.tools or []), - 'max_turns': options.max_turns, - 'streaming': on_chunk is not None, - } - resolved['format'] = options.output.format if options.output else None - resolved['constrained'] = options.output.constrained if options.output else None - if middleware: - resolved['middleware'] = [middleware_name(m) for m in middleware] - logger.debug('generate request resolved', **resolved) + if is_debug_enabled(logger): + resolved: dict[str, object] = { + 'model': options.model, + 'messages': len(options.messages), + 'tools': len(options.tools or []), + 'max_turns': options.max_turns, + 'streaming': on_chunk is not None, + } + resolved['format'] = options.output.format if options.output else None + resolved['constrained'] = options.output.constrained if options.output else None + if middleware: + resolved['middleware'] = [middleware_name(m) for m in middleware] + logger.debug('generate request resolved', **resolved) - try: - return await run_wrap_generate( - registry=registry, - options=options, - mw_pipeline=mw_pipeline, - message_index=message_index, - current_turn=current_turn, - call=call, - ) - except asyncio.CancelledError as exc: - stamp_cancelled_error(exc=exc, messages=call.messages) - raise - except (Exception, _StreamingCallbackError) as exc: - if streaming_callback_cause(exc=exc) is None: + try: + return await run_wrap_generate( + registry=registry, + options=options, + mw_pipeline=mw_pipeline, + message_index=message_index, + current_turn=current_turn, + call=call, + ) + except asyncio.CancelledError as exc: + stamp_cancelled_error(exc=exc, messages=call.messages) raise - return box_from_exc( - response=ModelResponse(), - messages=call.messages, - exc=exc, - caller_stopped=False, - ) + except (Exception, _StreamingCallbackError) as exc: + if streaming_callback_cause(exc=exc) is None: + raise + return box_from_exc( + response=ModelResponse(), + messages=call.messages, + exc=exc, + caller_stopped=False, + ) + finally: + _action_context.reset(context_token) class ChunkAccumulator: diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index de02596b..39f37efa 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -162,7 +162,7 @@ async def run_tool_request( token_meta = _tool_resumed_metadata.set(resumed_meta) token_input = _tool_original_input.set(original_input) sink = _ScopedToolChunkSink(tool_request_part, on_tool_chunk) if on_tool_chunk is not None else None - run_context = dict(ctx.context) if ctx and ctx.context else None + run_context = dict(ctx.context) if ctx is not None and ctx.context is not None else None telemetry_labels = cast(dict[str, object], dict(ctx.telemetry_labels)) if ctx and ctx.telemetry_labels else None try: return ( diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 4b3afa82..3fc59abc 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -624,6 +624,15 @@ def signature_of(fn: Callable[..., object]) -> inspect.Signature: return inspect.signature(fn) +def _annotation_target(fn: Callable[..., object]) -> Callable[..., object]: + """Return ``fn.__call__`` for callable instances so Python 3.14 reads their annotations.""" + if callable(fn) and not inspect.isroutine(fn) and not isinstance(fn, type): + call = fn.__call__ + if inspect.ismethod(call) or inspect.isfunction(call): + return cast(Callable[..., object], call) + return fn + + def resolve_type_hints(fn: Callable[..., object], known: Mapping[str, object] | None = None) -> dict[str, Any]: """``fn``'s annotations as types. A name that can't be found stays a string. @@ -634,30 +643,32 @@ def resolve_type_hints(fn: Callable[..., object], known: Mapping[str, object] | ``known`` fills in names missing from ``fn``'s module (see known_annotation_names). The module's own names win. """ + target = _annotation_target(fn) try: - return get_type_hints(fn) + return get_type_hints(target) except Exception: - module_globals = getattr(inspect.unwrap(fn), '__globals__', {}) + module_globals = getattr(inspect.unwrap(target), '__globals__', {}) namespace = {**known, **module_globals} if known else module_globals - return {name: _resolve_one(a, namespace) for name, a in _annotations_as_written(fn).items()} + return {name: _resolve_one(a, namespace) for name, a in _annotations_as_written(target).items()} def _annotations_as_written(fn: Callable[..., object]) -> dict[str, Any]: """``fn``'s annotations without evaluating them; a missing name is a string.""" + target = _annotation_target(fn) if sys.version_info >= (3, 14): import annotationlib - annotations = annotationlib.get_annotations(fn, format=annotationlib.Format.FORWARDREF) + annotations = annotationlib.get_annotations(target, format=annotationlib.Format.FORWARDREF) if not any(isinstance(a, annotationlib.ForwardRef) for a in annotations.values()): return annotations # A ForwardRef's __forward_arg__ swaps names it did find for # placeholders ('ModelRequest[__annotationlib_name_1__]'), so take # the source text, the string `from __future__ import annotations` gives. - as_text = annotationlib.get_annotations(fn, format=annotationlib.Format.STRING) + as_text = annotationlib.get_annotations(target, format=annotationlib.Format.STRING) return { name: as_text[name] if isinstance(a, annotationlib.ForwardRef) else a for name, a in annotations.items() } - return dict(inspect.getfullargspec(fn).annotations) + return dict(inspect.getfullargspec(target).annotations) # Code object of an empty function, for _resolve_one. @@ -1237,6 +1248,12 @@ async def _run( input = self._validate_input(input) init = self._validate_init(init) + if context is None: + # Inherit the enclosing action's context as a shallow copy, so + # concurrent child flows setting top-level keys on ctx.context + # don't clobber each other or the parent (matching run_tool_request). + ambient = _action_context.get(None) + context = dict(ambient) if ambient is not None else None token = None if context is not None: token = _action_context.set(context) diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index 4ddb0cf6..f8e7578e 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -454,13 +454,14 @@ async def lookup_price(sku: str) -> str: ephemeral = Tool(lookup_price, name='lookup_price') res = await ai.generate(prompt='Price of SKU-1?', tools=[ephemeral]) """ - if not inspect.iscoroutinefunction(func): + # A callable instance with `async def __call__` is async too. + if not (inspect.iscoroutinefunction(func) or inspect.iscoroutinefunction(type(func).__call__)): raise TypeError(f'Tool function must be async. Got sync function: {getattr(func, "__name__", repr(func))}') tool_name = name if name is not None else getattr(func, '__name__', None) if tool_name is None: raise ValueError(f'Cannot infer a tool name from {func!r}; pass name= explicitly.') tool_description = get_func_description(func, description) - typed_func = cast(Callable[..., Awaitable[OutputT]], func) + typed_func: Callable[..., Awaitable[OutputT]] = func self._wire_action = None async def tool_fn(raw_input: object, ctx: ActionRunContext[Any]) -> OutputT: diff --git a/packages/genkit/tests/genkit/ai/generate_loop_test.py b/packages/genkit/tests/genkit/ai/generate_loop_test.py index a9cd5ae0..d4f00686 100644 --- a/packages/genkit/tests/genkit/ai/generate_loop_test.py +++ b/packages/genkit/tests/genkit/ai/generate_loop_test.py @@ -5,6 +5,9 @@ """Turn-loop invariants: max_turns, restart input, system= with history, docs=, and resume with prompt=.""" +import asyncio +from collections.abc import Awaitable, Callable + import numpy as np import pytest @@ -15,13 +18,16 @@ Message, ModelResponse, Part, + Tool, ToolContext, ) 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._error import ErrorReason, GenkitError -from genkit._core._model import GenerateActionOptions, ModelRequest, reject_unanswered_interrupts +from genkit._core._model import GenerateActionOptions, ModelRequest, MultipartToolResponse, reject_unanswered_interrupts from genkit._core._typing import FinishReason, Role, ToolRequest +from genkit.middleware import Middleware, MiddlewareContext, ModelHookParams, ToolHookParams from genkit.testing import ScriptedModel, define_scripted_model @@ -241,6 +247,30 @@ def test_docs_context_without_extra_metadata_is_unchanged() -> None: assert '- [r1]: Lentil soup\n' in text +@pytest.mark.asyncio +async def test_child_flows_get_their_own_copy_of_the_context() -> None: + """Concurrent child flows writing ctx.context don't clobber each other or the parent.""" + ai = Genkit() + seen: dict[str, object] = {} + + @ai.flow() + async def tag_order(table: str, ctx: ActionRunContext) -> 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]: + tables = await asyncio.gather(*(tag_order(f't{i}') for i in range(n))) + seen['parent'] = ctx.context.get('table') + return list(tables) + + await seat_party(3, context={'auth': {'uid': 'host-1'}}) + + assert seen == {'t0': 't0', 't1': 't1', 't2': 't2', 'parent': None} + + @pytest.mark.asyncio @pytest.mark.parametrize('bad', [True, False, float('nan'), float('inf'), 2.5]) async def test_max_turns_rejects_non_whole_numbers(bad: object) -> None: @@ -346,6 +376,121 @@ async def transfer(inp: dict, ctx: ToolContext) -> str: assert {'resumed': {}} in span_attrs +@pytest.mark.asyncio +async def test_tool_accepts_an_async_callable_instance() -> None: + """A class with `async def __call__` is an async tool; sync callables still fail.""" + + class AllergyCheck: + async def __call__(self, dish: str) -> str: + return f'{dish}: nut-free' + + class SyncCheck: + def __call__(self, dish: str) -> str: + return dish + + tool = Tool(AllergyCheck(), name='allergy_check') + assert tool.name == 'allergy_check' + assert tool.input_schema == {'type': 'string'} + assert (await tool.run('peanuts')).response == 'peanuts: nut-free' + + with pytest.raises(TypeError, match='must be async'): + Tool(SyncCheck(), name='sync_check') # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] + + +@pytest.mark.asyncio +async def test_middleware_sees_the_context_passed_to_generate() -> None: + """Genkit.current_context() inside a hook is the generate call's context.""" + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [_answers('ok')] + seen: list[object] = [] + + class AuditTenant(Middleware): + async def wrap_model( + self, + params: ModelHookParams, + ctx: MiddlewareContext, + next_fn: Callable[[ModelHookParams, MiddlewareContext], Awaitable[ModelResponse]], + ) -> ModelResponse: + seen.append(Genkit.current_context()) + return await next_fn(params, ctx) + + await ai.generate(prompt='hi', context={'tenant': 'bistro-9'}, use=[AuditTenant()]) + + assert seen == [{'tenant': 'bistro-9'}] + assert Genkit.current_context() is None + + +@pytest.mark.asyncio +async def test_middleware_cleared_context_does_not_leak_to_tool() -> None: + """Clearing ctx.context in wrap_tool hides caller secrets from the tool.""" + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + tool_seen: list[object] = [] + + @ai.tool(name='transfer') + async def transfer(inp: dict, ctx: ToolContext) -> str: + tool_seen.append(dict(ctx.context)) + return 'ok' + + class StripContext(Middleware): + async def wrap_tool( + self, + params: ToolHookParams, + ctx: MiddlewareContext, + next_fn: Callable[[ToolHookParams, MiddlewareContext], Awaitable[MultipartToolResponse]], + ) -> MultipartToolResponse: + ctx.context.clear() + return await next_fn(params, ctx) + + pm.responses = [_transfer_request(1), _answers('done')] + await ai.generate(prompt='go', tools=['transfer'], context={'secrets': 'top-secret'}, use=[StripContext()]) + + assert tool_seen == [{}] + + +@pytest.mark.asyncio +async def test_middleware_context_mutations_sync_with_current_context_and_isolate_flow() -> None: + """Middleware mutations are visible via current_context() and do not mutate parent flow context.""" + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [_answers('ok')] + seen_in_second: list[object] = [] + + class RewriteTenant(Middleware): + async def wrap_model( + self, + params: ModelHookParams, + ctx: MiddlewareContext, + next_fn: Callable[[ModelHookParams, MiddlewareContext], Awaitable[ModelResponse]], + ) -> ModelResponse: + ctx.context['tenant'] = 'rewritten' + return await next_fn(params, ctx) + + class ReadCurrentContext(Middleware): + async def wrap_model( + self, + params: ModelHookParams, + ctx: MiddlewareContext, + next_fn: Callable[[ModelHookParams, MiddlewareContext], Awaitable[ModelResponse]], + ) -> ModelResponse: + current = Genkit.current_context() + seen_in_second.append(dict(current) if current is not None else None) + if current is not None: + current['leaked'] = True + return await next_fn(params, ctx) + + @ai.flow() + async def parent_flow(ctx: ActionRunContext) -> dict[str, object]: + await ai.generate(prompt='hi', use=[RewriteTenant(), ReadCurrentContext()]) + return dict(ctx.context) + + flow_ctx = await parent_flow(context={'tenant': 'original'}) + + assert seen_in_second == [{'tenant': 'rewritten'}] + assert flow_ctx == {'tenant': 'original'} + + @pytest.mark.asyncio async def test_resume_with_user_turn_after_paused_tool_does_not_mention_prompt() -> None: """History ending in a user turn after a paused tool request must not blame prompt=.""" diff --git a/packages/genkit/tests/genkit/ai/genkit_api_test.py b/packages/genkit/tests/genkit/ai/genkit_api_test.py index a7b42d2c..9542a643 100644 --- a/packages/genkit/tests/genkit/ai/genkit_api_test.py +++ b/packages/genkit/tests/genkit/ai/genkit_api_test.py @@ -5,6 +5,7 @@ """Tests for the Genkit extra API methods.""" +import asyncio import json import os import signal @@ -157,9 +158,38 @@ async def async_fn() -> str: def sync_fn() -> str: return 'hello' - with pytest.raises(TypeError, match='fn must be a coroutine function'): + with pytest.raises(TypeError, match='fn must return an awaitable'): await ai.run(name='test3', fn=sync_fn) # type: ignore[arg-type] + # JS/Go shape: positional name and fn, lambdas, async-callable instances. + assert await ai.run('test4', async_fn) == 'world' + assert await ai.run('test5', lambda: async_fn()) == 'world' + + class Fetch: + async def __call__(self) -> str: + return 'menu' + + assert await ai.run('test6', Fetch()) == 'menu' + + +@pytest.mark.asyncio +async def test_genkit_run_accepts_sync_def_and_bound_method_returning_awaitable() -> None: + """Any callable returning an awaitable works, including named defs and bound methods.""" + ai = Genkit() + + async def inner(x: int) -> int: + return x * 2 + + def fan() -> asyncio.Future[tuple[int, int]]: + return asyncio.gather(inner(1), inner(2)) + + class Runner: + def go(self) -> asyncio.Future[tuple[int, int]]: + return asyncio.gather(inner(3), inner(4)) + + assert await ai.run('fan', fan) == [2, 4] + assert await ai.run('bound', Runner().go) == [6, 8] + @pytest.mark.asyncio async def test_genkit_run_tags_flow_step_action_type() -> None: