Repository navigation
fix(py): tool calling loop fixes, multipart unwrapping, and context propagation - #7140
huangjeff5 wants to merge 22 commits into
Conversation
total_usage had no write site, so multi-turn chargeback only saw the last turn. GenerateRun now sums each billed model call (including Retry/Fallback attempts) and stamps the total on the final, aborted, and boxed responses. usage stays the final turn. Empty usages add nothing, so totalUsage stays off the wire for models that report none (matches the shared generate spec). PR3-06
A restart rebuilt the persisted model toolRequest from the original request, so the model's next turn and any audit log read the unapproved input. The resolved request now carries the input the tool actually ran with and keeps the model's original on metadata.replacedInput. A restart that pauses again re-interrupts on the replaced input. exp AgentInterrupt exposes the interrupt payload as .metadata (AgentInterrupt.restart still takes no replace_input). PR3-04
_transform_prompt_metadata dropped both keys and load_prompt hardcoded output_constrained=True for any schema, so `constrained: false` had no effect and tools + schema prompts looped to MAX_TURNS_EXCEEDED on Gemini. Both keys now reach the request; a schema with no setting still defaults to native JSON. output_constrained stays fixed at definition (prompt_test pins OutputSettings as non-overridable per call); the per-call kwarg from the ledger is not added. PR3-08
One malformed .prompt file aborted the whole folder walk (siblings and subdirectories) with no filename, then still logged "Loaded prompts". Each file now loads in its own try and failures log the path and error. Also: variants split on the first dot only (scorer.v2.1 -> variant v2.1), partial frontmatter needs `---` on its own lines so Markdown dividers survive, and the folder summary drops to debug. Not in this commit: registered input.schema keeping Python defaults and wrapping template ExceptionGroups (left for a follow-up). PR3-16
The FAILED check only ran for ModelStreamResponse, so a flow streaming the
whole ModelResponse served {"result": ...} with empty text on a provider
failure. Any handle whose result is a FAILED ModelResponse now ends in the
error frame.
Flows that return response.text can't be detected at the SSE edge; PR0
(raise by default) covers them, and also covers raising from the stream
iterator's terminal step, so that half is not duplicated here.
PR3-02
ai.generate(system=..., messages=history) prepended a second Role.SYSTEM in front of turn 1's, so Gemini followed the stale persona on handoff and the prompt grew every turn; system='' was ignored. When system is not None, the system messages that lead messages= are dropped first; system='' clears them. Omitting system keeps the saved persona. PR3-10
validate_custom_state validated a reloaded snapshot's custom state and threw the result away, so turn 2 tools got the stored JSON dict and crashed on state.cart. load_session now seeds the session with the state_schema instance (snapshot reload and client-managed state). Custom-state patches dump BaseModel state to JSON before diffing, so deltas are field-level. Not in this commit: baseline state on read-only turns (TurnEnd state=None) and merging fragmented text/reasoning in StreamedMessageAccumulator. PR3-14
context_item_template kept only ref/id and rendered text, so citation schemas hallucinated sources and image/PDF parts never reached the model. Non-key metadata now goes out as JSON next to [ref], media parts follow the citation text with purpose=context, and a skipped docs= (an existing non-pending context part) logs a warning instead of being silent. Docs without extra metadata render exactly as before. response.messages is still built from the caller's messages (JS parity); the augmented messages are on response.request. PR3-18
ai.run was keyword-only and gated on iscoroutinefunction, rejecting
ai.run('step', fn) (the JS/Go shape), lambda: fetch(i), and instances with
async __call__, all of which pass type checks. It now takes name and fn
positionally (keywords still work), calls fn(), and awaits the result. A fn
that returns a non-awaitable still raises TypeError; steps stay async like
tools and flows.
Metadata attributes stay str()-coerced: typing them needs the matching
genkit-otel change on the BR branch.
PR3-19
Action._run handed the enclosing action's context dict to child flows by reference, so concurrent children writing ctx.context clobbered each other and the parent. A child with no explicit context now runs on dict(ambient), the same isolation run_tool_request already gives tools. PR3-20
max_turns=True ran as 1 through GenerateCall's lax int field, and nan leaked a raw pydantic ValidationError. Both now raise the same INVALID_ARGUMENT as a negative count, from ai.generate and /util/generate. A whole float (dotprompt's maxTurns: 3 -> 3.0) still passes. Call count is unchanged: max_turns=N still allows N tool rounds plus the reply, matching JS maxTurns and the existing test_max_turns_budget_is_spent_entirely_on_tool_rounds. See reviewer notes. PR3-07
ai.generate(prompt=..., resume_restart=...) appended a user turn after the
paused tool request and failed INVALID_RESUME only after a model call. It
now raises INVALID_ARGUMENT (reason INVALID_RESUME) up front. The
unanswered-interrupt checks carry the same reason. A bare restart() resumes
with {} and now still stamps the 'resumed' span attribute (is not None
instead of truthiness).
PR3-05
Tool.__init__ checked iscoroutinefunction(func) only, so a class with async def __call__ was rejected as "Got sync function". It now also checks type(func).__call__. Sync callables still raise; tools stay async-only. PR3-12
generate_action never set _action_context, so Genkit.current_context() inside wrap_generate/wrap_model/wrap_tool returned None (or a stale outer context) on ai.generate(..., context=...). The call's resolved context is now bound for the whole generate span and reset after. PR3-21
…hunk
Thinking text rides on reasoning parts and stays out of .text, but there was
no accessor for it; JS has response.reasoning. Each type now has
.reasoning -> str ('' when the model sent none). Message.media and
ModelResponseChunk.media are D3 and live on the media-accessor branch.
PR3-13
…ck error NaN/Infinity became null in tool outputs and model messages (mode='json') but crashed the web encoders (allow_nan=False) with a 500 on a -> dict[str, float] flow. The web encoders now send null too, which is what JS JSON.stringify does. 0.12-style `stream, response = flow.stream(x)` failed with an opaque "not iterable"; StreamResponse.__iter__ now raises a TypeError that shows the 0.13 shape. PR3-22
A model that keeps calling tools (multimodal + output_schema loops on Gemini were seen) burned 50 paid turns before ABORTED. The default is now 5 tool rounds, matching JS maxTurns, and ai.generate documents what max_turns counts. Callers that need longer loops pass max_turns=. PR3-23
…ToolResponse Manual tool loops had no way to attach media to a tool response, and a MultipartToolResponse passed as output= was serialized as JSON text, hiding the image from the model. from_tool_response now takes content= and unwraps a MultipartToolResponse into output/content/metadata like the engine does. PR3-11
call_model stamped the pre-hook request, so a wrap_model that stripped docs, config, or tools before the provider saw them still had the original echoed back on response.request. It now stamps the last request run_action sent (falling back to the pre-hook request when a hook short-circuits). Messages on response.request stay the resendable history (attach_resendable_history) by design; message-level PII has to be scrubbed in wrap_generate (PR1-11). PR3-17
BoxedFailure.from_exc dropped the provider's Retry-After hint and the GenkitError reason, so to_exception() (what SSE framing and PR0's raise path re-raise) lost both. They now round-trip; a PublicError keeps its reason through its details as before. Not in this commit: moving in-process message scrubbing and list-details wiping to the HTTP/SSE edge, and attaching ValidationError.errors() to INVALID_OUTPUT. Both move a privacy boundary and need the PR0 contract in place first. PR3-03
There was a problem hiding this comment.
Code Review
This pull request introduces several enhancements and bug fixes to the Genkit Python SDK, including tracking total token usage across tool loops, supporting async callable instances as tools, copying ambient context for child flows, and handling non-finite floats as null in SSE serialization. It also adds frontmatter parsing for output constraints and content types in prompt files. The review feedback highlights a few potential AttributeError risks in _prompt.py and _tool.py when handling None or non-callable objects, and suggests removing a redundant type cast.
| def file_constrained(output: dict[str, Any]) -> bool | None: | ||
| """Frontmatter `constrained:` wins; a schema with no setting asks for native JSON mode.""" |
There was a problem hiding this comment.
If the prompt frontmatter has an empty or null output block, output can be passed as None. To prevent an AttributeError when calling output.get(...), update the type signature to accept dict[str, Any] | None and handle the None case gracefully.
| def file_constrained(output: dict[str, Any]) -> bool | None: | |
| """Frontmatter `constrained:` wins; a schema with no setting asks for native JSON mode.""" | |
| def file_constrained(output: dict[str, Any] | None) -> bool | None: | |
| """Frontmatter `constrained:` wins; a schema with no setting asks for native JSON mode.""" | |
| if not output: | |
| return None |
| output_constrained=file_constrained(metadata.get('output', {})), | ||
| output_content_type=metadata.get('output', {}).get('contentType'), |
There was a problem hiding this comment.
If metadata contains an explicit null value for output (e.g., output: null in YAML), metadata.get('output', {}) will return None instead of {}. This will cause an AttributeError when calling .get('contentType'). Using metadata.get('output') or {} is safer as it handles both missing and explicit None values.
| output_constrained=file_constrained(metadata.get('output', {})), | |
| output_content_type=metadata.get('output', {}).get('contentType'), | |
| output_constrained=file_constrained(metadata.get('output') or {}), | |
| output_content_type=(metadata.get('output') or {}).get('contentType'), |
| """ | ||
| 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__)): |
There was a problem hiding this comment.
Accessing type(func).__call__ directly can raise an AttributeError if func is not callable or is a mock/custom object that does not implement __call__. Using getattr(type(func), '__call__', None) is safer and avoids potential runtime crashes.
| if not (inspect.iscoroutinefunction(func) or inspect.iscoroutinefunction(type(func).__call__)): | |
| if not (inspect.iscoroutinefunction(func) or inspect.iscoroutinefunction(getattr(type(func), '__call__', None))): |
| def _output_key(output: object, raw_output: object, key: str) -> Any: # noqa: ANN401 | ||
| for source in (output, raw_output): | ||
| if isinstance(source, dict): | ||
| value = cast(dict[str, Any], source).get(key) |
There was a problem hiding this comment.
|
Closing: migrated to standalone repository genkit-ai/genkit-python (PR #48): genkit-ai/genkit-python#48 |
Fixes generation loop turn mechanics, context propagation, and multipart tool responses.
Main Changes
Part.from_tool_responseunwrapsMultipartToolResponsecorrectly.Toolsupports callable instances with async__call__.