Skip to content

feat(py): add .reasoning, ModelResponse.total_usage, and multipart Part.from_tool_response - #48

Merged
huangjeff5 merged 4 commits into
mainfrom
fix/py-1.0-pr3-generation-loop
Nov 16, 2026
Merged

huangjeff5 merged 4 commits into
mainfrom
fix/py-1.0-pr3-generation-loop

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Adds .reasoning on ModelResponse, Message, and ModelResponseChunk, populates ModelResponse.total_usage with every model call made under a generate, echoes the post-middleware request on response.request, and lets Part.from_tool_response build multipart tool responses the same way the tool runner does.

# --- BEFORE ---
# 1. Reading thinking tokens meant filtering raw content parts
thoughts = ''.join(p.reasoning for p in res.message.content if p.reasoning)

# 2. total_usage existed on the schema but was never set
res = await ai.generate(prompt='Is pad thai safe for peanut allergies?', tools=[check_allergens])
res.usage.input_tokens   # => 140  (last model call only)
res.total_usage          # => None

# 3. Media on a manual tool response meant hand-dumping camelCase wire dicts,
#    and a Pydantic output reached the plugin as a Python object
part = Part(tool_response=ToolResponse(name=req.name, ref=req.ref, output=receipt, content=[chart.model_dump(...)]))


# --- AFTER ---
# 1. .reasoning joins thinking parts; .text still leaves them out
print(res.reasoning)
# => Checking sauce and garnish ingredients for peanuts...

# 2. total_usage sums every model call the run made: each tool-loop turn, a Retry
#    calling next() again, a Fallback backup model, a nested generate in a tool
res = await ai.generate(prompt='Is pad thai safe for peanut allergies?', tools=[check_allergens], use=[Fallback(models=['backup'])])
print(res.usage.input_tokens, res.total_usage.input_tokens)
# => 140 412

# 3. content= and MultipartToolResponse are accepted; output and metadata are dumped to JSON
part = Part.from_tool_response(name=req.name, ref=req.ref, output=receipt, content=[chart])
part.tool_response.output
# => {'order_id': 'A17', 'total_cents': 1250}
Part.from_tool_response(name='sales_chart', content=[Part.from_media('')])
# => GenkitError: INVALID_ARGUMENT, Tool 'sales_chart' content includes a part with no live payload.

Main Changes

  • .reasoning on responses, messages, and chunks: .text already skips reasoning parts, so reading the model's thinking meant iterating message.content. .reasoning concatenates reasoning parts and returns '' when there are none. Go has resp.Reasoning(); JS has response.reasoning.
  • total_usage counts every model call under the run: Previously total_usage was always None, so a tool loop reported only its last call. Every model action now reports its usage to a context-scoped sink that generate installs, so calls made outside next() count too: Fallback calls the backup model directly, and a tool can run its own generate. usage stays the call that produced the reply, so total_usage >= usage holds. This follows Go's TotalUsage; JS never sets totalUsage.
  • response.request echoes the request after wrap_model; docs are inlined model-side: Previously response.request was the request before middleware, and docs= were inlined into the last user message before any wrap_model ran, so clearing request.docs in middleware didn't keep them from the model. Inlining now runs in the model action itself, after every wrap_model, as in Go. Every route to a model gets it, including Fallback's direct backup call and a judge model called from middleware, and a request that already carries the context part isn't inlined twice. response.request carries the request the model action last received (the last next() call when a middleware retries); messages stays the resendable history. JS also inlines model-side (augmentWithContext), but behind a supports.context check; Python always inlines, on purpose.
  • Part.from_tool_response matches the tool runner: Previously it accepted only output and kept it as-is, so a manual loop (return_tool_requests=True) had to hand-dump content, and a Pydantic output reached plugins as a model object (Bedrock fails to serialize it; plugins calling str() send the repr). It now accepts content: Sequence[Part], unwraps MultipartToolResponse, dumps output and metadata to JSON, and raises INVALID_ARGUMENT on empty or non-serializable parts, using the same helpers as the tool runner. Setting content or metadata both on the MultipartToolResponse and as a keyword also raises INVALID_ARGUMENT instead of dropping one.

Breaking changes

  • wrap_model no longer sees doc text in messages: docs reach wrap_model only on request.docs; the context part is added after the last middleware. Middleware that scanned message text for doc content must read request.docs instead. Clearing request.docs in wrap_model now keeps the docs from the model.

@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from 1379dbb to a0bc468 Compare November 9, 2026 19:08
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from a0bc468 to 1aee91c Compare November 9, 2026 19:53
@huangjeff5
huangjeff5 changed the base branch from main to fix/py-1.0-pr3-media-accessor November 9, 2026 19:53
@huangjeff5
huangjeff5 added this pull request to stack #59 November 9, 2026 19:58
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch from fa6ce23 to 8f25d33 Compare November 9, 2026 20:02
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from 1aee91c to 18f884b Compare November 9, 2026 20:02
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch from 8f25d33 to 0588ca1 Compare November 9, 2026 20:20
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from 18f884b to b39e746 Compare November 9, 2026 20:20
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch from 0588ca1 to 09d6041 Compare November 9, 2026 21:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from b39e746 to 1548b16 Compare November 9, 2026 21:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch from 09d6041 to d5c173d Compare November 9, 2026 21:26
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch 2 times, most recently from 6799219 to b1d8e06 Compare November 9, 2026 22:03
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch 2 times, most recently from 42f95c4 to 461fd3f Compare November 9, 2026 23:18
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from b1d8e06 to 3ae5af8 Compare November 9, 2026 23:18
@huangjeff5 huangjeff5 changed the title fix(py): tool calling loop fixes, multipart unwrapping, and context propagation fix(py): unwrap multipart tool responses and propagate context through tool loops Nov 10, 2026
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch from 461fd3f to 9f173e3 Compare November 10, 2026 07:44
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from 3ae5af8 to 6491461 Compare November 10, 2026 07:44
@huangjeff5 huangjeff5 changed the title fix(py): unwrap multipart tool responses and propagate context through tool loops fix(py): 1.0 generation-loop batch: usage totals, resume history, context, prompt loader, SSE Nov 10, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #59 November 10, 2026 18:16
@huangjeff5
huangjeff5 added this pull request to stack #75 November 10, 2026 18:16
@huangjeff5
huangjeff5 removed this pull request from stack #75 November 10, 2026 18:16
@huangjeff5
huangjeff5 added this pull request to stack #76 November 10, 2026 18:16
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch from 9f173e3 to 5155fe0 Compare November 10, 2026 18:37
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from 6491461 to 7834a9d Compare November 10, 2026 18:37
@huangjeff5
huangjeff5 removed this pull request from stack #76 November 10, 2026 18:38
@huangjeff5
huangjeff5 added this pull request to stack #77 November 10, 2026 18:38
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch from 5155fe0 to 8bf395f Compare November 10, 2026 21:57
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-media-accessor branch from b0db9b6 to c3aa280 Compare November 11, 2026 02:35
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from f720783 to c0bfbec Compare November 11, 2026 02:35
@huangjeff5
huangjeff5 removed this pull request from stack #82 November 11, 2026 02:36
@huangjeff5 huangjeff5 changed the title fix(py): 1.0 generation-loop batch: usage totals, resume history, context, prompt loader, SSE feat(py): add .reasoning, ModelResponse.total_usage, and multipart Part.from_tool_response Nov 11, 2026
@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-pr3-media-accessor branch from c3aa280 to c65bb39 Compare November 11, 2026 06:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from c0bfbec to 3cb93cf 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 changed the base branch from fix/py-1.0-pr3-media-accessor to fix/py-1.0-pr2-static-typing November 11, 2026 18:06
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch from 95ec0ef to a59c6ef Compare November 11, 2026 18:38
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from 3cb93cf to 1bced54 Compare November 11, 2026 18:38
@huangjeff5
huangjeff5 added this pull request to stack #104 November 11, 2026 19:43
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr2-static-typing branch from a59c6ef to 9d037ae Compare November 12, 2026 06:38
@huangjeff5
huangjeff5 removed this pull request from stack #104 November 12, 2026 06:39
@huangjeff5
huangjeff5 changed the base branch from fix/py-1.0-pr2-static-typing to main November 12, 2026 08:01
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3-generation-loop branch from 1bced54 to b85f80c Compare November 12, 2026 08:14

@hilariie hilariie left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs a rebase - main added its own generate_loop_test.py in #83, so the new test file is an add/add conflict. There's also no test where a middleware calls next() twice; swapping sent[-1] for sent[0], or counting usage once per turn, still passes every test here. Also, the reasoning and from_tool_response tests would sit better next to the existing accessor tests in model_test.py and part_test.py. sse_failed_response_test.py doesn't exercise SSE, and the existing BoxedFailure tests are in to_sse_test.py.

Resolves the add/add conflict on generate_loop_test.py and addresses review:

- total_usage comes from a usage sink every model action reports to, so
  Fallback's direct backup call and nested generates in tools count.
- Part.from_tool_response dumps output/metadata and validates content the
  same way the tool runner does (helpers moved down into _core/_model.py).
- Drop the BoxedFailure retry_after_ms/reason change: nothing reads it.
- Add a middleware-calls-next()-twice test; move reasoning and
  from_tool_response tests into model_test.py and part_test.py.
- Drop "as JS does" / "Same as JS" comparisons from comments.
@huangjeff5

Copy link
Copy Markdown
Collaborator Author

Merged main in 4ba3255 (no force push). The two generate_loop_test.py files are combined. Added test_middleware_calling_next_twice_echoes_the_last_request_and_bills_both: it fails if sent[-1] becomes sent[0] or if usage is counted once per turn (checked both mutations locally). The reasoning test moved to model_test.py and the from_tool_response tests to part_test.py. sse_failed_response_test.py is gone because the BoxedFailure change it tested is gone.

Docs used to be inlined into the last user message in turn_request, before any wrap_model ran, so clearing request.docs in middleware didn't keep them from the model and response.request under-reported what was sent. Inlining now runs in Action._run for model actions, as in Go, so every route to a model gets it: the turn loop, Fallback's direct backup call, a judge model. augment_with_context moved to _core/_model.py.
@huangjeff5
huangjeff5 enabled auto-merge (squash) November 16, 2026 22:41
@huangjeff5
huangjeff5 merged commit 4e336b5 into main Nov 16, 2026
20 of 21 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-1.0-pr3-generation-loop branch November 16, 2026 22:48
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