microsoft/autogen · error · RuntimeError

Invalid chunk type: {type(chunk)}

Error message

Invalid chunk type: {type(chunk)}

What it means

CodeExecutorAgent's streaming generation path requires model_client.create_stream() to yield only str deltas and one final CreateResult. This error means some other chunk type appeared in the stream, violating the ChatCompletionClient protocol.

Source

Thrown at python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py:816

        cancellation_token: CancellationToken,
    ) -> AsyncGenerator[Union[CreateResult, ModelClientStreamingChunkEvent], None]:
        """
        Perform a model inference and yield either streaming chunk events or the final CreateResult.
        """
        all_messages = await model_context.get_messages()
        llm_messages = cls._get_compatible_context(model_client=model_client, messages=system_messages + all_messages)

        if model_client_stream:
            model_result: Optional[CreateResult] = None
            async for chunk in model_client.create_stream(
                llm_messages, tools=[], cancellation_token=cancellation_token
            ):
                if isinstance(chunk, CreateResult):
                    model_result = chunk
                elif isinstance(chunk, str):
                    yield ModelClientStreamingChunkEvent(content=chunk, source=agent_name)
                else:
                    raise RuntimeError(f"Invalid chunk type: {type(chunk)}")
            if model_result is None:
                raise RuntimeError("No final model result in streaming mode.")
            yield model_result
        else:
            model_result = await model_client.create(llm_messages, tools=[], cancellation_token=cancellation_token)
            yield model_result

    @staticmethod
    async def _add_messages_to_context(
        model_context: ChatCompletionContext,
        messages: Sequence[BaseChatMessage],
    ) -> None:
        """
        Add incoming messages to the model context.
        """
        for msg in messages:
            if isinstance(msg, HandoffMessage):
                for llm_msg in msg.context:

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Fix the custom client's create_stream() to yield str deltas and end with a CreateResult.
  2. Log type(chunk) to identify the offending object type.
  3. Set model_client_stream=False to use the non-streaming create() path.
  4. Use the official autogen-ext clients, which honor the contract.
Defensive patterns

Strategy: validation

Validate before calling

chunks = [c async for c in model_client.create_stream([SystemMessage(content="ping")])]
assert all(isinstance(c, (str, CreateResult)) for c in chunks), "client emits invalid chunk types"

Type guard

from autogen_core.models import CreateResult

def is_valid_stream_chunk(chunk) -> bool:
    return isinstance(chunk, (str, CreateResult))

Try / catch

try:
    async for ev in agent.on_messages_stream(msgs, ct):
        ...
except RuntimeError as e:
    if "Invalid chunk type" in str(e):
        # rerun with streaming disabled
        ...
    raise

Prevention

When it happens

Trigger: Running a CodeExecutorAgent with model_client_stream=True against a custom or proxy client that yields provider-native chunk objects (dicts, lists, custom delta classes) instead of normalized str/CreateResult.

Common situations: Home-grown clients wrapping raw HTTP/SSE responses without normalization; replay test clients; thin decorators around real clients that pass through provider types.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/e08b5daa926bdafa. Report an issue: GitHub.