Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Add 'thinking blocks' to stream chunk builder + remove experimental 'by_tag' metrics on prometheus (fix cardinality issue) (#12395)

Krish Dholakia76c9df1f9106
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index 0583150b961..050eb0ed536 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -278,16 +278,7 @@ class PrometheusLogger(CustomLogger):
"litellm_deployment_failure_responses"
),
)
- self.litellm_deployment_failure_by_tag_responses = self._counter_factory(
- "litellm_deployment_failure_by_tag_responses",
- "Total number of failed LLM API calls for a specific LLM deploymeny by custom metadata tags",
- labelnames=[
- UserAPIKeyLabelNames.REQUESTED_MODEL.value,
- UserAPIKeyLabelNames.TAG.value,
- ]
- + _logged_llm_labels
- + EXCEPTION_LABELS,
- )
+
self.litellm_deployment_total_requests = self._counter_factory(
name="litellm_deployment_total_requests",
documentation="LLM Deployment Analytics - Total number of LLM API calls via litellm - success + failure",
@@ -356,37 +347,39 @@ class PrometheusLogger(CustomLogger):
# Parse and validate all configuration groups
parsed_configs = []
self.enabled_metrics = set()
-
+
for group_config in config:
# Validate configuration using Pydantic
if isinstance(group_config, dict):
parsed_config = PrometheusMetricsConfig(**group_config)
else:
parsed_config = group_config
-
+
parsed_configs.append(parsed_config)
self.enabled_metrics.update(parsed_config.metrics)
# Validate all configurations
validation_results = self._validate_all_configurations(parsed_configs)
-
+
if validation_results.has_errors:
self._pretty_print_validation_errors(validation_results)
- error_message = "Configuration validation failed:\n" + "\n".join(validation_results.all_error_messages)
+ error_message = "Configuration validation failed:\n" + "\n".join(
+ validation_results.all_error_messages
+ )
raise ValueError(error_message)
# Build label filters from valid configurations
label_filters = self._build_label_filters(parsed_configs)
-
+
# Pretty print the processed configuration
self._pretty_print_prometheus_config(label_filters)
return label_filters
-
+
def _validate_all_configurations(self, parsed_configs: List) -> ValidationResults:
"""Validate all metric configurations and return collected errors"""
metric_errors = []
label_errors = []
-
+
for config in parsed_configs:
for metric_name in config.metrics:
# Validate metric name
@@ -394,54 +387,63 @@ class PrometheusLogger(CustomLogger):
if metric_error:
metric_errors.append(metric_error)
continue # Skip label validation if metric name is invalid
-
+
# Validate labels if provided
if config.include_labels:
- label_error = self._validate_single_metric_labels(metric_name, config.include_labels)
+ label_error = self._validate_single_metric_labels(
+ metric_name, config.include_labels
+ )
if label_error:
label_errors.append(label_error)
-
+
return ValidationResults(metric_errors=metric_errors, label_errors=label_errors)
-
- def _validate_single_metric_name(self, metric_name: str) -> Optional[MetricValidationError]:
+
+ def _validate_single_metric_name(
+ self, metric_name: str
+ ) -> Optional[MetricValidationError]:
"""Validate a single metric name"""
from typing import get_args
+
if metric_name not in set(get_args(DEFINED_PROMETHEUS_METRICS)):
return MetricValidationError(
metric_name=metric_name,
- valid_metrics=get_args(DEFINED_PROMETHEUS_METRICS)
+ valid_metrics=get_args(DEFINED_PROMETHEUS_METRICS),
)
return None
- def _validate_single_metric_labels(self, metric_name: str, labels: List[str]) -> Optional[LabelValidationError]:
+ def _validate_single_metric_labels(
+ self, metric_name: str, labels: List[str]
+ ) -> Optional[LabelValidationError]:
"""Validate labels for a single metric"""
from typing import cast
# Get valid labels for this metric from PrometheusMetricLabels
- valid_labels = PrometheusMetricLabels.get_labels(cast(DEFINED_PROMETHEUS_METRICS, metric_name))
-
+ valid_labels = PrometheusMetricLabels.get_labels(
+ cast(DEFINED_PROMETHEUS_METRICS, metric_name)
+ )
+
# Find invalid labels
invalid_labels = [label for label in labels if label not in valid_labels]
-
+
if invalid_labels:
return LabelValidationError(
metric_name=metric_name,
invalid_labels=invalid_labels,
- valid_labels=valid_labels
+ valid_labels=valid_labels,
)
return None
-
+
def _build_label_filters(self, parsed_configs: List) -> Dict[str, List[str]]:
"""Build label filters from validated configurations"""
label_filters = {}
-
+
for config in parsed_configs:
for metric_name in config.metrics:
if config.include_labels:
# Only add if metric name is valid (validation already passed)
if self._validate_single_metric_name(metric_name) is None:
label_filters[metric_name] = config.include_labels
-
+
return label_filters
def _validate_configured_metric_labels(self, metric_name: str, labels: List[str]):
@@ -455,17 +457,19 @@ class PrometheusLogger(CustomLogger):
self._pretty_print_invalid_labels_error(
metric_name=label_error.metric_name,
invalid_labels=label_error.invalid_labels,
- valid_labels=label_error.valid_labels
+ valid_labels=label_error.valid_labels,
)
raise ValueError(label_error.message)
-
+
return True
-
+
#########################################################
# Pretty print functions
#########################################################
- def _pretty_print_validation_errors(self, validation_results: ValidationResults) -> None:
+ def _pretty_print_validation_errors(
+ self, validation_results: ValidationResults
+ ) -> None:
"""Pretty print all validation errors using rich"""
try:
from rich.console import Console
@@ -484,15 +488,19 @@ class PrometheusLogger(CustomLogger):
# Show invalid metric names if any
if validation_results.metric_errors:
- invalid_metrics = [e.metric_name for e in validation_results.metric_errors]
- valid_metrics = validation_results.metric_errors[0].valid_metrics # All should have same valid metrics
-
+ invalid_metrics = [
+ e.metric_name for e in validation_results.metric_errors
+ ]
+ valid_metrics = validation_results.metric_errors[
+ 0
+ ].valid_metrics # All should have same valid metrics
+
metrics_error_text = Text(
- f"Invalid Metric Names: {', '.join(invalid_metrics)}",
- style="bold red"
+ f"Invalid Metric Names: {', '.join(invalid_metrics)}",
+ style="bold red",
)
console.print(Panel(metrics_error_text, border_style="red"))
-
+
metrics_table = Table(
title="📊 Valid Metric Names",
show_header=True,
@@ -500,7 +508,9 @@ class PrometheusLogger(CustomLogger):
title_justify="left",
border_style="green",
)
- metrics_table.add_column("Available Metrics", style="cyan", no_wrap=True)
+ metrics_table.add_column(
+ "Available Metrics", style="cyan", no_wrap=True
+ )
for metric in sorted(valid_metrics):
metrics_table.add_row(metric)
@@ -511,11 +521,11 @@ class PrometheusLogger(CustomLogger):
if validation_results.label_errors:
for error in validation_results.label_errors:
labels_error_text = Text(
- f"Invalid Labels for '{error.metric_name}': {', '.join(error.invalid_labels)}",
- style="bold red"
+ f"Invalid Labels for '{error.metric_name}': {', '.join(error.invalid_labels)}",
+ style="bold red",
)
console.print(Panel(labels_error_text, border_style="red"))
-
+
labels_table = Table(
title=f"🏷️ Valid Labels for '{error.metric_name}'",
show_header=True,
@@ -553,8 +563,8 @@ class PrometheusLogger(CustomLogger):
# Create error panel title
title = Text(
- f"🚨🚨 Invalid Labels for Metric: '{metric_name}'\nInvalid labels: {', '.join(invalid_labels)}\nPlease specify only valid labels below",
- style="bold red"
+ f"🚨🚨 Invalid Labels for Metric: '{metric_name}'\nInvalid labels: {', '.join(invalid_labels)}\nPlease specify only valid labels below",
+ style="bold red",
)
# Create valid labels table
@@ -581,7 +591,7 @@ class PrometheusLogger(CustomLogger):
verbose_logger.error(
f"Invalid labels for metric '{metric_name}': {invalid_labels}. Valid labels: {sorted(valid_labels)}"
)
-
+
def _pretty_print_invalid_metric_error(
self, invalid_metric_name: str, valid_metrics: tuple
) -> None:
@@ -595,7 +605,10 @@ class PrometheusLogger(CustomLogger):
console = Console()
# Create error panel title
- title = Text(f"🚨🚨 Invalid Metric Name: '{invalid_metric_name}'\nPlease specify one of the allowed metrics below", style="bold red")
+ title = Text(
+ f"🚨🚨 Invalid Metric Name: '{invalid_metric_name}'\nPlease specify one of the allowed metrics below",
+ style="bold red",
+ )
# Create valid metrics table
metrics_table = Table(
@@ -621,7 +634,7 @@ class PrometheusLogger(CustomLogger):
verbose_logger.error(
f"Invalid metric name: {invalid_metric_name}. Valid metrics: {sorted(valid_metrics)}"
)
-
+
#########################################################
# End of pretty print functions
#########################################################
@@ -633,8 +646,8 @@ class PrometheusLogger(CustomLogger):
error = self._validate_single_metric_name(metric_name)
if error:
self._pretty_print_invalid_metric_error(
- invalid_metric_name=error.metric_name,
- valid_metrics=error.valid_metrics)
+ invalid_metric_name=error.metric_name, valid_metrics=error.valid_metrics
+ )
raise ValueError(error.message)
def _pretty_print_prometheus_config(
@@ -707,7 +720,6 @@ class PrometheusLogger(CustomLogger):
)
verbose_logger.info(f"Label filters: {label_filters}")
-
def _is_metric_enabled(self, metric_name: str) -> bool:
"""Check if a metric is enabled based on configuration"""
# If no specific configuration is provided, enable all metrics (default behavior)
@@ -1362,27 +1374,6 @@ class PrometheusLogger(CustomLogger):
)
self.litellm_deployment_failure_responses.labels(**_labels).inc()
- # tag based tracking
- if standard_logging_payload is not None and isinstance(
- standard_logging_payload, dict
- ):
- _tags = standard_logging_payload["request_tags"]
- for tag in _tags:
- self.litellm_deployment_failure_by_tag_responses.labels(
- **{
- UserAPIKeyLabelNames.REQUESTED_MODEL.value: model_group,
- UserAPIKeyLabelNames.TAG.value: tag,
- UserAPIKeyLabelNames.v2_LITELLM_MODEL_NAME.value: litellm_model_name,
- UserAPIKeyLabelNames.MODEL_ID.value: model_id,
- UserAPIKeyLabelNames.API_BASE.value: api_base,
- UserAPIKeyLabelNames.API_PROVIDER.value: llm_provider,
- UserAPIKeyLabelNames.EXCEPTION_CLASS.value: exception.__class__.__name__,
- UserAPIKeyLabelNames.EXCEPTION_STATUS.value: str(
- getattr(exception, "status_code", None)
- ),
- }
- ).inc()
-
_labels = prometheus_label_factory(
supported_enum_labels=self.get_labels_for_metric(
metric_name="litellm_deployment_total_requests"
diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
index 8f46f6b7141..fb919afd49d 100644
--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py
@@ -1,6 +1,6 @@
import base64
import time
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union, cast
from litellm.types.llms.openai import (
ChatCompletionAssistantContentValue,
@@ -25,6 +25,10 @@ if TYPE_CHECKING:
from litellm.types.litellm_core_utils.streaming_chunk_builder_utils import (
UsagePerChunk,
)
+ from litellm.types.llms.openai import (
+ ChatCompletionRedactedThinkingBlock,
+ ChatCompletionThinkingBlock,
+ )
class ChunkProcessor:
@@ -217,6 +221,66 @@ class ChunkProcessor:
# Update the "content" field within the response dictionary
return combined_content
+ def get_combined_thinking_content(
+ self, chunks: List[Dict[str, Any]]
+ ) -> Optional[
+ List[
+ Union["ChatCompletionThinkingBlock", "ChatCompletionRedactedThinkingBlock"]
+ ]
+ ]:
+ from litellm.types.llms.openai import (
+ ChatCompletionRedactedThinkingBlock,
+ ChatCompletionThinkingBlock,
+ )
+
+ thinking_blocks: List[
+ Union["ChatCompletionThinkingBlock", "ChatCompletionRedactedThinkingBlock"]
+ ] = []
+ combined_thinking_text: Optional[str] = None
+ data: Optional[str] = None
+ signature: Optional[str] = None
+ type: Literal["thinking", "redacted_thinking"] = "thinking"
+ for chunk in chunks:
+ choices = chunk["choices"]
+ for choice in choices:
+ delta = choice.get("delta", {})
+ thinking = delta.get("thinking_blocks", None)
+ if thinking and isinstance(thinking, list):
+ for thinking_block in thinking:
+ thinking_type = thinking_block.get("type", None)
+ if thinking_type and thinking_type == "redacted_thinking":
+ type = "redacted_thinking"
+ data = thinking_block.get("data", None)
+ else:
+ type = "thinking"
+ thinking_text = thinking_block.get("thinking", None)
+ if thinking_text:
+ if combined_thinking_text is None:
+ combined_thinking_text = ""
+
+ combined_thinking_text += thinking_text
+ signature = thinking_block.get("signature", None)
+
+ if combined_thinking_text and type == "thinking" and signature:
+ thinking_blocks.append(
+ ChatCompletionThinkingBlock(
+ type=type,
+ thinking=combined_thinking_text,
+ signature=signature,
+ )
+ )
+ elif data and type == "redacted_thinking":
+ thinking_blocks.append(
+ ChatCompletionRedactedThinkingBlock(
+ type=type,
+ data=data,
+ )
+ )
+
+ if len(thinking_blocks) > 0:
+ return thinking_blocks
+ return None
+
def get_combined_reasoning_content(
self, chunks: List[Dict[str, Any]]
) -> ChatCompletionAssistantContentValue:
diff --git a/litellm/main.py b/litellm/main.py
index 41e8a600e5f..98dc298e36e 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -453,7 +453,6 @@ async def acompletion(
#########################################################
#########################################################
-
# Adjusted to use explicit arguments instead of *args and **kwargs
completion_kwargs = {
"model": model,
@@ -510,13 +509,17 @@ async def acompletion(
)
return response
- ### APPLY MOCK DELAY ###
+ ### APPLY MOCK DELAY ###
mock_delay = kwargs.get("mock_delay")
mock_response = kwargs.get("mock_response")
mock_tool_calls = kwargs.get("mock_tool_calls")
mock_timeout = kwargs.get("mock_timeout")
- if mock_delay and should_run_mock_completion(mock_response=mock_response, mock_tool_calls=mock_tool_calls, mock_timeout=mock_timeout):
+ if mock_delay and should_run_mock_completion(
+ mock_response=mock_response,
+ mock_tool_calls=mock_tool_calls,
+ mock_timeout=mock_timeout,
+ ):
await asyncio.sleep(mock_delay)
try:
@@ -685,7 +688,6 @@ async def _sleep_for_timeout_async(timeout: Union[float, str, httpx.Timeout]):
await asyncio.sleep(timeout.connect)
-
def mock_completion(
model: str,
messages: List,
@@ -2870,9 +2872,9 @@ def completion( # type: ignore # noqa: PLR0915
"aws_region_name" not in optional_params
or optional_params["aws_region_name"] is None
):
- optional_params[
- "aws_region_name"
- ] = aws_bedrock_client.meta.region_name
+ optional_params["aws_region_name"] = (
+ aws_bedrock_client.meta.region_name
+ )
bedrock_route = BedrockModelInfo.get_bedrock_route(model)
if bedrock_route == "converse":
@@ -3498,6 +3500,8 @@ async def aembedding(*args, **kwargs) -> EmbeddingResponse:
)
+# fmt: off
+
# Overload for when aembedding=True (returns coroutine)
@overload
def embedding(
@@ -3520,7 +3524,7 @@ def embedding(
*,
aembedding: Literal[True],
**kwargs,
-) -> Coroutine[Any, Any, EmbeddingResponse]:
+) -> Coroutine[Any, Any, EmbeddingResponse]:
...
@@ -3546,32 +3550,10 @@ def embedding(
*,
aembedding: Literal[False] = False,
**kwargs,
-) -> EmbeddingResponse:
+) -> EmbeddingResponse:
...
-
-# Overload for when aembedding is not specified at all (returns EmbeddingResponse)
-@overload
-def embedding(
- model,
- input=[],
- # Optional params
- dimensions: Optional[int] = None,
- encoding_format: Optional[str] = None,
- timeout=600, # default to 10 minutes
- # set api_base, api_version, api_key
- api_base: Optional[str] = None,
- api_version: Optional[str] = None,
- api_key: Optional[str] = None,
- api_type: Optional[str] = None,
- caching: bool = False,
- user: Optional[str] = None,
- custom_llm_provider=None,
- litellm_call_id=None,
- logger_fn=None,
- **kwargs,
-) -> EmbeddingResponse:
- ...
+# fmt: on
@client
@@ -4727,9 +4709,9 @@ def adapter_completion(
new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs)
response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore
- translated_response: Optional[
- Union[BaseModel, AdapterCompletionStreamWrapper]
- ] = None
+ translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = (
+ None
+ )
if isinstance(response, ModelResponse):
translated_response = translation_obj.translate_completion_output_params(
response=response
@@ -5720,9 +5702,22 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(content_chunks) > 0:
- response["choices"][0]["message"][
- "content"
- ] = processor.get_combined_content(content_chunks)
+ response["choices"][0]["message"]["content"] = (
+ processor.get_combined_content(content_chunks)
+ )
+
+ thinking_blocks = [
+ chunk
+ for chunk in chunks
+ if len(chunk["choices"]) > 0
+ and "thinking_blocks" in chunk["choices"][0]["delta"]
+ and chunk["choices"][0]["delta"]["thinking_blocks"] is not None
+ ]
+
+ if len(thinking_blocks) > 0:
+ response["choices"][0]["message"]["thinking_blocks"] = (
+ processor.get_combined_thinking_content(thinking_blocks)
+ )
reasoning_chunks = [
chunk
@@ -5733,9 +5728,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(reasoning_chunks) > 0:
- response["choices"][0]["message"][
- "reasoning_content"
- ] = processor.get_combined_reasoning_content(reasoning_chunks)
+ response["choices"][0]["message"]["reasoning_content"] = (
+ processor.get_combined_reasoning_content(reasoning_chunks)
+ )
audio_chunks = [
chunk
diff --git a/tests/test_litellm/test_main.py b/tests/test_litellm/test_main.py
index 02f51dccf80..fd9c366a2f0 100644
--- a/tests/test_litellm/test_main.py
+++ b/tests/test_litellm/test_main.py
@@ -547,3 +547,553 @@ async def test_async_mock_delay():
end_time = time.time()
delay = end_time - start_time
assert delay >= 0.01
+
+
+def test_stream_chunk_builder_thinking_blocks():
+ from litellm import stream_chunk_builder
+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices
+
+ chunks = [
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ reasoning_content="I need to summar",
+ thinking_blocks=[
+ {
+ "type": "thinking",
+ "thinking": "I need to summar",
+ "signature": None,
+ }
+ ],
+ provider_specific_fields={
+ "thinking_blocks": [
+ {
+ "type": "thinking",
+ "thinking": "I need to summar",
+ "signature": None,
+ }
+ ]
+ },
+ content="",
+ role="assistant",
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ reasoning_content="ize the previous agent's thinking process into a",
+ thinking_blocks=[
+ {
+ "type": "thinking",
+ "thinking": "ize the previous agent's thinking process into a",
+ "signature": None,
+ }
+ ],
+ provider_specific_fields={
+ "thinking_blocks": [
+ {
+ "type": "thinking",
+ "thinking": "ize the previous agent's thinking process into a",
+ "signature": None,
+ }
+ ]
+ },
+ content="",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ reasoning_content=" short description. Based on the input data provide",
+ thinking_blocks=[
+ {
+ "type": "thinking",
+ "thinking": " short description. Based on the input data provide",
+ "signature": None,
+ }
+ ],
+ provider_specific_fields={
+ "thinking_blocks": [
+ {
+ "type": "thinking",
+ "thinking": " short description. Based on the input data provide",
+ "signature": None,
+ }
+ ]
+ },
+ content="",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ reasoning_content="d, it seems the agent was planning to refine their search",
+ thinking_blocks=[
+ {
+ "type": "thinking",
+ "thinking": "d, it seems the agent was planning to refine their search",
+ "signature": None,
+ }
+ ],
+ provider_specific_fields={
+ "thinking_blocks": [
+ {
+ "type": "thinking",
+ "thinking": "d, it seems the agent was planning to refine their search",
+ "signature": None,
+ }
+ ]
+ },
+ content="",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ reasoning_content=" to focus more on technical aspects of home automation and home",
+ thinking_blocks=[
+ {
+ "type": "thinking",
+ "thinking": " to focus more on technical aspects of home automation and home",
+ "signature": None,
+ }
+ ],
+ provider_specific_fields={
+ "thinking_blocks": [
+ {
+ "type": "thinking",
+ "thinking": " to focus more on technical aspects of home automation and home",
+ "signature": None,
+ }
+ ]
+ },
+ content="",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ reasoning_content=" energy system management.\n\nI'll create a brief",
+ thinking_blocks=[
+ {
+ "type": "thinking",
+ "thinking": " energy system management.\n\nI'll create a brief",
+ "signature": None,
+ }
+ ],
+ provider_specific_fields={
+ "thinking_blocks": [
+ {
+ "type": "thinking",
+ "thinking": " energy system management.\n\nI'll create a brief",
+ "signature": None,
+ }
+ ]
+ },
+ content="",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ reasoning_content=" summary of what the agent was doing.",
+ thinking_blocks=[
+ {
+ "type": "thinking",
+ "thinking": " summary of what the agent was doing.",
+ "signature": None,
+ }
+ ],
+ provider_specific_fields={
+ "thinking_blocks": [
+ {
+ "type": "thinking",
+ "thinking": " summary of what the agent was doing.",
+ "signature": None,
+ }
+ ]
+ },
+ content="",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ reasoning_content="",
+ thinking_blocks=[
+ {
+ "type": "thinking",
+ "thinking": "",
+ "signature": "ErUBCkYIBRgCIkAKBSMkB2+MBF643wiWxlERsGXVdlhbPx9lnTIbygzjFIeZ5uhTV+HNWDon9vQV4hmXvAKwQfwS8vkNFB366l05Egzt2U18IpRrZRyQn1UaDDdYvKHYP8Ps1IbWjSIw8eSYOU9gtqNcwR6D0wY7iOPx2GliDEatLI5rSs96CByoTIoADL2M5bX8KP0jEpbHKh0ccYryigdH/3J8EiFt/BmGUceVASP5l9r22dFWiBgC",
+ }
+ ],
+ provider_specific_fields={
+ "thinking_blocks": [
+ {
+ "type": "thinking",
+ "thinking": "",
+ "signature": "ErUBCkYIBRgCIkAKBSMkB2+MBF643wiWxlERsGXVdlhbPx9lnTIbygzjFIeZ5uhTV+HNWDon9vQV4hmXvAKwQfwS8vkNFB366l05Egzt2U18IpRrZRyQn1UaDDdYvKHYP8Ps1IbWjSIw8eSYOU9gtqNcwR6D0wY7iOPx2GliDEatLI5rSs96CByoTIoADL2M5bX8KP0jEpbHKh0ccYryigdH/3J8EiFt/BmGUceVASP5l9r22dFWiBgC",
+ }
+ ]
+ },
+ content="",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ provider_specific_fields=None,
+ content='{"a',
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ provider_specific_fields=None,
+ content='gent_doing"',
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ provider_specific_fields=None,
+ content=': "Re',
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ provider_specific_fields=None,
+ content="searching",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ provider_specific_fields=None,
+ content=" technic",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ provider_specific_fields=None,
+ content="al aspect",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ provider_specific_fields=None,
+ content="s of home au",
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=1,
+ delta=Delta(
+ provider_specific_fields=None,
+ content='tomation"}',
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ citations=None,
+ ),
+ ModelResponseStream(
+ id="chatcmpl-e8febeb7-cf7d-4947-9417-59ae5e6989f9",
+ created=1751934860,
+ model="claude-3-7-sonnet-latest",
+ object="chat.completion.chunk",
+ system_fingerprint=None,
+ choices=[
+ StreamingChoices(
+ finish_reason="tool_calls",
+ index=0,
+ delta=Delta(
+ provider_specific_fields=None,
+ content=None,
+ role=None,
+ function_call=None,
+ tool_calls=None,
+ audio=None,
+ ),
+ logprobs=None,
+ )
+ ],
+ provider_specific_fields=None,
+ ),
+ ]
+
+ response = stream_chunk_builder(chunks=chunks)
+ print(response)
+
+ assert response is not None
+ assert response.choices[0].message.content is not None
+ assert response.choices[0].message.thinking_blocks is not None