telemetry-dev-bedrock 0.2.5__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telemetry-dev-bedrock
3
- Version: 0.2.5
3
+ Version: 0.3.0
4
4
  Summary: AWS Bedrock integration for telemetry.dev Python SDK
5
5
  Keywords: telemetry,opentelemetry,bedrock,aws,boto3,genai,tracing
6
6
  Author: telemetry.dev
@@ -106,7 +106,7 @@ Global instrumentation wraps `botocore.client.BaseClient._make_api_call` and fil
106
106
 
107
107
  | Option | Default | Applies to | Notes |
108
108
  | --- | --- | --- | --- |
109
- | `capture_agent_trace` | `False` | Agent Runtime streams | Aggregates trace usage and counts by default. When enabled, also attaches trace events as `td.metadata.agent_trace`, filtered as described below. |
109
+ | `capture_agent_trace` | `True` | Agent Runtime streams | Attaches the trace events of a request with `enableTrace=True` as `td.metadata.agent_trace`, filtered as described below; they hold the agent's action group calls and their results. With `False`, only trace usage and counts are kept. |
110
110
 
111
111
  `td.metadata.agent_trace` is metadata, which is cut at `max_attribute_length` when you set one (at 65,536 characters by default with `telemetry-dev` 0.3.2 or earlier) but never passed to your `mask`, so each trace event is rebuilt from an explicit allowlist instead:
112
112
 
@@ -122,7 +122,7 @@ Any other field, including unknown trace types and the AWS SDK's `$unknown` unio
122
122
  ```py
123
123
  agent = wrap_bedrock(
124
124
  boto3.client("bedrock-agent-runtime"),
125
- capture_agent_trace=True,
125
+ capture_agent_trace=False, # keep only trace usage and counts
126
126
  )
127
127
  ```
128
128
 
@@ -135,9 +135,9 @@ All instrumented AWS responses/errors include `gen_ai.response.id` from the AWS
135
135
  | `Converse` | `generation` | `chat {modelId}` | normalized input/output messages, system instructions, sampling params, usage/cache usage, finish reason, request id, retry attempts, prompt-router response model, server latency, guardrail metadata |
136
136
  | `ConverseStream` | `generation` | `chat {modelId}` | pull-through stream output, time-to-first-chunk, usage/latency from `metadata`, partial output on early break/error |
137
137
  | `InvokeModel` | `generation` or `embedding` | `chat {modelId}` / `embeddings {modelId}` | native JSON request/response bodies, provider-native sampling, provider-native usage, embedding output type, HTTP-header token fallback |
138
- | `InvokeModelWithResponseStream` | `generation` or `embedding` | `chat {modelId}` / `embeddings {modelId}` | provider-native chunk text where known, optional final `amazon-bedrock-invocationMetrics` usage |
138
+ | `InvokeModelWithResponseStream` | `generation` or `embedding` | `chat {modelId}` / `embeddings {modelId}` | provider-native chunk text where known, Anthropic Claude and Amazon Nova tool calls with their arguments, optional final `amazon-bedrock-invocationMetrics` usage |
139
139
  | `ApplyGuardrail` | `span` | `apply_guardrail {guardrailIdentifier}` | guardrail input/output, action, action reason, request id |
140
- | `InvokeAgent` / `InvokeInlineAgent` | `agent` | `invoke_agent {agentId}` / `invoke_agent {agentName}` | user input, streamed answer, session/memory ids, alias id, trace usage aggregation, trace event count, return-control output |
140
+ | `InvokeAgent` / `InvokeInlineAgent` | `agent` | `invoke_agent {agentId}` / `invoke_agent {agentName}` | user input, inline agent instruction, return-of-control results sent back, streamed answer, session/memory ids, alias id, trace usage aggregation, trace event count, return-control output |
141
141
  | `Rerank` | `span` (`rerank` operation) | `rerank {modelArn basename}` | queries, inline sources, model request fields, ranked results and scores, result counts, pagination metadata, request id |
142
142
  | `Retrieve` | `span` | `retrieve {knowledgeBaseId}` | query, retrieval results, guardrail action, result count metadata |
143
143
  | `RetrieveAndGenerate` / stream | `generation` | `retrieve_and_generate {modelArn basename}` | input text, generated text, citations count, session id, guardrail action |
@@ -169,7 +169,7 @@ InvokeModel captures provider-native JSON bodies verbatim. A body whose content
169
169
  - Requests are never modified.
170
170
  - Streams end spans exactly once. Exhaustion records full output and finish reason; early `break`, `close()`, `GeneratorExit`, or stream errors record partial output and set `telemetry.dev.capture.truncated`.
171
171
  - Event-stream reconstruction and streamed `InvokeModel` bodies are kept up to 16 MiB, and all streams in flight share the `max_stream_bytes` bound of the core (64 MiB by default). These bounds need a `telemetry-dev` core with `max_stream_bytes`; with an older core, each stream keeps up to 64 KiB and 1,024 items. `InvokeModel` bodies and `Rerank` inputs and results are retained up to 16 MiB each; a body over that bound records no output and sets `telemetry.dev.capture.truncated`. The configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs.
172
- - A stream cut at its retention bound, closed early, or failed sets `telemetry.dev.capture.truncated`. An event that fails to map, or a failure while the time to first chunk or an output-chunk timestamp is recorded, is reported to `on_error`; only the first such failure of a stream is reported. A failure before the event's output is kept also sets the attribute, and no later text or content is kept; so does an `InvokeModel` stream chunk that is not UTF-8 or not JSON (a blank chunk holds no output and is skipped). Agent text is decoded across chunks, so a character split between two chunks is kept whole; Agent text that is not UTF-8, or a stream that ends inside a character, loses that text like a failed event and is reported; an Agent `returnControl` that arrives later still replaces the text output whole, also with a mask configured. A failure in the event's usage, metrics, or Agent trace summaries loses only that metadata and does not set the attribute, and so does a timing failure. A failure while Agent trace content is captured (`capture_agent_trace`) loses that trace and sets the attribute, but later text is still kept, also with a mask configured. A stream whose output fails to map when it ends records no output and sets the attribute. An `InvokeModel` body that is closed before it is fully read, whose read fails, or that fails to map (for example, a body that is not UTF-8 or not JSON) records no output and sets the attribute too; a mapping failure is reported to `on_error`. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value. Agent trace events share the bound, but dropping them only sets the attribute; Agent text is omitted only when a text chunk was dropped or failed to map, or the stream was closed early or failed. A normally exhausted Agent stream that returned control keeps its complete `returnControl` output even if earlier text or trace metadata passed the bound; an early close or failure still omits the output when a mask is configured.
172
+ - A stream cut at its retention bound, closed early, or failed sets `telemetry.dev.capture.truncated`. An event that fails to map, or a failure while the time to first chunk or an output-chunk timestamp is recorded, is reported to `on_error`; only the first such failure of a stream is reported. A failure before the event's output is kept also sets the attribute, and no later text or content is kept; so does an `InvokeModel` stream chunk that is not UTF-8 or not JSON (a blank chunk holds no output and is skipped). Agent text is decoded across chunks, so a character split between two chunks is kept whole; Agent text that is not UTF-8, or a stream that ends inside a character, loses that text like a failed event and is reported; an Agent `returnControl` that arrives later still replaces the text output whole, also with a mask configured. A failure in the event's usage, metrics, or Agent trace summaries loses only that metadata and does not set the attribute, and so does a timing failure. A failure while Agent trace content is captured (`capture_agent_trace`) loses that trace and sets the attribute, but later text is still kept, also with a mask configured. A stream whose output fails to map when it ends records no output and sets the attribute. An `InvokeModel` body that is closed before it is fully read, whose read fails, or that fails to map (for example, a body that is not UTF-8 or not JSON) records no output and sets the attribute too; a mapping failure is reported to `on_error`. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value. Agent trace events share the bound but may use at most half of it, and dropping them only sets the attribute (after a dropped trace, later traces are dropped too); Agent text is omitted only when a text chunk was dropped or failed to map, or the stream was closed early or failed. A normally exhausted Agent stream that returned control keeps its complete `returnControl` output even if earlier text or trace metadata passed the bound; an early close or failure still omits the output when a mask is configured.
173
173
  - boto3 has no async client. `aiobotocore` is a separate package and is out of scope.
174
174
 
175
175
  ## Coverage gaps
@@ -83,7 +83,7 @@ Global instrumentation wraps `botocore.client.BaseClient._make_api_call` and fil
83
83
 
84
84
  | Option | Default | Applies to | Notes |
85
85
  | --- | --- | --- | --- |
86
- | `capture_agent_trace` | `False` | Agent Runtime streams | Aggregates trace usage and counts by default. When enabled, also attaches trace events as `td.metadata.agent_trace`, filtered as described below. |
86
+ | `capture_agent_trace` | `True` | Agent Runtime streams | Attaches the trace events of a request with `enableTrace=True` as `td.metadata.agent_trace`, filtered as described below; they hold the agent's action group calls and their results. With `False`, only trace usage and counts are kept. |
87
87
 
88
88
  `td.metadata.agent_trace` is metadata, which is cut at `max_attribute_length` when you set one (at 65,536 characters by default with `telemetry-dev` 0.3.2 or earlier) but never passed to your `mask`, so each trace event is rebuilt from an explicit allowlist instead:
89
89
 
@@ -99,7 +99,7 @@ Any other field, including unknown trace types and the AWS SDK's `$unknown` unio
99
99
  ```py
100
100
  agent = wrap_bedrock(
101
101
  boto3.client("bedrock-agent-runtime"),
102
- capture_agent_trace=True,
102
+ capture_agent_trace=False, # keep only trace usage and counts
103
103
  )
104
104
  ```
105
105
 
@@ -112,9 +112,9 @@ All instrumented AWS responses/errors include `gen_ai.response.id` from the AWS
112
112
  | `Converse` | `generation` | `chat {modelId}` | normalized input/output messages, system instructions, sampling params, usage/cache usage, finish reason, request id, retry attempts, prompt-router response model, server latency, guardrail metadata |
113
113
  | `ConverseStream` | `generation` | `chat {modelId}` | pull-through stream output, time-to-first-chunk, usage/latency from `metadata`, partial output on early break/error |
114
114
  | `InvokeModel` | `generation` or `embedding` | `chat {modelId}` / `embeddings {modelId}` | native JSON request/response bodies, provider-native sampling, provider-native usage, embedding output type, HTTP-header token fallback |
115
- | `InvokeModelWithResponseStream` | `generation` or `embedding` | `chat {modelId}` / `embeddings {modelId}` | provider-native chunk text where known, optional final `amazon-bedrock-invocationMetrics` usage |
115
+ | `InvokeModelWithResponseStream` | `generation` or `embedding` | `chat {modelId}` / `embeddings {modelId}` | provider-native chunk text where known, Anthropic Claude and Amazon Nova tool calls with their arguments, optional final `amazon-bedrock-invocationMetrics` usage |
116
116
  | `ApplyGuardrail` | `span` | `apply_guardrail {guardrailIdentifier}` | guardrail input/output, action, action reason, request id |
117
- | `InvokeAgent` / `InvokeInlineAgent` | `agent` | `invoke_agent {agentId}` / `invoke_agent {agentName}` | user input, streamed answer, session/memory ids, alias id, trace usage aggregation, trace event count, return-control output |
117
+ | `InvokeAgent` / `InvokeInlineAgent` | `agent` | `invoke_agent {agentId}` / `invoke_agent {agentName}` | user input, inline agent instruction, return-of-control results sent back, streamed answer, session/memory ids, alias id, trace usage aggregation, trace event count, return-control output |
118
118
  | `Rerank` | `span` (`rerank` operation) | `rerank {modelArn basename}` | queries, inline sources, model request fields, ranked results and scores, result counts, pagination metadata, request id |
119
119
  | `Retrieve` | `span` | `retrieve {knowledgeBaseId}` | query, retrieval results, guardrail action, result count metadata |
120
120
  | `RetrieveAndGenerate` / stream | `generation` | `retrieve_and_generate {modelArn basename}` | input text, generated text, citations count, session id, guardrail action |
@@ -146,7 +146,7 @@ InvokeModel captures provider-native JSON bodies verbatim. A body whose content
146
146
  - Requests are never modified.
147
147
  - Streams end spans exactly once. Exhaustion records full output and finish reason; early `break`, `close()`, `GeneratorExit`, or stream errors record partial output and set `telemetry.dev.capture.truncated`.
148
148
  - Event-stream reconstruction and streamed `InvokeModel` bodies are kept up to 16 MiB, and all streams in flight share the `max_stream_bytes` bound of the core (64 MiB by default). These bounds need a `telemetry-dev` core with `max_stream_bytes`; with an older core, each stream keeps up to 64 KiB and 1,024 items. `InvokeModel` bodies and `Rerank` inputs and results are retained up to 16 MiB each; a body over that bound records no output and sets `telemetry.dev.capture.truncated`. The configured `max_attribute_length` does not shrink these retention bounds; the core applies it to the exported attribute after the mask runs.
149
- - A stream cut at its retention bound, closed early, or failed sets `telemetry.dev.capture.truncated`. An event that fails to map, or a failure while the time to first chunk or an output-chunk timestamp is recorded, is reported to `on_error`; only the first such failure of a stream is reported. A failure before the event's output is kept also sets the attribute, and no later text or content is kept; so does an `InvokeModel` stream chunk that is not UTF-8 or not JSON (a blank chunk holds no output and is skipped). Agent text is decoded across chunks, so a character split between two chunks is kept whole; Agent text that is not UTF-8, or a stream that ends inside a character, loses that text like a failed event and is reported; an Agent `returnControl` that arrives later still replaces the text output whole, also with a mask configured. A failure in the event's usage, metrics, or Agent trace summaries loses only that metadata and does not set the attribute, and so does a timing failure. A failure while Agent trace content is captured (`capture_agent_trace`) loses that trace and sets the attribute, but later text is still kept, also with a mask configured. A stream whose output fails to map when it ends records no output and sets the attribute. An `InvokeModel` body that is closed before it is fully read, whose read fails, or that fails to map (for example, a body that is not UTF-8 or not JSON) records no output and sets the attribute too; a mapping failure is reported to `on_error`. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value. Agent trace events share the bound, but dropping them only sets the attribute; Agent text is omitted only when a text chunk was dropped or failed to map, or the stream was closed early or failed. A normally exhausted Agent stream that returned control keeps its complete `returnControl` output even if earlier text or trace metadata passed the bound; an early close or failure still omits the output when a mask is configured.
149
+ - A stream cut at its retention bound, closed early, or failed sets `telemetry.dev.capture.truncated`. An event that fails to map, or a failure while the time to first chunk or an output-chunk timestamp is recorded, is reported to `on_error`; only the first such failure of a stream is reported. A failure before the event's output is kept also sets the attribute, and no later text or content is kept; so does an `InvokeModel` stream chunk that is not UTF-8 or not JSON (a blank chunk holds no output and is skipped). Agent text is decoded across chunks, so a character split between two chunks is kept whole; Agent text that is not UTF-8, or a stream that ends inside a character, loses that text like a failed event and is reported; an Agent `returnControl` that arrives later still replaces the text output whole, also with a mask configured. A failure in the event's usage, metrics, or Agent trace summaries loses only that metadata and does not set the attribute, and so does a timing failure. A failure while Agent trace content is captured (`capture_agent_trace`) loses that trace and sets the attribute, but later text is still kept, also with a mask configured. A stream whose output fails to map when it ends records no output and sets the attribute. An `InvokeModel` body that is closed before it is fully read, whose read fails, or that fails to map (for example, a body that is not UTF-8 or not JSON) records no output and sets the attribute too; a mapping failure is reported to `on_error`. With a mask configured, incomplete reconstructed output is omitted because the mask cannot inspect the complete value. Agent trace events share the bound but may use at most half of it, and dropping them only sets the attribute (after a dropped trace, later traces are dropped too); Agent text is omitted only when a text chunk was dropped or failed to map, or the stream was closed early or failed. A normally exhausted Agent stream that returned control keeps its complete `returnControl` output even if earlier text or trace metadata passed the bound; an early close or failure still omits the output when a mask is configured.
150
150
  - boto3 has no async client. `aiobotocore` is a separate package and is out of scope.
151
151
 
152
152
  ## Coverage gaps
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev-bedrock"
3
- version = "0.2.5"
3
+ version = "0.3.0"
4
4
  description = "AWS Bedrock integration for telemetry.dev Python SDK"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev-bedrock"
3
- version = "0.2.5"
3
+ version = "0.3.0"
4
4
  description = "AWS Bedrock integration for telemetry.dev Python SDK"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -2,6 +2,6 @@ from __future__ import annotations
2
2
 
3
3
  from ._instrument import instrument_bedrock, uninstrument_bedrock, wrap_bedrock
4
4
 
5
- __version__ = "0.2.5"
5
+ __version__ = "0.3.0"
6
6
 
7
7
  __all__ = ["__version__", "instrument_bedrock", "uninstrument_bedrock", "wrap_bedrock"]
@@ -45,7 +45,7 @@ if hasattr(os, "register_at_fork") and "_install_fork_hook" not in globals():
45
45
  os.register_at_fork(after_in_child=_reset_install_lock_in_child)
46
46
 
47
47
 
48
- def wrap_bedrock(client: _T, *, capture_agent_trace: bool = False) -> _T:
48
+ def wrap_bedrock(client: _T, *, capture_agent_trace: bool = True) -> _T:
49
49
  with _install_lock:
50
50
  if getattr(client, _WRAPPED_ATTR, False):
51
51
  return client
@@ -70,7 +70,7 @@ def wrap_bedrock(client: _T, *, capture_agent_trace: bool = False) -> _T:
70
70
  return client
71
71
 
72
72
 
73
- def instrument_bedrock(*, capture_agent_trace: bool = False) -> None:
73
+ def instrument_bedrock(*, capture_agent_trace: bool = True) -> None:
74
74
  with _install_lock:
75
75
  global _original_api_call, _patched_api_call
76
76
  if _original_api_call is not None:
@@ -151,19 +151,34 @@ def _apply_response(_params: dict[str, Any], response: dict[str, Any]) -> dict[s
151
151
  )
152
152
 
153
153
 
154
- def _agent_input(text: Any) -> list[dict[str, Any]] | None:
155
- return (
156
- [{"role": "user", "parts": [{"type": "text", "content": text}]}]
157
- if isinstance(text, str)
158
- else None
159
- )
154
+ def _agent_input(text: Any, session_state: Any = None) -> list[dict[str, Any]] | None:
155
+ """The user's text or, after a return of control, the results of the actions the app ran,
156
+ which the request carries in ``returnControlInvocationResults`` of its session state. The
157
+ agent ignores ``inputText`` when the request carries those results (InvokeAgent and
158
+ InvokeInlineAgent API reference), so the text is left out then."""
159
+ session = session_state if isinstance(session_state, dict) else {}
160
+ results = session.get("returnControlInvocationResults")
161
+ invocation_id = session.get("invocationId")
162
+ if isinstance(results, list) and results:
163
+ return [
164
+ {
165
+ "role": "tool",
166
+ "parts": [
167
+ clean({"type": "tool_call_response", "id": invocation_id, "response": result})
168
+ for result in results
169
+ ],
170
+ }
171
+ ]
172
+ if isinstance(text, str) and text:
173
+ return [{"role": "user", "parts": [{"type": "text", "content": text}]}]
174
+ return None
160
175
 
161
176
 
162
177
  def _agent_request(params: dict[str, Any]) -> dict[str, Any]:
163
178
  return clean(
164
179
  {
165
180
  "provider": PROVIDER,
166
- "input": _agent_input(params.get("inputText")),
181
+ "input": _agent_input(params.get("inputText"), params.get("sessionState")),
167
182
  "agent_id": params.get("agentId"),
168
183
  "metadata": clean(
169
184
  {
@@ -182,7 +197,8 @@ def _inline_agent_request(params: dict[str, Any]) -> dict[str, Any]:
182
197
  {
183
198
  "provider": PROVIDER,
184
199
  "model": params.get("foundationModel"),
185
- "input": _agent_input(params.get("inputText")),
200
+ "input": _agent_input(params.get("inputText"), params.get("inlineSessionState")),
201
+ "system_instructions": params.get("instruction"),
186
202
  "agent_name": params.get("agentName"),
187
203
  "metadata": clean({"bedrock_session_id": params.get("sessionId")}) or None,
188
204
  }
@@ -502,13 +502,14 @@ class InvokeModelStreamState(StreamState):
502
502
  # Invocation metrics have no documented compaction exclusion.
503
503
  if base_key in self.final_usage or base_key not in self.usage:
504
504
  usage[key] = usage.get(key, 0) + value
505
+ tool_calls = _tool_calls_from_provider_chunks(self.chunks)
505
506
  output: Any = self.chunks
506
- if text:
507
+ if text or tool_calls:
507
508
  output = [
508
509
  clean(
509
510
  {
510
511
  "role": "assistant",
511
- "parts": [{"type": "text", "content": text}],
512
+ "parts": ([{"type": "text", "content": text}] if text else []) + tool_calls,
512
513
  "finish_reason": self.finish_reason,
513
514
  }
514
515
  )
@@ -568,6 +569,9 @@ class AgentStreamState(StreamState):
568
569
  self.saw_return_control = False
569
570
  self.return_control_rejected = False
570
571
  self.traces: list[Any] = []
572
+ self.traces_cut = False
573
+ self.metadata_bytes = 0
574
+ self.metadata_items = 0
571
575
  # Metadata bypasses the capture flags and the mask, so trace content is filtered here,
572
576
  # and a mask that cannot see it withholds it.
573
577
  client = telemetry_dev.get_client()
@@ -607,7 +611,7 @@ class AgentStreamState(StreamState):
607
611
  trace = event.get("trace") if isinstance(event.get("trace"), dict) else None
608
612
  if trace:
609
613
  self.trace_count += 1
610
- if self.capture_trace:
614
+ if self.capture_trace and not self.traces_cut:
611
615
  try:
612
616
  retained = _project_trace(trace, _TRACE_PART, self.trace_capture)
613
617
  except Exception:
@@ -615,10 +619,48 @@ class AgentStreamState(StreamState):
615
619
  # text is, so later text is still kept.
616
620
  self.metadata_lost = True
617
621
  raise
618
- if self.budget.accept(retained):
622
+ # Once one trace is dropped, later ones are too, so the kept traces are a prefix.
623
+ if self._accept_metadata(retained):
619
624
  self.traces.append(retained)
625
+ else:
626
+ self.traces_cut = True
627
+ self.metadata_lost = True
620
628
  self._collect_trace(trace)
621
629
 
630
+ def _accept_metadata(self, value: Any) -> bool:
631
+ """As ``budget.accept``, for agent traces: they may use at most half of the bound's bytes
632
+ and items, and a value that does not fit is dropped without marking the budget
633
+ truncated, so the text that comes later still fits."""
634
+ budget = self.budget
635
+ if budget.truncated:
636
+ return False
637
+ room = min(
638
+ budget.max_bytes - budget.bytes_used, budget.max_bytes // 2 - self.metadata_bytes
639
+ )
640
+ # Older cores also bound a stream budget's items.
641
+ item_room = min(
642
+ budget.max_items - budget.items_used, budget.max_items // 2 - self.metadata_items
643
+ )
644
+ if room <= 0 or item_room <= 0:
645
+ return False
646
+ measure = telemetry_dev.CaptureBudget(max_bytes=room, max_items=item_room)
647
+ if not measure.accept(value):
648
+ return False
649
+ total = budget.bytes_used + measure.bytes_used
650
+ # Older cores have no reserve_bytes and bound each budget on its own.
651
+ reserve = getattr(budget, "reserve_bytes", None)
652
+ if callable(reserve):
653
+ if not reserve(total):
654
+ return False
655
+ elif total > budget.max_bytes:
656
+ return False
657
+ else:
658
+ budget.bytes_used = total
659
+ budget.items_used += measure.items_used
660
+ self.metadata_bytes += measure.bytes_used
661
+ self.metadata_items += measure.items_used
662
+ return True
663
+
622
664
  def finish(self, *, partial: bool) -> dict[str, Any]:
623
665
  # A stream cut short may stop inside a character; that is already an incomplete capture.
624
666
  if not partial:
@@ -999,15 +1041,75 @@ def _int_value(value: Any) -> int | None:
999
1041
  return None
1000
1042
 
1001
1043
 
1044
+ def _tool_calls_from_provider_chunks(chunks: list[Any]) -> list[dict[str, Any]]:
1045
+ """The streamed tool calls, by content block: Anthropic Claude ``content_block_start`` with a
1046
+ ``tool_use`` block and ``input_json_delta``, or Amazon Nova ``contentBlockStart.start.toolUse``
1047
+ and ``contentBlockDelta.delta.toolUse.input``. The arguments arrive as JSON text in pieces."""
1048
+ calls: dict[int, dict[str, Any]] = {}
1049
+ for value in chunks:
1050
+ if not isinstance(value, dict):
1051
+ continue
1052
+ nova_start = _dict(value.get("contentBlockStart"))
1053
+ nova_delta = _dict(value.get("contentBlockDelta"))
1054
+ index = value.get("index")
1055
+ if not isinstance(index, int):
1056
+ index = nova_start.get("contentBlockIndex", nova_delta.get("contentBlockIndex"))
1057
+ if not isinstance(index, int):
1058
+ continue
1059
+ block = _dict(value.get("content_block"))
1060
+ nova_tool = _dict(_dict(nova_start.get("start")).get("toolUse"))
1061
+ if value.get("type") == "content_block_start" and block.get("type") == "tool_use":
1062
+ calls[index] = {"id": block.get("id"), "name": block.get("name"), "pieces": []}
1063
+ elif nova_tool:
1064
+ calls[index] = {
1065
+ "id": nova_tool.get("toolUseId"),
1066
+ "name": nova_tool.get("name"),
1067
+ "pieces": [],
1068
+ }
1069
+ elif index in calls:
1070
+ delta = _dict(value.get("delta"))
1071
+ nova_piece = _dict(_dict(nova_delta.get("delta")).get("toolUse")).get("input")
1072
+ piece = (
1073
+ delta.get("partial_json")
1074
+ if value.get("type") == "content_block_delta"
1075
+ and delta.get("type") == "input_json_delta"
1076
+ else nova_piece
1077
+ )
1078
+ if isinstance(piece, str):
1079
+ calls[index]["pieces"].append(piece)
1080
+ parts: list[dict[str, Any]] = []
1081
+ for call in calls.values():
1082
+ arguments: Any = {}
1083
+ # Joined once: appending to the stored string would copy it for every piece.
1084
+ raw = "".join(call["pieces"])
1085
+ if raw:
1086
+ try:
1087
+ arguments = json.loads(raw)
1088
+ except json.JSONDecodeError:
1089
+ arguments = raw
1090
+ parts.append(
1091
+ clean(
1092
+ {
1093
+ "type": "tool_call",
1094
+ "id": call["id"],
1095
+ "name": call["name"],
1096
+ "arguments": arguments,
1097
+ }
1098
+ )
1099
+ )
1100
+ return parts
1101
+
1102
+
1103
+ def _dict(value: Any) -> dict[str, Any]:
1104
+ return value if isinstance(value, dict) else {}
1105
+
1106
+
1002
1107
  def _text_from_provider_chunk(value: Any) -> str:
1003
1108
  if not isinstance(value, dict):
1004
1109
  return ""
1005
1110
  delta = value.get("delta") if isinstance(value.get("delta"), dict) else {}
1006
- block_delta = (
1007
- value.get("content_block_delta")
1008
- if isinstance(value.get("content_block_delta"), dict)
1009
- else {}
1010
- )
1111
+ # Amazon Nova nests its text delta under contentBlockDelta.
1112
+ block_delta = _dict(value.get("content_block_delta")) or _dict(value.get("contentBlockDelta"))
1011
1113
  nested = block_delta.get("delta") if isinstance(block_delta.get("delta"), dict) else {}
1012
1114
  for candidate in (
1013
1115
  value.get("outputText"),