Skip to content

fix(py): accept positional steps and async callables in ai.run/Tool, and isolate child action context - #84

Merged
huangjeff5 merged 6 commits into
mainfrom
fix/py-1.0-pr3c-action-context-ai-run
Nov 13, 2026
Merged

huangjeff5 merged 6 commits into
mainfrom
fix/py-1.0-pr3c-action-context-ai-run

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

ai.run accepts positional (name, fn) arguments and callables returning awaitables (including lambdas calling async def functions and classes with async def __call__), child flows get isolated context copies, and middleware hooks see the call's context.

# --- BEFORE ---
async def fetch_menu(i: int) -> str:
    return f'menu_{i}'

# 1. Positional arguments in ai.run crashed
await ai.run('fetch-0', lambda: fetch_menu(0))
# => TypeError: Genkit.run() takes 1 positional argument but 3 were given

# 2. Lambdas returning coroutines were rejected because inspect.iscoroutinefunction() is False on lambdas
await ai.run(name='fetch-0', fn=lambda: fetch_menu(0))
# => TypeError: fn must be a coroutine function

# 3. Tool constructor rejected class instances with async def __call__
class OrderValidator:
    async def __call__(self, order: dict) -> bool:
        return True

Tool(OrderValidator(), name='validate_order')
# => TypeError: fn must be a coroutine function

# 4. Concurrent child flows shared a mutable ctx.context dict and clobbered each other
@ai.flow
async def seat_party(n: int, ctx: ActionRunContext) -> list[str]:
    # Child flows writing ctx.context['table'] overwrote each other's keys
    return await asyncio.gather(*[tag_order(f't{i}') for i in range(n)])

# 5. Middleware hooks saw None for context passed to ai.generate
await ai.generate(prompt='hi', context={'tenant': 'bistro-9'}, use=[AuditMiddleware()])
# => Genkit.current_context() inside wrap_model returned None


# --- AFTER ---
async def fetch_menu(i: int) -> str:
    return f'menu_{i}'

# 1. Positional args, closures, and fan-out all work in ai.run
menus = await asyncio.gather(*[
    ai.run(f'fetch-{i}', lambda i=i: fetch_menu(i))
    for i in range(3)
])
# => ['menu_0', 'menu_1', 'menu_2']

# 2. Named sync functions are still rejected up front before running
def sync_charge():
    ledger.charge(40)

await ai.run('charge', sync_charge)
# => TypeError: fn must return an awaitable: pass an async def, a lambda returning a coroutine, or wrap blocking work in asyncio.to_thread
#    (ledger.charge never ran)

# 3. Stateful callable class instances work directly as Tools
class OrderValidator:
    async def __call__(self, order: dict) -> bool:
        return True

validator_tool = Tool(OrderValidator(), name='validate_order')
print(validator_tool.name)
# => validate_order

# 4. Child flows get isolated copies of context; concurrent writes do not collide
@ai.flow
async def seat_party(n: int, ctx: ActionRunContext) -> list[str]:
    return await asyncio.gather(*[tag_order(f't{i}') for i in range(n)])
# Each child flow mutates its own dictionary copy safely

# 5. Middleware hooks see the context passed to generate
class AuditMiddleware(Middleware):
    async def wrap_model(self, params, ctx, next_fn):
        print(Genkit.current_context())
        return await next_fn(params, ctx)

await ai.generate(prompt='hi', context={'tenant': 'bistro-9'}, use=[AuditMiddleware()])
# => {'tenant': 'bistro-9'}

Main Changes

  • Accept positional steps and any awaitable callable in ai.run: In Python, lambdas are synchronous function objects that can return coroutine objects (e.g. lambda: fetch_menu(i) where fetch_menu is an async def function); checking inspect.iscoroutinefunction(fn) rejected every lambda returning a coroutine. We changed ai.run(name, fn) to accept arguments positionally or by keyword, inspect the returned value with inspect.isawaitable(), and reject named sync def functions up front before execution.
  • Support class instances with async def __call__ in Tool: Previously, Tool(...) relied strictly on inspect.iscoroutinefunction(), which evaluates to False on class instances even when their class defines an async def __call__. We now inspect type(func).__call__, allowing stateful callable objects to be registered as tools without wrapper functions.
  • Shallow-copy context to child actions: Previously, ActionRunContext passed the parent flow's mutable self.context dict directly to child flows, causing concurrent sibling tasks to overwrite each other's keys under async load. Child actions now receive a shallow copy (dict(parent.context)), isolating writes.
  • Bind call context for middleware during ai.generate: Previously, Genkit.current_context() returned None inside middleware hooks when context was passed directly to ai.generate(context=...). We now bind the call's context for the duration of the generate action, making it visible to telemetry and audit middleware.

@huangjeff5
huangjeff5 added this pull request to stack #88 November 11, 2026 02:37
@huangjeff5
huangjeff5 removed this pull request from stack #88 November 11, 2026 06:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3c-action-context-ai-run branch from a44f8d2 to 4376044 Compare November 11, 2026 06:22
@huangjeff5
huangjeff5 added this pull request to stack #89 November 11, 2026 06:23
@huangjeff5
huangjeff5 removed this pull request from stack #89 November 11, 2026 18:06
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3c-action-context-ai-run branch from 4376044 to 82db2b8 Compare November 11, 2026 18:38
@huangjeff5
huangjeff5 added this pull request to stack #104 November 11, 2026 19:43
…t input, and max_turns

- max_turns: validated up front. True, nan, inf, and 2.5 raise
  INVALID_ARGUMENT instead of running as 1 or leaking a ValidationError.
  A whole float like 3.0 from a .prompt file still works. Default stays
  50 tool rounds.
- restart(replace_input=...): history and the model's next turn carry the
  input the tool ran with. replacedInput is stripped from the history part
  so it doesn't read as a pending restart. A restart that pauses again
  pauses on the approved input.
- system= with messages=: prepended; system messages already in history
  are sent as stored. system='' adds nothing.
- prompt= with resume_respond/resume_restart: fails FAILED_PRECONDITION /
  INVALID_RESUME before the model runs, and the message names prompt=.
- docs=: text only, `- [ref]: text`; metadata and media stay out of the
  prompt. Skipping docs= because a context part already exists now logs.
- AgentInterrupt.metadata exposes the Interrupt(...) payload.
- A bare restart() reads as resumed in ctx.is_resumed() and on the span.
- Resume validation errors in reject_unanswered_interrupts set
  reason=INVALID_RESUME.
@huangjeff5
huangjeff5 removed this pull request from stack #104 November 12, 2026 06:39
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3c-action-context-ai-run branch from 82db2b8 to 766d5ea Compare November 12, 2026 07:26
@huangjeff5
huangjeff5 added this pull request to stack #118 November 12, 2026 07:32
@huangjeff5
huangjeff5 requested a review from apascal07 November 12, 2026 07:39
Comment thread packages/genkit/src/genkit/_ai/_aio.py Resolved
Base automatically changed from fix/py-1.0-pr3b-generate-loop-invariants to main November 13, 2026 03:18
# Conflicts:
#	packages/genkit/src/genkit/_ai/_aio.py
#	packages/genkit/src/genkit/_ai/_generate.py
#	packages/genkit/tests/genkit/ai/generate_loop_test.py
@huangjeff5
huangjeff5 merged commit 1d89c3b into main Nov 13, 2026
20 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-1.0-pr3c-action-context-ai-run branch November 13, 2026 15:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants