Skip to content

ContentParser

autogen.llm_clients.models.content_blocks.ContentParser #

Parses content blocks with automatic fallback to GenericContent.

This enables extensibility: 1. Try to parse as known type (TextContent, ReasoningContent, etc.) 2. If unknown type or parsing fails → GenericContent (preserves data) 3. Later add new types to registry without breaking existing code

register classmethod #

register(content_type, content_class)

Register a new content type.

Example

Add support for new "reflection" type#

class ReflectionContent(BaseContent): type: Literal["reflection"] = "reflection" reflection: str confidence: float

ContentParser.register("reflection", ReflectionContent)

Source code in autogen/llm_clients/models/content_blocks.py
@classmethod
def register(cls, content_type: str, content_class: type[BaseContent]) -> None:
    """Register a new content type.

    Example:
        # Add support for new "reflection" type
        class ReflectionContent(BaseContent):
            type: Literal["reflection"] = "reflection"
            reflection: str
            confidence: float

        ContentParser.register("reflection", ReflectionContent)
    """
    cls._registry[content_type] = content_class

parse classmethod #

parse(data)

Parse content block data to appropriate type.

RETURNS DESCRIPTION
BaseContent
  • Specific type (TextContent, ReasoningContent, etc.) if known
BaseContent
  • GenericContent if unknown type or parsing fails
BaseContent
  • Always succeeds - never raises for unknown types!
Source code in autogen/llm_clients/models/content_blocks.py
@classmethod
def parse(cls, data: dict[str, Any]) -> BaseContent:
    """Parse content block data to appropriate type.

    Returns:
        - Specific type (TextContent, ReasoningContent, etc.) if known
        - GenericContent if unknown type or parsing fails
        - Always succeeds - never raises for unknown types!
    """
    content_type = data.get("type", "unknown")

    # Try known type
    if content_type in cls._registry:
        content_class = cls._registry[content_type]
        try:
            return content_class(**data)
        except Exception as e:
            # Parsing failed - fall back to generic
            # This ensures we never lose data due to validation errors
            warnings.warn(
                f"Failed to parse {content_type} as {content_class.__name__}: {e}. Using GenericContent instead.",
                UserWarning,
                stacklevel=2,
            )
            return GenericContent(**data)

    # Unknown type - use generic (KEY FOR FORWARD COMPATIBILITY!)
    # Ensure 'type' field is present for GenericContent validation
    data_with_type = {"type": content_type, **data}
    return GenericContent(**data_with_type)