Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/genkit/src/genkit/_ai/_agents/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=[...])``.
Expand Down Expand Up @@ -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 []
Expand All @@ -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
Expand Down
33 changes: 21 additions & 12 deletions packages/genkit/src/genkit/_ai/_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
130 changes: 71 additions & 59 deletions packages/genkit/src/genkit/_ai/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
Action,
ActionKind,
ActionRunContext,
_action_context, # pyright: ignore[reportPrivateUsage]
create_action_key,
get_current_context,
parse_action_key,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion packages/genkit/src/genkit/_ai/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
29 changes: 23 additions & 6 deletions packages/genkit/src/genkit/_core/_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.
Expand Down Expand Up @@ -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
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
token = None
if context is not None:
token = _action_context.set(context)
Expand Down
5 changes: 3 additions & 2 deletions packages/genkit/src/genkit/_core/_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)):
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
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:
Expand Down
Loading
Loading