Skip to content

Base

Core exporting infrastructure.

This module provides base classes, types, result builders, and extras for exportign flows.

AgentPosition

Bases: Enum

Position relative to a specific agent.

BaseExtras dataclass

BaseExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
)

Bases: ExportContributor

Base class for all exporter extras with export contribution.

add_arg

add_arg(arg: InstanceArgument | str, tabs: int = 0) -> None

Add an extra argument.

Parameters:

NameTypeDescriptionDefault
argInstanceArgument

The argument to add.

required
tabsint

The number of tabs to indent the argument, by default 0.

0
Source code in waldiez/exporting/core/extras/base.py
def add_arg(self, arg: InstanceArgument | str, tabs: int = 0) -> None:
    """Add an extra argument.

    Parameters
    ----------
    arg : InstanceArgument
        The argument to add.
    tabs : int, optional
        The number of tabs to indent the argument, by default 0.
    """
    if isinstance(arg, InstanceArgument):
        if arg not in self.extra_args:
            self.extra_args.append(arg)
    elif isinstance(arg, str) and arg.strip():  # pyright: ignore
        # If it's a string, create an InstanceArgument
        # split by '=' (it's an argument line)
        parts = arg.split("=", 1)
        if len(parts) == 2:
            name, value = parts
            comment = ""
            if " #" in value:
                value, _comment = value.split(" #", 1)
                comment = _comment.strip()
            new_arg = InstanceArgument(
                instance_id=self.instance_id,
                name=name.strip(),
                value=value.strip(),
                tabs=tabs,
                comment=comment.strip(),
            )
            if new_arg not in self.extra_args:
                self.extra_args.append(new_arg)

add_import

add_import(import_statement: ImportStatement) -> None

Add an import statement.

Parameters:

NameTypeDescriptionDefault
import_statementstr

The import statement to add.

required
Source code in waldiez/exporting/core/extras/base.py
def add_import(self, import_statement: ImportStatement) -> None:
    """Add an import statement.

    Parameters
    ----------
    import_statement : str
        The import statement to add.
    """
    if import_statement and import_statement.statement.strip():
        self.extra_imports.append(import_statement)

add_imports

add_imports(imports: Sequence[ImportStatement]) -> None

Add multiple import statements.

Parameters:

NameTypeDescriptionDefault
importsSet[str]

The import statements to add.

required
Source code in waldiez/exporting/core/extras/base.py
def add_imports(self, imports: Sequence[ImportStatement]) -> None:
    """Add multiple import statements.

    Parameters
    ----------
    imports : Set[str]
        The import statements to add.
    """
    for imp in imports:
        self.add_import(imp)

append_after_agent

append_after_agent(content: str) -> None

Append content to the after_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_after_agent(self, content: str) -> None:
    """Append content to the after_agent section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.after_agent:
            self.after_agent += "\n" + content.rstrip()
        else:
            self.after_agent = content.rstrip()

append_after_all_agents

append_after_all_agents(content: str) -> None

Append content to the after_all_agents section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_after_all_agents(self, content: str) -> None:
    """Append content to the after_all_agents section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.after_all_agents:
            self.after_all_agents += "\n" + content.rstrip()
        else:
            self.after_all_agents = content.rstrip()

append_before_agent

append_before_agent(content: str) -> None

Append content to the before_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_before_agent(self, content: str) -> None:
    """Append content to the before_agent section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.before_agent:
            self.before_agent += "\n" + content.rstrip()
        else:
            self.before_agent = content.rstrip()

contribute_to_export

contribute_to_export(result: ExportResult) -> None

Contribute this extras' content to the export result.

Parameters:

NameTypeDescriptionDefault
resultExportResult

The export result to contribute to.

required
Source code in waldiez/exporting/core/extras/base.py
def contribute_to_export(self, result: ExportResult) -> None:
    """Contribute this extras' content to the export result.

    Parameters
    ----------
    result : ExportResult
        The export result to contribute to.
    """
    # Add imports
    result.add_imports(self.extra_imports, ImportPosition.THIRD_PARTY)

    # Add before/after content with default positioning
    # Subclasses can override this method for custom positioning
    if self.before_agent:
        result.add_content(
            self.before_agent,
            ExportPosition.AGENTS,
            order=ContentOrder.PRE_CONTENT,
        )

    if self.extra_args:
        for arg in self.extra_args:
            result.add_content(
                arg.get_content(),
                ExportPosition.AGENTS,
                order=ContentOrder.MAIN_CONTENT,
                agent_position=AgentPosition.AS_ARGUMENT,
            )

    if self.after_agent:
        result.add_content(
            self.after_agent,
            ExportPosition.AGENTS,
            order=ContentOrder.POST_CONTENT,
        )

    # Allow subclasses to contribute additional content
    self._contribute_specific_content(result)

get_extra_args_content

get_extra_args_content() -> str

Get the extra arguments content.

Returns:

TypeDescription
str

The extra arguments content.

Source code in waldiez/exporting/core/extras/base.py
def get_extra_args_content(self) -> str:
    """Get the extra arguments content.

    Returns
    -------
    str
        The extra arguments content.
    """
    return "\n".join([arg.get_content() for arg in self.extra_args]) + "\n"

has_content

has_content() -> bool

Check if there's any meaningful content.

Returns:

TypeDescription
bool

True if there's any content in this extras instance.

Source code in waldiez/exporting/core/extras/base.py
def has_content(self) -> bool:
    """Check if there's any meaningful content.

    Returns
    -------
    bool
        True if there's any content in this extras instance.
    """
    return bool(
        self.extra_imports
        or self.before_agent.strip()
        or self.after_agent.strip()
        or self.has_specific_content()
    )

has_specific_content abstractmethod

has_specific_content() -> bool

Check if there's subclass-specific content.

Returns:

TypeDescription
bool

True if there's specific content for this extras type.

Source code in waldiez/exporting/core/extras/base.py
@abc.abstractmethod
def has_specific_content(self) -> bool:
    """Check if there's subclass-specific content.

    Returns
    -------
    bool
        True if there's specific content for this extras type.
    """

prepend_after_all_agents

prepend_after_all_agents(content: str) -> None

Prepend content to the after_all_agents section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to prepend.

required
Source code in waldiez/exporting/core/extras/base.py
def prepend_after_all_agents(self, content: str) -> None:
    """Prepend content to the after_all_agents section.

    Parameters
    ----------
    content : str
        The content to prepend.
    """
    if content and content.strip():
        if self.after_all_agents:
            self.after_all_agents = (
                content.rstrip() + "\n" + self.after_all_agents
            )
        else:
            self.after_all_agents = content.rstrip()

prepend_before_agent

prepend_before_agent(content: str) -> None

Prepend content to the before_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to prepend.

required
Source code in waldiez/exporting/core/extras/base.py
def prepend_before_agent(self, content: str) -> None:
    """Prepend content to the before_agent section.

    Parameters
    ----------
    content : str
        The content to prepend.
    """
    if content and content.strip():
        if self.before_agent:
            self.before_agent = content.rstrip() + "\n" + self.before_agent
        else:
            self.before_agent = content.rstrip()

CaptainExtras dataclass

CaptainExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    nested_config: Optional[dict[str, Any]] = None,
)

Bases: StandardExtras

Extras for captain agents.

has_specific_content

has_specific_content() -> bool

Check for captain specific content.

Returns:

TypeDescription
bool

True if there's captain specific content.

Source code in waldiez/exporting/core/extras/agent_extras/captain_extras.py
def has_specific_content(self) -> bool:
    """Check for captain specific content.

    Returns
    -------
    bool
        True if there's captain specific content.
    """
    if not super().has_specific_content():
        return bool(self.extra_args or self.nested_config)
    return True

set_nested_config

set_nested_config(config: dict[str, Any]) -> None

Set the nested configuration.

Parameters:

NameTypeDescriptionDefault
configDict[str, Any]

The nested configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/captain_extras.py
def set_nested_config(self, config: dict[str, Any]) -> None:
    """Set the nested configuration.

    Parameters
    ----------
    config : Dict[str, Any]
        The nested configuration.
    """
    self.nested_config = config

ChatExtras dataclass

ChatExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    chat_prerequisites: str = "",
    chat_initiation: str = "",
    chat_registration: str = "",
)

Bases: BaseExtras

Extras for chat exporters.

Attributes:

NameTypeDescription
chat_definitionstr

The chat definition content.

chat_initiationstr

The chat initiation content.

add_registration

add_registration(registration: str) -> None

Add chat registration content.

Parameters:

NameTypeDescriptionDefault
registrationstr

The chat registration content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def add_registration(self, registration: str) -> None:
    """Add chat registration content.

    Parameters
    ----------
    registration : str
        The chat registration content.
    """
    if registration and registration.strip():
        self.chat_registration += "\n" + registration.strip() + "\n"

has_specific_content

has_specific_content() -> bool

Check for chat specific content.

Returns:

TypeDescription
bool

True if there's chat specific content.

Source code in waldiez/exporting/core/extras/chat_extras.py
def has_specific_content(self) -> bool:
    """Check for chat specific content.

    Returns
    -------
    bool
        True if there's chat specific content.
    """
    return bool(
        self.chat_initiation.strip()
        or self.chat_prerequisites.strip()
        or self.chat_registration.strip()
    )

set_chat_initiation

set_chat_initiation(initiation: str) -> None

Set the chat initiation.

Parameters:

NameTypeDescriptionDefault
initiationstr

The chat initiation content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_initiation(self, initiation: str) -> None:
    """Set the chat initiation.

    Parameters
    ----------
    initiation : str
        The chat initiation content.
    """
    self.chat_initiation = initiation

set_chat_prerequisites

set_chat_prerequisites(prerequisites: str) -> None

Set the chat prerequisites.

Parameters:

NameTypeDescriptionDefault
prerequisitesstr

The chat prerequisites content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_prerequisites(self, prerequisites: str) -> None:
    """Set the chat prerequisites.

    Parameters
    ----------
    prerequisites : str
        The chat prerequisites content.
    """
    self.chat_prerequisites = prerequisites

set_chat_registration

set_chat_registration(registration: str) -> None

Set the chat registration.

Parameters:

NameTypeDescriptionDefault
registrationstr

The chat registration content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_registration(self, registration: str) -> None:
    """Set the chat registration.

    Parameters
    ----------
    registration : str
        The chat registration content.
    """
    self.chat_registration = registration

CodeExecutionConfig dataclass

CodeExecutionConfig(
    executor_content: str = "",
    executor_argument: str = "False",
    executor_import: ImportStatement | None = None,
)

Code execution configuration.

has_content

has_content() -> bool

Check if there's any code execution content.

Returns:

TypeDescription
bool

True if there's any code execution configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any code execution content.

    Returns
    -------
    bool
        True if there's any code execution configuration.
    """
    return bool(
        self.executor_content.strip()
        or self.executor_argument != "False"
        or self.executor_import
    )

ConfigurableExporter

ConfigurableExporter(
    config: Optional[dict[str, Any]] = None, **kwargs: Any
)

Bases: Exporter[Extras]

Exporter with configuration support.

Parameters:

NameTypeDescriptionDefault
configOptional[Dict[str, Any]]

Configuration dictionary, by default None

None
**kwargsAny

Additional keyword arguments.

{}
Source code in waldiez/exporting/core/exporters.py
def __init__(self, config: Optional[dict[str, Any]] = None, **kwargs: Any):
    """Initialize with configuration.

    Parameters
    ----------
    config : Optional[Dict[str, Any]], optional
        Configuration dictionary, by default None
    **kwargs : Any
        Additional keyword arguments.
    """
    super().__init__(**kwargs)
    self._config = config or {}

get_config_value

get_config_value(key: str, default: Any = None) -> Any

Get a configuration value.

Parameters:

NameTypeDescriptionDefault
keystr

The configuration key.

required
defaultAny

Default value if key not found, by default None

None

Returns:

TypeDescription
Any

The configuration value or default.

Source code in waldiez/exporting/core/exporters.py
def get_config_value(self, key: str, default: Any = None) -> Any:
    """Get a configuration value.

    Parameters
    ----------
    key : str
        The configuration key.
    default : Any, optional
        Default value if key not found, by default None

    Returns
    -------
    Any
        The configuration value or default.
    """
    return self._config.get(key, default)

set_config_value

set_config_value(key: str, value: Any) -> None

Set a configuration value.

Parameters:

NameTypeDescriptionDefault
keystr

The configuration key.

required
valueAny

The configuration value.

required
Source code in waldiez/exporting/core/exporters.py
def set_config_value(self, key: str, value: Any) -> None:
    """Set a configuration value.

    Parameters
    ----------
    key : str
        The configuration key.
    value : Any
        The configuration value.
    """
    self._config[key] = value

ContentGenerator

Bases: Protocol

Protocol for generating content.

generate

generate(
    merged_result: ExportResult,
    is_async: bool,
    after_run: str,
    **kwargs: Any
) -> str

Generate content based on provided parameters.

Parameters:

NameTypeDescriptionDefault
merged_resultExportResult

The merged export result containing all content.

required
is_asyncbool

Whether to generate async content.

required
after_runstr

Additional content to add after the main flow execution.

required
**kwargsAny

Parameters to influence content generation.

{}

Returns:

TypeDescription
str

The generated content.

Source code in waldiez/exporting/core/protocols.py
def generate(
    self,
    merged_result: ExportResult,
    is_async: bool,
    after_run: str,
    **kwargs: Any,
) -> str:  # pyright: ignore
    """Generate content based on provided parameters.

    Parameters
    ----------
    merged_result : ExportResult
        The merged export result containing all content.
    is_async : bool
        Whether to generate async content.
    after_run : str
        Additional content to add after the main flow execution.
    **kwargs : Any
        Parameters to influence content generation.

    Returns
    -------
    str
        The generated content.
    """

ContentMetadata dataclass

ContentMetadata(
    content_type: ContentType,
    source_id: Optional[str] = None,
    dependencies: list[str] = list[str](),
    tags: set[str] = set[str](),
)

Metadata about exported content.

ContentOrder

Bases: Enum

Standard ordering for positioned content.

ContentType

Bases: Enum

Type of content being exported.

DefaultPathResolver

Bases: PathResolver

Default path resolver for Waldiez items.

resolve

resolve(path: str) -> str

Resolve a path to a local file system path.

Parameters:

NameTypeDescriptionDefault
pathUnion[str, Path]

The path to resolve.

required

Returns:

TypeDescription
Optional[Path]

The resolved local path or None if not found.

Source code in waldiez/exporting/core/extras/path_resolver.py
def resolve(self, path: str) -> str:
    """Resolve a path to a local file system path.

    Parameters
    ----------
    path : Union[str, Path]
        The path to resolve.

    Returns
    -------
    Optional[Path]
        The resolved local path or None if not found.
    """
    resolved = _check_local_path(path)
    if not resolved:
        return _get_raw_path_string(path)
    return _get_raw_path_string(resolved)

DefaultSerializer

Bases: Serializer

Default serializer for Waldiez items.

serialize

serialize(obj: Any, **kwargs: Any) -> str

Serialize an item to a formatted string.

Parameters:

NameTypeDescriptionDefault
objAny

The item to serialize.

required
**kwargsAny

Additional keyword arguments, such as tabs for indentation level.

{}

Returns:

TypeDescription
str

The serialized string representation of the item.

Source code in waldiez/exporting/core/extras/serializer.py
def serialize(self, obj: Any, **kwargs: Any) -> str:
    """Serialize an item to a formatted string.

    Parameters
    ----------
    obj : Any
        The item to serialize.
    **kwargs : Any
        Additional keyword arguments, such as `tabs` for indentation level.

    Returns
    -------
    str
        The serialized string representation of the item.
    """
    tabs = kwargs.get("tabs", 1)
    return serialize_item(obj, tabs)

EnvironmentVariable dataclass

EnvironmentVariable(
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
)

Environment variable with metadata.

as_tuple

as_tuple() -> tuple[str, str]

Get the environment variable as a tuple.

Returns:

TypeDescription
tuple[str, str]

The environment variable as a tuple.

Source code in waldiez/exporting/core/types.py
def as_tuple(self) -> tuple[str, str]:
    """Get the environment variable as a tuple.

    Returns
    -------
    tuple[str, str]
        The environment variable as a tuple.
    """
    return (self.name, self.value)

ExportConfig dataclass

ExportConfig(
    name: str = "Waldiez Flow",
    description: str = "Make AG2 Agents Collaborate: Drag, Drop, and Orchestrate with Waldiez",
    requirements: list[str] = list[str](),
    tags: list[str] = list[str](),
    output_extension: str = "py",
    is_async: bool = False,
    output_directory: Optional[str | Path] = None,
    uploads_root: Optional[Path] = None,
    cache_seed: Optional[int] = None,
    structured_io: bool = False,
    skip_patch_io: bool = True,
)

Configuration for export operations.

Attributes:

NameTypeDescription
namestr

The name of the export.

descriptionstr

A brief description of the export.

requirementslist[str]

A list of requirements for the export.

tagslist[str]

A list of tags associated with the export.

output_directoryOptional[str | Path]

The directory where the exported content will be saved.

uploads_rootOptional[str | Path]

The root directory for uploads, if applicable.

cache_seedOptional[int]

The seed for caching, if applicable.

structured_iobool

Whether the export should use structured I/O.

output_extensionstr

The file extension for the exported content.

is_asyncbool

Whether the exported content should be asynchronous.

skip_patch_iobool

Whether to skip patching I/O operations.

create classmethod

create(**kwargs: Any) -> ExportConfig

Create a new ExportConfig instance with the provided values.

Parameters:

NameTypeDescriptionDefault
**kwargsAny

Keyword arguments to initialize the ExportConfig.

{}

Returns:

TypeDescription
ExportConfig

A new instance of ExportConfig.

Source code in waldiez/exporting/core/types.py
@classmethod
def create(cls, **kwargs: Any) -> "ExportConfig":
    """Create a new ExportConfig instance with the provided values.

    Parameters
    ----------
    **kwargs : Any
        Keyword arguments to initialize the ExportConfig.

    Returns
    -------
    ExportConfig
        A new instance of ExportConfig.
    """
    valid_fields = {f.name for f in fields(cls)}
    output_extension = kwargs.pop("output_extension", "py")
    for_notebook = kwargs.pop("for_notebook", output_extension == "ipynb")
    if for_notebook is True:
        output_extension = "ipynb"
    cache_seed = kwargs.pop("cache_seed", None)
    if cache_seed is not None and not isinstance(cache_seed, int):
        cache_seed = None
    return cls(
        cache_seed=cache_seed,
        output_extension=output_extension,
        **{k: v for k, v in kwargs.items() if k in valid_fields},
    )

for_notebook property

for_notebook: bool

Check if the export is intended for a notebook environment.

Returns:

TypeDescription
bool

True if the output extension is 'ipynb', otherwise False.

update

update(**kwargs: Any) -> None

Update the export configuration with new values.

Parameters:

NameTypeDescriptionDefault
**kwargsAny

Keyword arguments to update the configuration.

{}

Raises:

TypeDescription
ValueError

If an invalid configuration key is provided.

Source code in waldiez/exporting/core/types.py
def update(self, **kwargs: Any) -> None:
    """Update the export configuration with new values.

    Parameters
    ----------
    **kwargs : Any
        Keyword arguments to update the configuration.

    Raises
    ------
    ValueError
        If an invalid configuration key is provided.
    """
    valid_fields = {f.name for f in fields(self)}
    for key, value in kwargs.items():
        if key in valid_fields:
            setattr(self, key, value)
    if (
        "for_notebook" in kwargs
        and isinstance(kwargs["for_notebook"], bool)
        and "output_extension" not in kwargs
    ):  # pragma: no cover
        self.output_extension = "ipynb" if kwargs["for_notebook"] else "py"

ExportContributor

Bases: Protocol

Protocol for objects that can contribute to exports.

contribute_to_export

contribute_to_export(result: ExportResult) -> None

Contribute content to the export result.

Parameters:

NameTypeDescriptionDefault
resultExportResult

The export result to contribute to.

required
Source code in waldiez/exporting/core/protocols.py
def contribute_to_export(self, result: ExportResult) -> None:
    """Contribute content to the export result.

    Parameters
    ----------
    result : ExportResult
        The export result to contribute to.
    """

ExportPosition

Bases: Enum

Position for content in the exported code.

Attributes:

NameTypeDescription
TOPint

Position at the top of the file, typically for comments or metadata.

IMPORTSint

Position for import statements.

TOOLSint

Position for tool definitions.

MODELSint

Position for model configurations (llm_config).

AGENTSint

Position for agent definitions.

CHATSint

Position for chat/connection definitions.

BOTTOMint

Position at the bottom of the file, typically for main execution or final code.

ExportResult dataclass

ExportResult(
    main_content: Optional[str] = None,
    imports: set[ImportStatement] = set[ImportStatement](),
    positioned_content: list[PositionedContent] = list[
        PositionedContent
    ](),
    instance_arguments: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    environment_variables: list[EnvironmentVariable] = list[
        EnvironmentVariable
    ](),
    validation_result: Optional[ValidationResult] = None,
    metadata: dict[str, Any] = dict[str, Any](),
)

Complete export result with all components.

add_content

add_content(
    content: str,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
    order: Union[ContentOrder, int] = MAIN_CONTENT,
    skip_strip: bool = False,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    metadata: Optional[dict[str, Any]] = None,
) -> None

Add positioned content.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to add.

required
positionExportPosition

The position of the content, by default AGENTS

DEFAULT_EXPORT_POSITION
orderint

The order within the position, by default 0

MAIN_CONTENT
skip_stripbool

Whether to skip stripping whitespace from content, by default False

False
agent_idOptional[str]

The agent ID if positioned relative to an agent, by default None

None
agent_positionOptional[AgentPosition]

The position relative to the agent, by default None

None
metadataOptional[dict[str, Any]]

Additional metadata for the content, by default None

None
Source code in waldiez/exporting/core/result.py
def add_content(
    self,
    content: str,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
    order: Union[ContentOrder, int] = ContentOrder.MAIN_CONTENT,
    skip_strip: bool = False,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    metadata: Optional[dict[str, Any]] = None,
) -> None:
    """Add positioned content.

    Parameters
    ----------
    content : str
        The content to add.
    position : ExportPosition, optional
        The position of the content, by default AGENTS
    order : int, optional
        The order within the position, by default 0
    skip_strip : bool, optional
        Whether to skip stripping whitespace from content, by default False
    agent_id : Optional[str], optional
        The agent ID if positioned relative to an agent, by default None
    agent_position : Optional[AgentPosition], optional
        The position relative to the agent, by default None
    metadata : Optional[dict[str, Any]], optional
        Additional metadata for the content, by default None
    """
    order_value = order.value if isinstance(order, ContentOrder) else order
    if content and content.strip():
        positioned = PositionedContent(
            content=content.strip() if not skip_strip else content,
            position=position,
            order=order_value,
            agent_id=agent_id,
            agent_position=agent_position,
            **(metadata or {}),
        )
        if positioned not in self.positioned_content:
            self.positioned_content.append(positioned)

add_env_var

add_env_var(
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
) -> None

Add environment variable.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the environment variable.

required
valuestr

The value of the environment variable.

required
descriptionOptional[str]

Description of the variable, by default None

None
requiredbool

Whether the variable is required, by default True

True
Source code in waldiez/exporting/core/result.py
def add_env_var(
    self,
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
) -> None:
    """Add environment variable.

    Parameters
    ----------
    name : str
        The name of the environment variable.
    value : str
        The value of the environment variable.
    description : Optional[str], optional
        Description of the variable, by default None
    required : bool, optional
        Whether the variable is required, by default True
    """
    if name and value:
        env_var = EnvironmentVariable(
            name=name,
            value=value,
            description=description,
            required=required,
        )
        # Avoid duplicates based on name
        for existing in self.environment_variables:
            if existing.name == name:
                # Update existing
                existing.value = value
                existing.description = description
                existing.required = required
                return
        self.environment_variables.append(env_var)

add_import

add_import(
    statement: str,
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None

Add an import statement.

Parameters:

NameTypeDescriptionDefault
statementstr

The import statement to add.

required
positionImportPosition

The position of the import, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION
Source code in waldiez/exporting/core/result.py
def add_import(
    self, statement: str, position: ImportPosition = DEFAULT_IMPORT_POSITION
) -> None:
    """Add an import statement.

    Parameters
    ----------
    statement : str
        The import statement to add.
    position : ImportPosition, optional
        The position of the import, by default THIRD_PARTY
    """
    if statement and statement.strip():
        self.imports.add(
            ImportStatement(
                statement=statement.strip(),
                position=position,
            )
        )

add_imports

add_imports(
    statements: Union[
        set[str],
        list[str],
        set[ImportStatement],
        list[ImportStatement],
    ],
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None

Add multiple import statements.

Parameters:

NameTypeDescriptionDefault
statementsUnion[
set[str],
list[str]],
set[ImportStatement],
list[ImportStatement]

] The import statements to add.

required
positionImportPosition

The position of the imports, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION
Source code in waldiez/exporting/core/result.py
def add_imports(
    self,
    statements: Union[
        set[str],
        list[str],
        set[ImportStatement],
        list[ImportStatement],
    ],
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None:
    """Add multiple import statements.

    Parameters
    ----------
    statements : Union[
            set[str],
            list[str]],
            set[ImportStatement],
            list[ImportStatement]
        ]
        The import statements to add.
    position : ImportPosition, optional
        The position of the imports, by default THIRD_PARTY
    """
    for statement in statements:
        if isinstance(statement, ImportStatement):
            # If it's already an ImportStatement, use it directly
            self.add_import(statement.statement, statement.position)
        else:
            # Otherwise, treat it as a string
            self.add_import(statement, position)

add_instance_argument

add_instance_argument(
    name: str,
    value: Any,
    instance_id: str,
    tabs: int = 0,
    comment: Optional[str] = None,
) -> None

Add an instance argument.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the argument.

required
valueAny

The value of the argument.

required
instance_idstr

The ID of the instance this argument belongs to.

required
tabsint

Number of tabs for indentation, by default 0

0
commentOptional[str]

Optional comment for the argument, by default None

None
Source code in waldiez/exporting/core/result.py
def add_instance_argument(
    self,
    name: str,
    value: Any,
    instance_id: str,
    tabs: int = 0,
    comment: Optional[str] = None,
) -> None:
    """Add an instance argument.

    Parameters
    ----------
    name : str
        The name of the argument.
    value : Any
        The value of the argument.
    instance_id : str
        The ID of the instance this argument belongs to.
    tabs : int, optional
        Number of tabs for indentation, by default 0
    comment : Optional[str], optional
        Optional comment for the argument, by default None
    """
    if name and value is not None:
        arg = InstanceArgument(
            instance_id=instance_id,
            name=name,
            value=value,
            comment=comment,
            tabs=tabs,
        )
        # Avoid duplicates based on name
        for existing in self.instance_arguments:
            if existing.name == name:
                # Update existing
                existing.value = value
                existing.comment = comment
                return
        self.instance_arguments.append(arg)

add_instance_arguments

add_instance_arguments(
    arguments: Union[
        list[InstanceArgument], set[InstanceArgument]
    ],
) -> None

Add multiple instance arguments.

Parameters:

NameTypeDescriptionDefault
argumentsUnion[list[InstanceArgument], set[InstanceArgument]]

The instance arguments to add.

required
Source code in waldiez/exporting/core/result.py
def add_instance_arguments(
    self,
    arguments: Union[list[InstanceArgument], set[InstanceArgument]],
) -> None:
    """Add multiple instance arguments.

    Parameters
    ----------
    arguments : Union[list[InstanceArgument], set[InstanceArgument]]
        The instance arguments to add.
    """
    for arg in arguments:
        self.add_instance_argument(
            instance_id=arg.instance_id,
            name=arg.name,
            value=arg.value,
            comment=arg.comment,
        )

clear

clear() -> None

Clear all content from the result.

Source code in waldiez/exporting/core/result.py
def clear(self) -> None:
    """Clear all content from the result."""
    self.main_content = None
    self.imports.clear()
    self.positioned_content.clear()
    self.environment_variables.clear()
    self.validation_result = None
    self.metadata.clear()

get_agent_content

get_agent_content(
    agent_id: str,
    agent_position: Optional[AgentPosition] = None,
) -> list[PositionedContent]

Get content positioned relative to a specific agent.

Parameters:

NameTypeDescriptionDefault
agent_idstr

The ID of the agent.

required
agent_positionOptional[AgentPosition]

Filter by specific agent position, by default None (all positions)

None

Returns:

TypeDescription
list[PositionedContent]

Sorted list of content for the specified agent.

Source code in waldiez/exporting/core/result.py
def get_agent_content(
    self, agent_id: str, agent_position: Optional[AgentPosition] = None
) -> list[PositionedContent]:
    """Get content positioned relative to a specific agent.

    Parameters
    ----------
    agent_id : str
        The ID of the agent.
    agent_position : Optional[AgentPosition], optional
        Filter by specific agent position, by default None (all positions)

    Returns
    -------
    list[PositionedContent]
        Sorted list of content for the specified agent.
    """
    content = [
        c
        for c in self.positioned_content
        if c.agent_id == agent_id
        and (agent_position is None or c.agent_position == agent_position)
    ]
    return sorted(content)

get_all_content_sorted

get_all_content_sorted() -> list[PositionedContent]

Get all positioned content sorted by position and order.

Returns:

TypeDescription
list[PositionedContent]

All positioned content sorted.

Source code in waldiez/exporting/core/result.py
def get_all_content_sorted(self) -> list[PositionedContent]:
    """Get all positioned content sorted by position and order.

    Returns
    -------
    list[PositionedContent]
        All positioned content sorted.
    """
    return sorted(self.positioned_content)

get_content_by_position

get_content_by_position(
    position: ExportPosition,
    skip_agent_arguments: bool = True,
) -> list[PositionedContent]

Get all content for a specific position.

Parameters:

NameTypeDescriptionDefault
positionExportPosition

The position to filter by.

required
skip_agent_argumentsbool

Whether to skip content positioned as agent arguments, by default True

True

Returns:

TypeDescription
list[PositionedContent]

Sorted list of content for the specified position.

Source code in waldiez/exporting/core/result.py
def get_content_by_position(
    self,
    position: ExportPosition,
    skip_agent_arguments: bool = True,
) -> list[PositionedContent]:
    """Get all content for a specific position.

    Parameters
    ----------
    position : ExportPosition
        The position to filter by.
    skip_agent_arguments : bool, optional
        Whether to skip content positioned as agent arguments,
        by default True

    Returns
    -------
    list[PositionedContent]
        Sorted list of content for the specified position.
    """
    if not skip_agent_arguments:
        content = [
            c for c in self.positioned_content if c.position == position
        ]
    else:
        content = [
            c
            for c in self.positioned_content
            if c.position == position
            and (c.agent_position != AgentPosition.AS_ARGUMENT)
        ]
    return sorted(content)

get_imports_by_position

get_imports_by_position(
    position: ImportPosition,
) -> list[ImportStatement]

Get imports filtered by position.

Parameters:

NameTypeDescriptionDefault
positionImportPosition

The position to filter by.

required

Returns:

TypeDescription
list[ImportStatement]

list of imports for the specified position.

Source code in waldiez/exporting/core/result.py
def get_imports_by_position(
    self, position: ImportPosition
) -> list[ImportStatement]:
    """Get imports filtered by position.

    Parameters
    ----------
    position : ImportPosition
        The position to filter by.

    Returns
    -------
    list[ImportStatement]
        list of imports for the specified position.
    """
    return [
        imp for imp in self.get_sorted_imports() if imp.position == position
    ]

get_sorted_imports

get_sorted_imports() -> list[ImportStatement]

Get imports sorted by position and statement.

Returns:

TypeDescription
list[ImportStatement]

Sorted list of import statements.

Source code in waldiez/exporting/core/result.py
def get_sorted_imports(self) -> list[ImportStatement]:
    """Get imports sorted by position and statement.

    Returns
    -------
    list[ImportStatement]
        Sorted list of import statements.
    """
    return sorted(self.imports)

get_statistics

get_statistics() -> dict[str, int]

Get statistics about the export result.

Returns:

TypeDescription
dict[str, int]

dictionary with statistics about the export.

Source code in waldiez/exporting/core/result.py
def get_statistics(self) -> dict[str, int]:
    """Get statistics about the export result.

    Returns
    -------
    dict[str, int]
        dictionary with statistics about the export.
    """
    return {
        "total_imports": len(self.imports),
        "builtin_imports": len(
            self.get_imports_by_position(ImportPosition.BUILTINS)
        ),
        "third_party_imports": len(
            self.get_imports_by_position(ImportPosition.THIRD_PARTY)
        ),
        "local_imports": len(
            self.get_imports_by_position(ImportPosition.LOCAL)
        ),
        "positioned_content_items": len(self.positioned_content),
        "environment_variables": len(self.environment_variables),
        "validation_errors": (
            len(self.validation_result.errors)
            if self.validation_result
            else 0
        ),
        "validation_warnings": (
            len(self.validation_result.warnings)
            if self.validation_result
            else 0
        ),
    }

has_content

has_content() -> bool

Check if there's any meaningful content.

Returns:

TypeDescription
bool

True if there's any content, imports, or environment variables.

Source code in waldiez/exporting/core/result.py
def has_content(self) -> bool:
    """Check if there's any meaningful content.

    Returns
    -------
    bool
        True if there's any content, imports, or environment variables.
    """
    return bool(
        self.main_content
        or self.imports
        or self.positioned_content
        or self.environment_variables
    )

has_errors

has_errors() -> bool

Check if there are validation errors.

Returns:

TypeDescription
bool

True if there are validation errors.

Source code in waldiez/exporting/core/result.py
def has_errors(self) -> bool:
    """Check if there are validation errors.

    Returns
    -------
    bool
        True if there are validation errors.
    """
    return (
        self.validation_result is not None
        and self.validation_result.has_errors()
    )

has_warnings

has_warnings() -> bool

Check if there are validation warnings.

Returns:

TypeDescription
bool

True if there are validation warnings.

Source code in waldiez/exporting/core/result.py
def has_warnings(self) -> bool:
    """Check if there are validation warnings.

    Returns
    -------
    bool
        True if there are validation warnings.
    """
    return (
        self.validation_result is not None
        and self.validation_result.has_warnings()
    )

merge

merge(
    other: ExportResult,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
) -> None

Merge another ExportResult into this one.

Parameters:

NameTypeDescriptionDefault
otherExportResult

The other result to merge.

required
positionExportPosition

The position for the merged content, by default AGENTS

DEFAULT_EXPORT_POSITION
Source code in waldiez/exporting/core/result.py
def merge(
    self,
    other: "ExportResult",
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
) -> None:
    """Merge another ExportResult into this one.

    Parameters
    ----------
    other : ExportResult
        The other result to merge.
    position : ExportPosition, optional
        The position for the merged content, by default AGENTS
    """
    if other.main_content:
        self.main_content = (
            (self.main_content or "") + "\n" + other.main_content
        ).strip()

    self.imports.update(other.imports)

    self.positioned_content.extend(
        PositionedContent(
            content=c.content,
            position=position,
            order=c.order,
            agent_id=c.agent_id,
            agent_position=c.agent_position,
            **c.metadata,
        )
        for c in other.positioned_content
    )

    self.environment_variables.extend(other.environment_variables)

    if other.validation_result:
        if self.validation_result:
            self.validation_result.merge(other.validation_result)
        else:
            self.validation_result = other.validation_result

    # Merge instance arguments
    for arg in other.instance_arguments:
        self.add_instance_argument(
            name=arg.name,
            value=arg.value,
            instance_id=arg.instance_id,
            comment=arg.comment,
        )

    self.metadata.update(other.metadata)

merge_with

merge_with(other: ExportResult) -> None

Merge another ExportResult into this one.

Parameters:

NameTypeDescriptionDefault
otherExportResult

The other result to merge.

required
Source code in waldiez/exporting/core/result.py
def merge_with(self, other: "ExportResult") -> None:
    """Merge another ExportResult into this one.

    Parameters
    ----------
    other : ExportResult
        The other result to merge.
    """
    # Merge imports (set automatically handles duplicates)
    self.imports.update(other.imports)

    # Merge positioned content
    self.positioned_content.extend(other.positioned_content)

    # Merge environment variables (avoid duplicates by name)
    for env_var in other.environment_variables:
        self.add_env_var(
            env_var.name,
            env_var.value,
            env_var.description,
            env_var.required,
        )

    # Merge metadata
    self.metadata.update(other.metadata)

    # Handle validation results
    if other.validation_result:
        if self.validation_result:
            # Merge validation results
            self.validation_result.errors.extend(
                other.validation_result.errors
            )
            self.validation_result.warnings.extend(
                other.validation_result.warnings
            )
            self.validation_result.is_valid = (
                self.validation_result.is_valid
                and other.validation_result.is_valid
            )
        else:
            self.validation_result = other.validation_result

ExportResultBuilder dataclass

ExportResultBuilder(_result: ExportResult = ExportResult())

Builder pattern for constructing ExportResult objects.

build

build() -> ExportResult

Build the final ExportResult.

Returns:

TypeDescription
ExportResult

The constructed ExportResult.

Source code in waldiez/exporting/core/result.py
def build(self) -> ExportResult:
    """Build the final ExportResult.

    Returns
    -------
    ExportResult
        The constructed ExportResult.
    """
    return self._result

with_content

with_content(
    content: str,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
    order: ContentOrder = MAIN_CONTENT,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
) -> ExportResultBuilder

Add positioned content.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to add.

required
positionExportPosition

The content position, by default AGENTS

DEFAULT_EXPORT_POSITION
orderint

The order within position, by default 0

MAIN_CONTENT
agent_idOptional[str]

Agent ID for agent-relative positioning, by default None

None
agent_positionOptional[AgentPosition]

Position relative to agent, by default None

None

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_content(
    self,
    content: str,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
    order: ContentOrder = ContentOrder.MAIN_CONTENT,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
) -> "ExportResultBuilder":
    """Add positioned content.

    Parameters
    ----------
    content : str
        The content to add.
    position : ExportPosition, optional
        The content position, by default AGENTS
    order : int, optional
        The order within position, by default 0
    agent_id : Optional[str], optional
        Agent ID for agent-relative positioning, by default None
    agent_position : Optional[AgentPosition], optional
        Position relative to agent, by default None

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.add_content(
        content=content,
        position=position,
        order=order,
        agent_id=agent_id,
        agent_position=agent_position,
    )
    return self

with_env_var

with_env_var(
    name: str, value: str, description: Optional[str] = None
) -> ExportResultBuilder

Add environment variable.

Parameters:

NameTypeDescriptionDefault
namestr

Variable name.

required
valuestr

Variable value.

required
descriptionOptional[str]

Variable description, by default None

None

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_env_var(
    self, name: str, value: str, description: Optional[str] = None
) -> "ExportResultBuilder":
    """Add environment variable.

    Parameters
    ----------
    name : str
        Variable name.
    value : str
        Variable value.
    description : Optional[str], optional
        Variable description, by default None

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.add_env_var(name, value, description)
    return self

with_import

with_import(
    statement: str,
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> ExportResultBuilder

Add an import statement.

Parameters:

NameTypeDescriptionDefault
statementstr

The import statement.

required
positionImportPosition

The import position, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_import(
    self, statement: str, position: ImportPosition = DEFAULT_IMPORT_POSITION
) -> "ExportResultBuilder":
    """Add an import statement.

    Parameters
    ----------
    statement : str
        The import statement.
    position : ImportPosition, optional
        The import position, by default THIRD_PARTY

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.add_import(statement, position)
    return self

with_main_content

with_main_content(content: str) -> ExportResultBuilder

Set the main content.

Parameters:

NameTypeDescriptionDefault
contentstr

The main content to set.

required

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_main_content(self, content: str) -> "ExportResultBuilder":
    """Set the main content.

    Parameters
    ----------
    content : str
        The main content to set.

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.main_content = content
    return self

with_metadata

with_metadata(key: str, value: Any) -> ExportResultBuilder

Add metadata.

Parameters:

NameTypeDescriptionDefault
keystr

Metadata key.

required
valueAny

Metadata value.

required

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_metadata(self, key: str, value: Any) -> "ExportResultBuilder":
    """Add metadata.

    Parameters
    ----------
    key : str
        Metadata key.
    value : Any
        Metadata value.

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.metadata[key] = value
    return self

Exporter

Exporter(
    context: Optional[ExporterContext] = None, **kwargs: Any
)

Bases: ABC, Generic[Extras]

Exporter base class with structured extras and clean interface.

Parameters:

NameTypeDescriptionDefault
contextOptional[ExporterContext]

The exporter context with dependencies, by default None

None
**kwargsAny

Additional keyword arguments for subclasses.

{}
Source code in waldiez/exporting/core/exporter.py
def __init__(
    self,
    context: Optional[ExporterContext] = None,
    **kwargs: Any,
):
    """Initialize the exporter.

    Parameters
    ----------
    context : Optional[ExporterContext], optional
        The exporter context with dependencies, by default None
    **kwargs : Any
        Additional keyword arguments for subclasses.
    """
    self._context = context or DefaultExporterContext(
        config=ExportConfig.create(**kwargs)
    )
    config = self._context.get_config()
    config.update(**kwargs)
    self._context.set_config(config)
    self._result = ExportResult()
    self._initialized = False
    self._builder = ExportResultBuilder()
    self.config = self._context.get_config()

    # Allow subclasses to handle additional kwargs
    self._handle_kwargs(**kwargs)

add_content

add_content(
    content: str,
    position: ExportPosition,
    order: ContentOrder = MAIN_CONTENT,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    skip_strip: bool | None = None,
    **metadata: Any
) -> None

Add positioned content.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to add.

required
positionExportPosition

The position of the content.

required
orderint

The order within the position, by default 0

MAIN_CONTENT
agent_idOptional[str]

Agent ID for agent-relative positioning, by default None

None
agent_positionOptional[AgentPosition]

Position relative to agent, by default None

None
skip_stripbool | None

Whether to skip stripping whitespace, by default None If None, defaults to True for CHATS position (keep identation),

None
**metadataAny

Additional metadata for the content.

{}
Source code in waldiez/exporting/core/exporter.py
def add_content(
    self,
    content: str,
    position: ExportPosition,
    order: ContentOrder = ContentOrder.MAIN_CONTENT,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    skip_strip: bool | None = None,
    **metadata: Any,
) -> None:
    """Add positioned content.

    Parameters
    ----------
    content : str
        The content to add.
    position : ExportPosition
        The position of the content.
    order : int, optional
        The order within the position, by default 0
    agent_id : Optional[str], optional
        Agent ID for agent-relative positioning, by default None
    agent_position : Optional[AgentPosition], optional
        Position relative to agent, by default None
    skip_strip : bool | None, optional
        Whether to skip stripping whitespace, by default None
        If None, defaults to True for CHATS position (keep identation),
    **metadata : Any
        Additional metadata for the content.
    """
    if skip_strip is None:
        skip_strip = position == ExportPosition.CHATS
    self._result.add_content(
        content=content,
        position=position,
        order=order,
        agent_id=agent_id,
        agent_position=agent_position,
        skip_strip=skip_strip,
        **metadata,
    )

add_env_var

add_env_var(
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
) -> None

Add environment variable.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the environment variable.

required
valuestr

The value of the environment variable.

required
descriptionOptional[str]

Description of the variable, by default None

None
requiredbool

Whether the variable is required, by default True

True
Source code in waldiez/exporting/core/exporter.py
def add_env_var(
    self,
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
) -> None:
    """Add environment variable.

    Parameters
    ----------
    name : str
        The name of the environment variable.
    value : str
        The value of the environment variable.
    description : Optional[str], optional
        Description of the variable, by default None
    required : bool, optional
        Whether the variable is required, by default True
    """
    self._result.add_env_var(name, value, description, required)

add_import

add_import(
    statement: str,
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None

Add an import statement.

Parameters:

NameTypeDescriptionDefault
statementstr

The import statement to add.

required
positionImportPosition

The position of the import, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION
Source code in waldiez/exporting/core/exporter.py
def add_import(
    self,
    statement: str,
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None:
    """Add an import statement.

    Parameters
    ----------
    statement : str
        The import statement to add.
    position : ImportPosition, optional
        The position of the import, by default THIRD_PARTY
    """
    self._result.add_import(statement, position)

add_imports

add_imports(
    statements: set[str],
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None

Add multiple import statements.

Parameters:

NameTypeDescriptionDefault
statementsSet[str]

The import statements to add.

required
positionImportPosition

The position of the imports, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION
Source code in waldiez/exporting/core/exporter.py
def add_imports(
    self,
    statements: set[str],
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None:
    """Add multiple import statements.

    Parameters
    ----------
    statements : Set[str]
        The import statements to add.
    position : ImportPosition, optional
        The position of the imports, by default THIRD_PARTY
    """
    self._result.add_imports(statements, position)

clear

clear() -> None

Clear all export content and reset initialization state.

Source code in waldiez/exporting/core/exporter.py
def clear(self) -> None:
    """Clear all export content and reset initialization state."""
    self._result.clear()
    self._initialized = False

context property

context: ExporterContext

Get the exporter context.

Returns:

TypeDescription
ExporterContext

The exporter context.

export

export() -> ExportResult

Export and return the complete result.

Returns:

TypeDescription
ExportResult

The complete export result.

Source code in waldiez/exporting/core/exporter.py
def export(self) -> ExportResult:
    """Export and return the complete result.

    Returns
    -------
    ExportResult
        The complete export result.
    """
    self._ensure_initialized()
    return self._result

extras abstractmethod property

extras: Extras

Get the structured extras for this exporter.

Returns:

TypeDescription
Extras

The extras instance.

generate_main_content abstractmethod

generate_main_content() -> Optional[str]

Generate the main export content.

Returns:

TypeDescription
Optional[str]

The main content, or None if no content should be generated.

Source code in waldiez/exporting/core/exporter.py
@abc.abstractmethod
def generate_main_content(self) -> Optional[str]:
    """Generate the main export content.

    Returns
    -------
    Optional[str]
        The main content, or None if no content should be generated.
    """

get_content_by_position

get_content_by_position(
    position: ExportPosition,
) -> list[PositionedContent]

Get content for a specific position.

Parameters:

NameTypeDescriptionDefault
positionExportPosition

The position to filter by.

required

Returns:

TypeDescription
List[PositionedContent]

List of content for the specified position.

Source code in waldiez/exporting/core/exporter.py
def get_content_by_position(
    self, position: ExportPosition
) -> list[PositionedContent]:
    """Get content for a specific position.

    Parameters
    ----------
    position : ExportPosition
        The position to filter by.

    Returns
    -------
    List[PositionedContent]
        List of content for the specified position.
    """
    self._ensure_initialized()
    return self._result.get_content_by_position(position)

get_environment_variables

get_environment_variables() -> list[EnvironmentVariable]

Get environment variables.

Returns:

TypeDescription
List[EnvironmentVariable]

List of environment variables.

Source code in waldiez/exporting/core/exporter.py
def get_environment_variables(self) -> list[EnvironmentVariable]:
    """Get environment variables.

    Returns
    -------
    List[EnvironmentVariable]
        List of environment variables.
    """
    self._ensure_initialized()
    return self._result.environment_variables

get_imports

get_imports() -> list[ImportStatement]

Get sorted imports.

Returns:

TypeDescription
List[ImportStatement]

Sorted list of import statements.

Source code in waldiez/exporting/core/exporter.py
def get_imports(self) -> list[ImportStatement]:
    """Get sorted imports.

    Returns
    -------
    List[ImportStatement]
        Sorted list of import statements.
    """
    self._ensure_initialized()
    return self._result.get_sorted_imports()

get_main_content

get_main_content() -> Optional[str]

Get the main content.

Returns:

TypeDescription
Optional[str]

The main content.

Source code in waldiez/exporting/core/exporter.py
def get_main_content(self) -> Optional[str]:
    """Get the main content.

    Returns
    -------
    Optional[str]
        The main content.
    """
    self._ensure_initialized()
    return self._result.main_content

get_metadata

get_metadata(key: str, default: Any = None) -> Any

Get metadata from the export result.

Parameters:

NameTypeDescriptionDefault
keystr

The metadata key.

required
defaultAny

Default value if key not found, by default None

None

Returns:

TypeDescription
Any

The metadata value or default.

Source code in waldiez/exporting/core/exporter.py
def get_metadata(self, key: str, default: Any = None) -> Any:
    """Get metadata from the export result.

    Parameters
    ----------
    key : str
        The metadata key.
    default : Any, optional
        Default value if key not found, by default None

    Returns
    -------
    Any
        The metadata value or default.
    """
    return self._result.metadata.get(key, default)

get_statistics

get_statistics() -> dict[str, int]

Get statistics about the export.

Returns:

TypeDescription
Dict[str, int]

Dictionary with export statistics.

Source code in waldiez/exporting/core/exporter.py
def get_statistics(self) -> dict[str, int]:
    """Get statistics about the export.

    Returns
    -------
    Dict[str, int]
        Dictionary with export statistics.
    """
    self._ensure_initialized()
    return self._result.get_statistics()

has_content

has_content() -> bool

Check if the exporter has any content.

Returns:

TypeDescription
bool

True if there's any content.

Source code in waldiez/exporting/core/exporter.py
def has_content(self) -> bool:
    """Check if the exporter has any content.

    Returns
    -------
    bool
        True if there's any content.
    """
    self._ensure_initialized()
    return self._result.has_content()

has_errors

has_errors() -> bool

Check if there are validation errors.

Returns:

TypeDescription
bool

True if there are validation errors.

Source code in waldiez/exporting/core/exporter.py
def has_errors(self) -> bool:
    """Check if there are validation errors.

    Returns
    -------
    bool
        True if there are validation errors.
    """
    self._ensure_initialized()
    return self._result.has_errors()

has_warnings

has_warnings() -> bool

Check if there are validation warnings.

Returns:

TypeDescription
bool

True if there are validation warnings.

Source code in waldiez/exporting/core/exporter.py
def has_warnings(self) -> bool:
    """Check if there are validation warnings.

    Returns
    -------
    bool
        True if there are validation warnings.
    """
    self._ensure_initialized()
    return self._result.has_warnings()

reset

reset() -> None

Reset the exporter to initial state.

Source code in waldiez/exporting/core/exporter.py
def reset(self) -> None:
    """Reset the exporter to initial state."""
    self._result = ExportResult()
    self._initialized = False
    self._builder = ExportResultBuilder()

set_metadata

set_metadata(key: str, value: Any) -> None

Set metadata on the export result.

Parameters:

NameTypeDescriptionDefault
keystr

The metadata key.

required
valueAny

The metadata value.

required
Source code in waldiez/exporting/core/exporter.py
def set_metadata(self, key: str, value: Any) -> None:
    """Set metadata on the export result.

    Parameters
    ----------
    key : str
        The metadata key.
    value : Any
        The metadata value.
    """
    self._result.metadata[key] = value

ExporterContentError

Bases: ExporterError

Exception raised when content generation fails.

ExporterContext dataclass

ExporterContext(
    serializer: Optional[Serializer] = None,
    path_resolver: Optional[PathResolver] = None,
    validator: Optional[Validator] = None,
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
)

Context object containing common exporter dependencies.

get_config

get_config(
    name: Optional[str] = None,
    description: Optional[str] = None,
    requirements: Optional[list[str]] = None,
    tags: Optional[list[str]] = None,
    output_extension: Optional[str] = None,
    is_async: bool = False,
    output_directory: Optional[str] = None,
    cache_seed: Optional[int] = None,
    structured_io: bool = False,
    skip_patch_io: bool = True,
) -> ExportConfig

Get export config or return default.

Parameters:

NameTypeDescriptionDefault
nameOptional[str]

The name of the export, by default None

None
descriptionOptional[str]

A brief description of the export, by default None

None
requirementsOptional[list[str]]

A list of requirements for the export, by default None

None
tagsOptional[list[str]]

A list of tags associated with the export, by default None

None
output_extensionOptional[str]

The file extension for the output, by default None

None
is_asyncbool

Whether the export is asynchronous, by default False

False
output_directoryOptional[str]

The directory where the output will be saved, by default None

None
cache_seedOptional[int]

The seed for caching, by default None

None
structured_iobool

Whether to use structured I/O, by default False

False
skip_patch_iobool

Whether to skip patching I/O, by default True

True

Returns:

TypeDescription
ExportConfig

The export configuration.

Source code in waldiez/exporting/core/context.py
def get_config(
    self,
    name: Optional[str] = None,
    description: Optional[str] = None,
    requirements: Optional[list[str]] = None,
    tags: Optional[list[str]] = None,
    output_extension: Optional[str] = None,
    is_async: bool = False,
    output_directory: Optional[str] = None,
    cache_seed: Optional[int] = None,
    structured_io: bool = False,
    skip_patch_io: bool = True,
) -> ExportConfig:
    """Get export config or return default.

    Parameters
    ----------
    name : Optional[str], optional
        The name of the export, by default None
    description : Optional[str], optional
        A brief description of the export, by default None
    requirements : Optional[list[str]], optional
        A list of requirements for the export, by default None
    tags : Optional[list[str]], optional
        A list of tags associated with the export, by default None
    output_extension : Optional[str], optional
        The file extension for the output, by default None
    is_async : bool, optional
        Whether the export is asynchronous, by default False
    output_directory : Optional[str], optional
        The directory where the output will be saved, by default None
    cache_seed : Optional[int], optional
        The seed for caching, by default None
    structured_io : bool, optional
        Whether to use structured I/O, by default False
    skip_patch_io : bool, optional
        Whether to skip patching I/O, by default True

    Returns
    -------
    ExportConfig
        The export configuration.
    """
    kwargs: dict[str, Any] = {
        "requirements": requirements or [],
        "tags": tags or [],
        "is_async": self.config.is_async if self.config else is_async,
        "structured_io": (
            self.config.structured_io if self.config else structured_io
        ),
        "skip_patch_io": (
            self.config.skip_patch_io if self.config else skip_patch_io
        ),
    }
    if output_extension is not None:
        kwargs["output_extension"] = output_extension
    if output_directory is not None:
        kwargs["output_directory"] = output_directory
    if cache_seed is not None:
        kwargs["cache_seed"] = cache_seed
    if name is not None:
        kwargs["name"] = name
    if description is not None:
        kwargs["description"] = description
    if self.config is not None:
        self.config.update(**kwargs)
    else:
        self.config = ExportConfig.create(**kwargs)
    return self.config

get_logger

get_logger() -> ExportingLogger

Get logger or create a default one.

Returns:

TypeDescription
ExportingLogger

The logger instance.

Source code in waldiez/exporting/core/context.py
def get_logger(self) -> ExportingLogger:
    """Get logger or create a default one.

    Returns
    -------
    ExportingLogger
        The logger instance.
    """
    return self.logger or WaldiezLogger()

get_path_resolver

get_path_resolver() -> PathResolver

Get path resolver or return default.

Returns:

TypeDescription
PathResolver

The path resolver instance.

Source code in waldiez/exporting/core/context.py
def get_path_resolver(self) -> PathResolver:
    """Get path resolver or return default.

    Returns
    -------
    PathResolver
        The path resolver instance.
    """
    return self.path_resolver or DefaultPathResolver()

get_serializer

get_serializer() -> Serializer

Get serializer or raise if not set.

Returns:

TypeDescription
Serializer

The serializer instance.

Source code in waldiez/exporting/core/context.py
def get_serializer(self) -> Serializer:
    """Get serializer or raise if not set.

    Returns
    -------
    Serializer
        The serializer instance.
    """
    return self.serializer or DefaultSerializer()

set_config

set_config(config: ExportConfig) -> None

Set the export configuration.

Parameters:

NameTypeDescriptionDefault
configExportConfig

The export configuration to set.

required
Source code in waldiez/exporting/core/context.py
def set_config(self, config: ExportConfig) -> None:
    """Set the export configuration.

    Parameters
    ----------
    config : ExportConfig
        The export configuration to set.
    """
    self.config = config

ExporterError

Bases: Exception

Base exception for exporter errors.

ExporterInitializationError

Bases: ExporterError

Exception raised when exporter initialization fails.

ExporterValidationError

Bases: ExporterError

Exception raised when export validation fails.

ExportingLogger

Bases: Protocol

Protocol for logging during exporting.

critical

critical(message: Any, *args: Any, **kwargs: Any) -> None

Log a critical error message.

Parameters:

NameTypeDescriptionDefault
messageAny

The critical error message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def critical(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log a critical error message.

    Parameters
    ----------
    message : Any
        The critical error message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """
    self.log(message, *args, level="critical", **kwargs)

debug

debug(message: Any, *args: Any, **kwargs: Any) -> None

Log a debug message.

Parameters:

NameTypeDescriptionDefault
messageAny

The debug message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def debug(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log a debug message.

    Parameters
    ----------
    message : Any
        The debug message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """
    self.log(message, *args, level="debug", **kwargs)

error

error(message: Any, *args: Any, **kwargs: Any) -> None

Log an error message.

Parameters:

NameTypeDescriptionDefault
messageAny

The error message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def error(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log an error message.

    Parameters
    ----------
    message : Any
        The error message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

exception

exception(message: Any, *args: Any, **kwargs: Any) -> None

Log an exception message.

Parameters:

NameTypeDescriptionDefault
messageAny

The exception message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def exception(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log an exception message.

    Parameters
    ----------
    message : Any
        The exception message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """
    self.log(message, *args, level="exception", **kwargs)

get_level

get_level() -> str

Get the current logging level.

Returns:

TypeDescription
str

The current logging level.

Source code in waldiez/exporting/core/protocols.py
def get_level(self) -> str:  # pyright: ignore
    """Get the current logging level.

    Returns
    -------
    str
        The current logging level.
    """

info

info(message: Any, *args: Any, **kwargs: Any) -> None

Log an informational message.

Parameters:

NameTypeDescriptionDefault
messageAny

The informational message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def info(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log an informational message.

    Parameters
    ----------
    message : Any
        The informational message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

log

log(
    message: Any,
    *args: Any,
    level: str = "info",
    **kwargs: Any
) -> None

Log a message with the specified level.

Parameters:

NameTypeDescriptionDefault
messageAny

The message to log or message template for formatting.

required
levelstr

The logging level to use (e.g., "debug", "info", "warning", "error", "critical"). Defaults to "info".

'info'
*argsAny

Arguments to format into the message using % formatting.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def log(
    self, message: Any, *args: Any, level: str = "info", **kwargs: Any
) -> None:
    """Log a message with the specified level.

    Parameters
    ----------
    message : Any
        The message to log or message template for formatting.
    level : str, optional
        The logging level to use (e.g., "debug", "info", "warning", "error",
        "critical"). Defaults to "info".
    *args : Any
        Arguments to format into the message using % formatting.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

set_level

set_level(level: str) -> None

Set the logging level.

Parameters:

NameTypeDescriptionDefault
levelstr

The logging level to set (e.g., "debug", "info", "warning", "error", "critical").

required

Raises:

TypeDescription
ValueError

If the provided level is invalid.

Source code in waldiez/exporting/core/protocols.py
def set_level(self, level: str) -> None:
    """Set the logging level.

    Parameters
    ----------
    level : str
        The logging level to set
        (e.g., "debug", "info", "warning", "error", "critical").

    Raises
    ------
    ValueError
        If the provided level is invalid.
    """

success

success(message: Any, *args: Any, **kwargs: Any) -> None

Log a success message.

Parameters:

NameTypeDescriptionDefault
messageAny

The success message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def success(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log a success message.

    Parameters
    ----------
    message : Any
        The success message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

warning

warning(message: Any, *args: Any, **kwargs: Any) -> None

Log a warning message.

Parameters:

NameTypeDescriptionDefault
messageAny

The warning message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def warning(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log a warning message.

    Parameters
    ----------
    message : Any
        The warning message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

GroupManagerExtras dataclass

GroupManagerExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    strategy: GroupManagerStrategy = PATTERN,
    pattern_definition: str = "",
    pattern_class_name: str = "AutoPattern",
    pattern_imports: set[str] = set[str](),
    group_chat_definition: str = "",
    group_chat_name: str = "",
    group_chat_argument: str = "",
    custom_speaker_selection: str = "",
    context_variables_content: str = "",
    after_work_content: str = "",
)

Bases: StandardExtras

Extras for group manager agents.

has_specific_content

has_specific_content() -> bool

Check if group manager has specific content.

Returns:

TypeDescription
bool

True if there is specific content for the group manager,

Source code in waldiez/exporting/core/extras/agent_extras/group_manager_extras.py
def has_specific_content(self) -> bool:
    """Check if group manager has specific content.

    Returns
    -------
    bool
        True if there is specific content for the group manager,
    """
    if not super().has_specific_content():
        return bool(
            self.pattern_definition.strip()
            or self.group_chat_definition.strip()
            or self.custom_speaker_selection.strip()
        )
    return True

GroupManagerStrategy

Bases: Enum

Strategy for group manager agent.

ImportPosition

Bases: Enum

Position for import statements in the generated code.

ImportStatement dataclass

ImportStatement(
    statement: str,
    position: ImportPosition = THIRD_PARTY,
    metadata: Optional[dict[str, Any]] = None,
)

Represents an import statement with its position.

InstanceArgument dataclass

InstanceArgument(
    instance_id: str,
    name: str,
    value: Any,
    tabs: int = 0,
    tabs_length: int = 4,
    with_new_line_before: bool = False,
    with_new_line_after: bool = False,
    with_new_line_if_empty: bool = False,
    skip_if_empty_string: bool = True,
    comment: Optional[str] = None,
)

Represents an instance argument for an agent, model or tool.

get_content

get_content(
    prepend_new_line: bool = False,
    append_new_line: bool = False,
) -> str

Get the content representation of the instance argument.

Parameters:

NameTypeDescriptionDefault
prepend_new_linebool

Whether to prepend a new line before the content, by default False.

False
append_new_linebool

Whether to append a new line at the end of the content, by default False.

False

Returns:

TypeDescription
str

The formatted content string for the instance argument.

Source code in waldiez/exporting/core/types.py
def get_content(
    self,
    prepend_new_line: bool = False,
    append_new_line: bool = False,
) -> str:
    """Get the content representation of the instance argument.

    Parameters
    ----------
    prepend_new_line : bool, optional
        Whether to prepend a new line before the content,
        by default False.
    append_new_line : bool, optional
        Whether to append a new line at the end of the content,
        by default False.

    Returns
    -------
    str
        The formatted content string for the instance argument.
    """
    if (
        self.skip_if_empty_string
        and isinstance(self.value, str)
        and not self.value.strip()
    ):
        return "\n" if self.with_new_line_if_empty else ""
    space = " " * (self.tabs * self.tabs_length)
    content = f"{space}{self.name}={self.value}," + (
        f"  # {self.comment}" if self.comment else ""
    )
    if self.with_new_line_before or prepend_new_line:
        content = "\n" + content
    if self.with_new_line_after or append_new_line:
        content += "\n"
    return content

has_content

has_content() -> bool

Check if the instance argument has content.

Returns:

TypeDescription
bool

True if the instance argument has content, otherwise False.

Source code in waldiez/exporting/core/types.py
def has_content(self) -> bool:
    """Check if the instance argument has content.

    Returns
    -------
    bool
        True if the instance argument has content, otherwise False.
    """
    if self.skip_if_empty_string and isinstance(self.value, str):
        return bool(self.value.strip())
    return self.value is not None and self.value != ""

ModelExtras dataclass

ModelExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    llm_config: Optional[dict[str, Any]] = None,
    config_file_path: str = "",
)

Bases: BaseExtras

Extras for model exporters.

get_content

get_content() -> str

Get the content of the LLM configuration.

Returns:

TypeDescription
str

The serialized LLM configuration.

Source code in waldiez/exporting/core/extras/model_extras.py
def get_content(self) -> str:
    """Get the content of the LLM configuration.

    Returns
    -------
    str
        The serialized LLM configuration.
    """
    if self.llm_config and "content" in self.llm_config:
        return self.llm_config["content"]
    return ""

has_specific_content

has_specific_content() -> bool

Check for model specific content.

Returns:

TypeDescription
bool

True if there's model specific content.

Source code in waldiez/exporting/core/extras/model_extras.py
def has_specific_content(self) -> bool:
    """Check for model specific content.

    Returns
    -------
    bool
        True if there's model specific content.
    """
    if self.llm_config and "content" in self.llm_config:
        return bool(self.llm_config["content"])
    return False

set_config_file_path

set_config_file_path(path: str) -> None

Set the configuration file path.

Parameters:

NameTypeDescriptionDefault
pathstr

The configuration file path.

required
Source code in waldiez/exporting/core/extras/model_extras.py
def set_config_file_path(self, path: str) -> None:
    """Set the configuration file path.

    Parameters
    ----------
    path : str
        The configuration file path.
    """
    self.config_file_path = path

set_llm_config

set_llm_config(config: dict[str, Any]) -> None

Set the LLM configuration.

Parameters:

NameTypeDescriptionDefault
configdict[str, Any]

The LLM configuration.

required
Source code in waldiez/exporting/core/extras/model_extras.py
def set_llm_config(self, config: dict[str, Any]) -> None:
    """Set the LLM configuration.

    Parameters
    ----------
    config : dict[str, Any]
        The LLM configuration.
    """
    self.llm_config = config

PathResolver

Bases: Protocol

Protocol for resolving a path.

resolve

resolve(path: str) -> str

Resolve a path.

Parameters:

NameTypeDescriptionDefault
pathstr

The path to resolve.

required

Returns:

TypeDescription
str

The resolved path.

Raises:

TypeDescription
ValueError

If the path cannot be resolved.

Source code in waldiez/exporting/core/protocols.py
def resolve(self, path: str) -> str:  # pyright: ignore
    """Resolve a path.

    Parameters
    ----------
    path : str
        The path to resolve.

    Returns
    -------
    str
        The resolved path.

    Raises
    ------
    ValueError
        If the path cannot be resolved.
    """

PositionedContent dataclass

PositionedContent(
    content: str,
    position: ExportPosition,
    order: int = 0,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    metadata: dict[str, Any] = dict[str, Any](),
)

Content with position and ordering metadata.

is_agent_positioned

is_agent_positioned() -> bool

Check if this content is positioned relative to an agent.

Returns:

TypeDescription
bool

True if this content has an agent ID and position, otherwise False.

Source code in waldiez/exporting/core/content.py
def is_agent_positioned(self) -> bool:
    """Check if this content is positioned relative to an agent.

    Returns
    -------
    bool
        True if this content has an agent ID and position, otherwise False.
    """
    return self.agent_position is not None and self.agent_id is not None

RAGUserExtras dataclass

RAGUserExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    before_content: str = "",
    imports: set[str] = set[str](),
)

Bases: StandardExtras

RAG configuration.

has_specific_content

has_specific_content() -> bool

Check if there's any RAG content.

Returns:

TypeDescription
bool

True if there's any RAG configuration.

Source code in waldiez/exporting/core/extras/agent_extras/rag_user_extras.py
def has_specific_content(self) -> bool:
    """Check if there's any RAG content.

    Returns
    -------
    bool
        True if there's any RAG configuration.
    """
    if not super().has_specific_content():
        return bool(
            self.extra_args or self.before_content.strip() or self.imports
        )
    return True

ReasoningExtras dataclass

ReasoningExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
)

Bases: StandardExtras

Extras for reasoning agents.

has_specific_content

has_specific_content() -> bool

Check for reasoning specific content.

Returns:

TypeDescription
bool

True if there's reasoning specific content.

Source code in waldiez/exporting/core/extras/agent_extras/reasoning_extras.py
def has_specific_content(self) -> bool:
    """Check for reasoning specific content.

    Returns
    -------
    bool
        True if there's reasoning specific content.
    """
    if not super().has_specific_content():
        return bool(
            self.extra_args
            or self.extra_imports
            or self.before_agent.strip()
            or self.after_agent.strip()
        )
    return True

Serializer

Bases: Protocol

Protocol for serialization components.

serialize

serialize(obj: Any, **kwargs: Any) -> str

Serialize an object to string representation.

Parameters:

NameTypeDescriptionDefault
objAny

The object to serialize.

required
**kwargsAny

Additional keyword arguments for serialization.

{}

Returns:

TypeDescription
str

The serialized representation.

Source code in waldiez/exporting/core/protocols.py
def serialize(self, obj: Any, **kwargs: Any) -> str:  # pyright: ignore
    """Serialize an object to string representation.

    Parameters
    ----------
    obj : Any
        The object to serialize.
    **kwargs : Any
        Additional keyword arguments for serialization.

    Returns
    -------
    str
        The serialized representation.
    """

SimpleExporter

SimpleExporter(
    context: Optional[ExporterContext] = None, **kwargs: Any
)

Bases: Exporter[None]

Simple exporter that doesn't use extras system.

Source code in waldiez/exporting/core/exporter.py
def __init__(
    self,
    context: Optional[ExporterContext] = None,
    **kwargs: Any,
):
    """Initialize the exporter.

    Parameters
    ----------
    context : Optional[ExporterContext], optional
        The exporter context with dependencies, by default None
    **kwargs : Any
        Additional keyword arguments for subclasses.
    """
    self._context = context or DefaultExporterContext(
        config=ExportConfig.create(**kwargs)
    )
    config = self._context.get_config()
    config.update(**kwargs)
    self._context.set_config(config)
    self._result = ExportResult()
    self._initialized = False
    self._builder = ExportResultBuilder()
    self.config = self._context.get_config()

    # Allow subclasses to handle additional kwargs
    self._handle_kwargs(**kwargs)

extras property

extras: None

Simple exporters don't have extras.

StandardExtras dataclass

StandardExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
)

Bases: BaseExtras

Extras for standard agents (UserProxy, Assistant, etc.).

get_code_execution_arg

get_code_execution_arg() -> InstanceArgument

Get the code execution argument string.

Returns:

TypeDescription
InstanceArgument

The code execution argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_code_execution_arg(self) -> InstanceArgument:
    """Get the code execution argument string.

    Returns
    -------
    InstanceArgument
        The code execution argument.
    """
    if (
        self.code_execution_config
        and self.code_execution_config.executor_argument
    ):
        argunent = self.code_execution_config.executor_argument
    else:
        argunent = "False"
    return InstanceArgument(
        instance_id=self.instance_id,
        name="code_execution_config",
        value=argunent,
        tabs=1,
    )

get_system_message_arg

get_system_message_arg() -> InstanceArgument

Get the system message argument.

Returns:

TypeDescription
InstanceArgument

The system message argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_system_message_arg(self) -> InstanceArgument:
    """Get the system message argument.

    Returns
    -------
    InstanceArgument
        The system message argument.
    """
    if (
        self.system_message_config
        and self.system_message_config.system_message_arg
    ):
        argument = self.system_message_config.system_message_arg
    else:
        argument = ""
    return InstanceArgument(
        instance_id=self.instance_id,
        name="system_message",
        value=argument,
        skip_if_empty_string=True,
        with_new_line_before=True,
        tabs=1,
    )

get_termination_arg

get_termination_arg() -> InstanceArgument

Get the termination argument.

Returns:

TypeDescription
InstanceArgument

The termination argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_termination_arg(self) -> InstanceArgument:
    """Get the termination argument.

    Returns
    -------
    InstanceArgument
        The termination argument.
    """
    if self.termination_config and self.termination_config.termination_arg:
        argument = self.termination_config.termination_arg
    else:
        argument = "None"
    comment: str | None = None
    if argument == "None":
        comment = "pyright: ignore"
    return InstanceArgument(
        instance_id=self.instance_id,
        name="is_termination_msg",
        value=argument,
        comment=comment,
        tabs=1,
    )

has_specific_content

has_specific_content() -> bool

Check for standard agent specific content.

Returns:

TypeDescription
bool

True if there's standard agent specific content.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_specific_content(self) -> bool:
    """Check for standard agent specific content.

    Returns
    -------
    bool
        True if there's standard agent specific content.
    """
    return bool(
        self.extra_args
        or (
            self.code_execution_config
            and self.code_execution_config.has_content()
        )
        or (
            self.termination_config
            and self.termination_config.has_content()
        )
        or (
            self.system_message_config
            and self.system_message_config.has_content()
        )
    )

set_code_execution

set_code_execution(config: CodeExecutionConfig) -> None

Set code execution configuration.

Parameters:

NameTypeDescriptionDefault
configCodeExecutionConfig

The code execution configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_code_execution(self, config: CodeExecutionConfig) -> None:
    """Set code execution configuration.

    Parameters
    ----------
    config : CodeExecutionConfig
        The code execution configuration.
    """
    self.code_execution_config = config
    if config.executor_import:
        self.add_import(config.executor_import)
    # we either add the executor content here or
    # in _contribute_specific_content below
    if config.executor_content:
        self.append_before_agent(config.executor_content)

set_system_message_config

set_system_message_config(
    config: SystemMessageConfig,
) -> None

Set system message configuration.

Parameters:

NameTypeDescriptionDefault
configSystemMessageConfig

The system message configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_system_message_config(self, config: SystemMessageConfig) -> None:
    """Set system message configuration.

    Parameters
    ----------
    config : SystemMessageConfig
        The system message configuration.
    """
    self.system_message_config = config
    if config.before_agent_conent:
        self.append_before_agent(config.before_agent_conent)

set_termination_config

set_termination_config(config: TerminationConfig) -> None

Set termination configuration.

Parameters:

NameTypeDescriptionDefault
configTerminationConfig

The termination configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_termination_config(self, config: TerminationConfig) -> None:
    """Set termination configuration.

    Parameters
    ----------
    config : TerminationConfig
        The termination configuration.
    """
    self.termination_config = config
    if config.before_content:
        self.append_before_agent(config.before_content)

SystemMessageConfig dataclass

SystemMessageConfig(
    before_agent_conent: str = "",
    system_message_arg: str = "",
)

System message configuration.

has_content

has_content() -> bool

Check if there's any system message content.

Returns:

TypeDescription
bool

True if there's any system message configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any system message content.

    Returns
    -------
    bool
        True if there's any system message configuration.
    """
    return bool(str(self.system_message_arg).strip())

TerminationConfig dataclass

TerminationConfig(
    termination_arg: str = "None", before_content: str = ""
)

Termination configuration.

has_content

has_content() -> bool

Check if there's any termination content.

Returns:

TypeDescription
bool

True if there's any termination configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any termination content.

    Returns
    -------
    bool
        True if there's any termination configuration.
    """
    return bool(self.before_content.strip())

ToolExtras dataclass

ToolExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    function_content: str = "",
    registration_content: str = "",
)

Bases: BaseExtras

Extras for tool exporters.

add_function_content

add_function_content(content: str) -> None

Add function definition content.

Parameters:

NameTypeDescriptionDefault
contentstr

The function content to add.

required
Source code in waldiez/exporting/core/extras/tool_extras.py
def add_function_content(self, content: str) -> None:
    """Add function definition content.

    Parameters
    ----------
    content : str
        The function content to add.
    """
    if content and content.strip():  # pragma: no branch
        if self.function_content:
            self.function_content += "\n\n" + content.rstrip()
        else:
            self.function_content = content.rstrip()
        while not self.function_content.endswith("\n\n"):
            self.function_content += "\n\n"

add_registration_content

add_registration_content(content: str) -> None

Add function registration content.

Parameters:

NameTypeDescriptionDefault
contentstr

The registration content to add.

required
Source code in waldiez/exporting/core/extras/tool_extras.py
def add_registration_content(self, content: str) -> None:
    """Add function registration content.

    Parameters
    ----------
    content : str
        The registration content to add.
    """
    if content and content.strip():  # pragma: no branch
        self.registration_content += "\n" + content.rstrip() + "\n"

has_specific_content

has_specific_content() -> bool

Check for tool specific content.

Returns:

TypeDescription
bool

True if there's tool specific content.

Source code in waldiez/exporting/core/extras/tool_extras.py
def has_specific_content(self) -> bool:
    """Check for tool specific content.

    Returns
    -------
    bool
        True if there's tool specific content.
    """
    return bool(
        self.function_content.strip() or self.registration_content.strip()
    )

ValidationError dataclass

ValidationError(
    message: str,
    severity: str = "error",
    location: Optional[str] = None,
    suggestion: Optional[str] = None,
)

Represents a validation error.

ValidationResult dataclass

ValidationResult(
    is_valid: bool,
    errors: list[ValidationError] = list[ValidationError](),
    warnings: list[ValidationError] = list[
        ValidationError
    ](),
)

Result of validation operations.

add_error

add_error(
    message: str,
    location: Optional[str] = None,
    suggestion: Optional[str] = None,
) -> None

Add a validation error.

Parameters:

NameTypeDescriptionDefault
messagestr

The error message to add.

required
locationOptional[str]

The location in the code where the error occurred, by default None

None
suggestionOptional[str]

A suggestion for fixing the error, by default None

None
Source code in waldiez/exporting/core/validation.py
def add_error(
    self,
    message: str,
    location: Optional[str] = None,
    suggestion: Optional[str] = None,
) -> None:
    """Add a validation error.

    Parameters
    ----------
    message : str
        The error message to add.
    location : Optional[str], optional
        The location in the code where the error occurred, by default None
    suggestion : Optional[str], optional
        A suggestion for fixing the error, by default None
    """
    self.errors.append(
        ValidationError(message, "error", location, suggestion)
    )
    self.is_valid = False

add_warning

add_warning(
    message: str, location: Optional[str] = None
) -> None

Add a validation warning.

Parameters:

NameTypeDescriptionDefault
messagestr

The warning message to add.

required
locationOptional[str]

The location in the code where the warning occurred, by default None

None
Source code in waldiez/exporting/core/validation.py
def add_warning(self, message: str, location: Optional[str] = None) -> None:
    """Add a validation warning.

    Parameters
    ----------
    message : str
        The warning message to add.
    location : Optional[str], optional
        The location in the code where the warning occurred, by default None
    """
    self.warnings.append(ValidationError(message, "warning", location))

has_errors

has_errors() -> bool

Check if there are any errors.

Returns:

TypeDescription
bool

True if there are validation errors, otherwise False.

Source code in waldiez/exporting/core/validation.py
def has_errors(self) -> bool:
    """Check if there are any errors.

    Returns
    -------
    bool
        True if there are validation errors, otherwise False.
    """
    return len(self.errors) > 0

has_warnings

has_warnings() -> bool

Check if there are any warnings.

Returns:

TypeDescription
bool

True if there are validation warnings, otherwise False.

Source code in waldiez/exporting/core/validation.py
def has_warnings(self) -> bool:
    """Check if there are any warnings.

    Returns
    -------
    bool
        True if there are validation warnings, otherwise False.
    """
    return len(self.warnings) > 0

merge

merge(other: ValidationResult) -> None

Merge another ValidationResult into this one.

Parameters:

NameTypeDescriptionDefault
otherValidationResult

The other validation result to merge.

required
Source code in waldiez/exporting/core/validation.py
def merge(self, other: "ValidationResult") -> None:
    """Merge another ValidationResult into this one.

    Parameters
    ----------
    other : ValidationResult
        The other validation result to merge.
    """
    self.is_valid = self.is_valid and other.is_valid
    self.errors.extend(other.errors)
    self.warnings.extend(other.warnings)

Validator

Bases: Protocol

Protocol for validation components.

validate

validate(content: Any) -> ValidationResult

Validate content and return result.

Parameters:

NameTypeDescriptionDefault
contentAny

The content to validate.

required

Returns:

TypeDescription
ValidationResult

The validation result.

Source code in waldiez/exporting/core/protocols.py
def validate(self, content: Any) -> ValidationResult:  # pyright: ignore
    """Validate content and return result.

    Parameters
    ----------
    content : Any
        The content to validate.

    Returns
    -------
    ValidationResult
        The validation result.
    """

constants

Constants for Waldiez exporting core.

content

Content module for Waldiez exporting core.

ContentMetadata dataclass

ContentMetadata(
    content_type: ContentType,
    source_id: Optional[str] = None,
    dependencies: list[str] = list[str](),
    tags: set[str] = set[str](),
)

Metadata about exported content.

PositionedContent dataclass

PositionedContent(
    content: str,
    position: ExportPosition,
    order: int = 0,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    metadata: dict[str, Any] = dict[str, Any](),
)

Content with position and ordering metadata.

is_agent_positioned

is_agent_positioned() -> bool

Check if this content is positioned relative to an agent.

Returns:

TypeDescription
bool

True if this content has an agent ID and position, otherwise False.

Source code in waldiez/exporting/core/content.py
def is_agent_positioned(self) -> bool:
    """Check if this content is positioned relative to an agent.

    Returns
    -------
    bool
        True if this content has an agent ID and position, otherwise False.
    """
    return self.agent_position is not None and self.agent_id is not None

context

Singleton context for exporters.

DefaultExporterContext

DefaultExporterContext(
    serializer: Optional[Serializer] = None,
    validator: Optional[Validator] = None,
    path_resolver: Optional[PathResolver] = None,
    logger: Optional[ExportingLogger] = None,
    config: Optional[ExportConfig] = None,
)

Bases: ExporterContext

Singleton context for exporters.

Provides a default configuration with standard serializer and escaper. Access via get_default_exporter_context() for proper initialization.

Note

This is a singleton - only one instance exists per application. Direct instantiation may not behave as expected.

Source code in waldiez/exporting/core/context.py
def __init__(
    self,
    serializer: Optional[Serializer] = None,
    validator: Optional[Validator] = None,
    path_resolver: Optional[PathResolver] = None,
    logger: Optional[ExportingLogger] = None,
    config: Optional[ExportConfig] = None,
) -> None:
    if hasattr(self, "_initialized"):
        return
    super().__init__(
        serializer=serializer or DefaultSerializer(),
        path_resolver=path_resolver or DefaultPathResolver(),
        logger=logger or WaldiezLogger(),
        validator=validator,
        config=config,
    )
    self._initialized = True

ExporterContext dataclass

ExporterContext(
    serializer: Optional[Serializer] = None,
    path_resolver: Optional[PathResolver] = None,
    validator: Optional[Validator] = None,
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
)

Context object containing common exporter dependencies.

get_config

get_config(
    name: Optional[str] = None,
    description: Optional[str] = None,
    requirements: Optional[list[str]] = None,
    tags: Optional[list[str]] = None,
    output_extension: Optional[str] = None,
    is_async: bool = False,
    output_directory: Optional[str] = None,
    cache_seed: Optional[int] = None,
    structured_io: bool = False,
    skip_patch_io: bool = True,
) -> ExportConfig

Get export config or return default.

Parameters:

NameTypeDescriptionDefault
nameOptional[str]

The name of the export, by default None

None
descriptionOptional[str]

A brief description of the export, by default None

None
requirementsOptional[list[str]]

A list of requirements for the export, by default None

None
tagsOptional[list[str]]

A list of tags associated with the export, by default None

None
output_extensionOptional[str]

The file extension for the output, by default None

None
is_asyncbool

Whether the export is asynchronous, by default False

False
output_directoryOptional[str]

The directory where the output will be saved, by default None

None
cache_seedOptional[int]

The seed for caching, by default None

None
structured_iobool

Whether to use structured I/O, by default False

False
skip_patch_iobool

Whether to skip patching I/O, by default True

True

Returns:

TypeDescription
ExportConfig

The export configuration.

Source code in waldiez/exporting/core/context.py
def get_config(
    self,
    name: Optional[str] = None,
    description: Optional[str] = None,
    requirements: Optional[list[str]] = None,
    tags: Optional[list[str]] = None,
    output_extension: Optional[str] = None,
    is_async: bool = False,
    output_directory: Optional[str] = None,
    cache_seed: Optional[int] = None,
    structured_io: bool = False,
    skip_patch_io: bool = True,
) -> ExportConfig:
    """Get export config or return default.

    Parameters
    ----------
    name : Optional[str], optional
        The name of the export, by default None
    description : Optional[str], optional
        A brief description of the export, by default None
    requirements : Optional[list[str]], optional
        A list of requirements for the export, by default None
    tags : Optional[list[str]], optional
        A list of tags associated with the export, by default None
    output_extension : Optional[str], optional
        The file extension for the output, by default None
    is_async : bool, optional
        Whether the export is asynchronous, by default False
    output_directory : Optional[str], optional
        The directory where the output will be saved, by default None
    cache_seed : Optional[int], optional
        The seed for caching, by default None
    structured_io : bool, optional
        Whether to use structured I/O, by default False
    skip_patch_io : bool, optional
        Whether to skip patching I/O, by default True

    Returns
    -------
    ExportConfig
        The export configuration.
    """
    kwargs: dict[str, Any] = {
        "requirements": requirements or [],
        "tags": tags or [],
        "is_async": self.config.is_async if self.config else is_async,
        "structured_io": (
            self.config.structured_io if self.config else structured_io
        ),
        "skip_patch_io": (
            self.config.skip_patch_io if self.config else skip_patch_io
        ),
    }
    if output_extension is not None:
        kwargs["output_extension"] = output_extension
    if output_directory is not None:
        kwargs["output_directory"] = output_directory
    if cache_seed is not None:
        kwargs["cache_seed"] = cache_seed
    if name is not None:
        kwargs["name"] = name
    if description is not None:
        kwargs["description"] = description
    if self.config is not None:
        self.config.update(**kwargs)
    else:
        self.config = ExportConfig.create(**kwargs)
    return self.config

get_logger

get_logger() -> ExportingLogger

Get logger or create a default one.

Returns:

TypeDescription
ExportingLogger

The logger instance.

Source code in waldiez/exporting/core/context.py
def get_logger(self) -> ExportingLogger:
    """Get logger or create a default one.

    Returns
    -------
    ExportingLogger
        The logger instance.
    """
    return self.logger or WaldiezLogger()

get_path_resolver

get_path_resolver() -> PathResolver

Get path resolver or return default.

Returns:

TypeDescription
PathResolver

The path resolver instance.

Source code in waldiez/exporting/core/context.py
def get_path_resolver(self) -> PathResolver:
    """Get path resolver or return default.

    Returns
    -------
    PathResolver
        The path resolver instance.
    """
    return self.path_resolver or DefaultPathResolver()

get_serializer

get_serializer() -> Serializer

Get serializer or raise if not set.

Returns:

TypeDescription
Serializer

The serializer instance.

Source code in waldiez/exporting/core/context.py
def get_serializer(self) -> Serializer:
    """Get serializer or raise if not set.

    Returns
    -------
    Serializer
        The serializer instance.
    """
    return self.serializer or DefaultSerializer()

set_config

set_config(config: ExportConfig) -> None

Set the export configuration.

Parameters:

NameTypeDescriptionDefault
configExportConfig

The export configuration to set.

required
Source code in waldiez/exporting/core/context.py
def set_config(self, config: ExportConfig) -> None:
    """Set the export configuration.

    Parameters
    ----------
    config : ExportConfig
        The export configuration to set.
    """
    self.config = config

create_exporter_context

create_exporter_context(
    serializer: Optional[Serializer] = None,
    validator: Optional[Validator] = None,
    path_resolver: Optional[PathResolver] = None,
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
) -> ExporterContext

Create an exporter context with the given components.

Parameters:

NameTypeDescriptionDefault
serializerOptional[Serializer]

The serializer component, by default None

None
path_resolverOptional[PathResolver]

The path resolver component, by default None

None
validatorOptional[Validator]

The validator component, by default None

None
configOptional[ExportConfig]

The export configuration, by default None

None
loggerOptional[ExportingLogger]

The logger instance, by default None

None

Returns:

TypeDescription
ExporterContext

The created context.

Source code in waldiez/exporting/core/context.py
def create_exporter_context(
    serializer: Optional[Serializer] = None,
    validator: Optional[Validator] = None,
    path_resolver: Optional[PathResolver] = None,
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
) -> ExporterContext:
    """Create an exporter context with the given components.

    Parameters
    ----------
    serializer : Optional[Serializer], optional
        The serializer component, by default None
    path_resolver : Optional[PathResolver], optional
        The path resolver component, by default None
    validator : Optional[Validator], optional
        The validator component, by default None
    config : Optional[ExportConfig], optional
        The export configuration, by default None
    logger : Optional[ExportingLogger], optional
        The logger instance, by default None

    Returns
    -------
    ExporterContext
        The created context.
    """
    return ExporterContext(
        serializer=serializer or DefaultSerializer(),
        path_resolver=path_resolver or DefaultPathResolver(),
        validator=validator,
        logger=logger or WaldiezLogger(),
        config=config,
    )

get_default_exporter_context

get_default_exporter_context(
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
) -> ExporterContext

Get the default exporter context.

Parameters:

NameTypeDescriptionDefault
configOptional[ExportConfig]

The export configuration, by default None

None
loggerOptional[ExportingLogger]

The logger instance, by default None

None

Returns:

TypeDescription
ExporterContext

The default exporter context.

Source code in waldiez/exporting/core/context.py
def get_default_exporter_context(
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
) -> ExporterContext:
    """Get the default exporter context.

    Parameters
    ----------
    config : Optional[ExportConfig], optional
        The export configuration, by default None
    logger : Optional[ExportingLogger], optional
        The logger instance, by default None

    Returns
    -------
    ExporterContext
        The default exporter context.
    """
    return DefaultExporterContext(
        serializer=DefaultSerializer(),
        path_resolver=DefaultPathResolver(),
        logger=logger or WaldiezLogger(),
        config=config,
    )

create_empty_result

create_empty_result() -> ExportResult

Create an empty ExportResult.

Returns:

TypeDescription
ExportResult

An empty ExportResult instance.

Source code in waldiez/exporting/core/result.py
def create_empty_result() -> ExportResult:
    """Create an empty ExportResult.

    Returns
    -------
    ExportResult
        An empty ExportResult instance.
    """
    return ExportResult()

create_exporter_context

create_exporter_context(
    serializer: Optional[Serializer] = None,
    validator: Optional[Validator] = None,
    path_resolver: Optional[PathResolver] = None,
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
) -> ExporterContext

Create an exporter context with the given components.

Parameters:

NameTypeDescriptionDefault
serializerOptional[Serializer]

The serializer component, by default None

None
path_resolverOptional[PathResolver]

The path resolver component, by default None

None
validatorOptional[Validator]

The validator component, by default None

None
configOptional[ExportConfig]

The export configuration, by default None

None
loggerOptional[ExportingLogger]

The logger instance, by default None

None

Returns:

TypeDescription
ExporterContext

The created context.

Source code in waldiez/exporting/core/context.py
def create_exporter_context(
    serializer: Optional[Serializer] = None,
    validator: Optional[Validator] = None,
    path_resolver: Optional[PathResolver] = None,
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
) -> ExporterContext:
    """Create an exporter context with the given components.

    Parameters
    ----------
    serializer : Optional[Serializer], optional
        The serializer component, by default None
    path_resolver : Optional[PathResolver], optional
        The path resolver component, by default None
    validator : Optional[Validator], optional
        The validator component, by default None
    config : Optional[ExportConfig], optional
        The export configuration, by default None
    logger : Optional[ExportingLogger], optional
        The logger instance, by default None

    Returns
    -------
    ExporterContext
        The created context.
    """
    return ExporterContext(
        serializer=serializer or DefaultSerializer(),
        path_resolver=path_resolver or DefaultPathResolver(),
        validator=validator,
        logger=logger or WaldiezLogger(),
        config=config,
    )

create_result_with_content

create_result_with_content(
    main_content: str, imports: Optional[list[str]] = None
) -> ExportResult

Create an ExportResult with basic content.

Parameters:

NameTypeDescriptionDefault
main_contentstr

The main content.

required
importsOptional[list[str]]

list of import statements, by default None

None

Returns:

TypeDescription
ExportResult

The created ExportResult.

Source code in waldiez/exporting/core/result.py
def create_result_with_content(
    main_content: str,
    imports: Optional[list[str]] = None,
) -> ExportResult:
    """Create an ExportResult with basic content.

    Parameters
    ----------
    main_content : str
        The main content.
    imports : Optional[list[str]], optional
        list of import statements, by default None

    Returns
    -------
    ExportResult
        The created ExportResult.
    """
    result = ExportResult(main_content=main_content)

    if imports:
        result.add_imports(imports)

    return result

enums

Enums for Waldiez exporting core.

AgentPosition

Bases: Enum

Position relative to a specific agent.

ContentOrder

Bases: Enum

Standard ordering for positioned content.

ContentType

Bases: Enum

Type of content being exported.

ExportPosition

Bases: Enum

Position for content in the exported code.

Attributes:

NameTypeDescription
TOPint

Position at the top of the file, typically for comments or metadata.

IMPORTSint

Position for import statements.

TOOLSint

Position for tool definitions.

MODELSint

Position for model configurations (llm_config).

AGENTSint

Position for agent definitions.

CHATSint

Position for chat/connection definitions.

BOTTOMint

Position at the bottom of the file, typically for main execution or final code.

GroupManagerStrategy

Bases: Enum

Strategy for group manager agent.

ImportPosition

Bases: Enum

Position for import statements in the generated code.

errors

Exporter core exceptions module.

ExporterContentError

Bases: ExporterError

Exception raised when content generation fails.

ExporterError

Bases: Exception

Base exception for exporter errors.

ExporterInitializationError

Bases: ExporterError

Exception raised when exporter initialization fails.

ExporterValidationError

Bases: ExporterError

Exception raised when export validation fails.

exporter

Base exporter classes.

Exporter

Exporter(
    context: Optional[ExporterContext] = None, **kwargs: Any
)

Bases: ABC, Generic[Extras]

Exporter base class with structured extras and clean interface.

Parameters:

NameTypeDescriptionDefault
contextOptional[ExporterContext]

The exporter context with dependencies, by default None

None
**kwargsAny

Additional keyword arguments for subclasses.

{}
Source code in waldiez/exporting/core/exporter.py
def __init__(
    self,
    context: Optional[ExporterContext] = None,
    **kwargs: Any,
):
    """Initialize the exporter.

    Parameters
    ----------
    context : Optional[ExporterContext], optional
        The exporter context with dependencies, by default None
    **kwargs : Any
        Additional keyword arguments for subclasses.
    """
    self._context = context or DefaultExporterContext(
        config=ExportConfig.create(**kwargs)
    )
    config = self._context.get_config()
    config.update(**kwargs)
    self._context.set_config(config)
    self._result = ExportResult()
    self._initialized = False
    self._builder = ExportResultBuilder()
    self.config = self._context.get_config()

    # Allow subclasses to handle additional kwargs
    self._handle_kwargs(**kwargs)

add_content

add_content(
    content: str,
    position: ExportPosition,
    order: ContentOrder = MAIN_CONTENT,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    skip_strip: bool | None = None,
    **metadata: Any
) -> None

Add positioned content.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to add.

required
positionExportPosition

The position of the content.

required
orderint

The order within the position, by default 0

MAIN_CONTENT
agent_idOptional[str]

Agent ID for agent-relative positioning, by default None

None
agent_positionOptional[AgentPosition]

Position relative to agent, by default None

None
skip_stripbool | None

Whether to skip stripping whitespace, by default None If None, defaults to True for CHATS position (keep identation),

None
**metadataAny

Additional metadata for the content.

{}
Source code in waldiez/exporting/core/exporter.py
def add_content(
    self,
    content: str,
    position: ExportPosition,
    order: ContentOrder = ContentOrder.MAIN_CONTENT,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    skip_strip: bool | None = None,
    **metadata: Any,
) -> None:
    """Add positioned content.

    Parameters
    ----------
    content : str
        The content to add.
    position : ExportPosition
        The position of the content.
    order : int, optional
        The order within the position, by default 0
    agent_id : Optional[str], optional
        Agent ID for agent-relative positioning, by default None
    agent_position : Optional[AgentPosition], optional
        Position relative to agent, by default None
    skip_strip : bool | None, optional
        Whether to skip stripping whitespace, by default None
        If None, defaults to True for CHATS position (keep identation),
    **metadata : Any
        Additional metadata for the content.
    """
    if skip_strip is None:
        skip_strip = position == ExportPosition.CHATS
    self._result.add_content(
        content=content,
        position=position,
        order=order,
        agent_id=agent_id,
        agent_position=agent_position,
        skip_strip=skip_strip,
        **metadata,
    )

add_env_var

add_env_var(
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
) -> None

Add environment variable.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the environment variable.

required
valuestr

The value of the environment variable.

required
descriptionOptional[str]

Description of the variable, by default None

None
requiredbool

Whether the variable is required, by default True

True
Source code in waldiez/exporting/core/exporter.py
def add_env_var(
    self,
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
) -> None:
    """Add environment variable.

    Parameters
    ----------
    name : str
        The name of the environment variable.
    value : str
        The value of the environment variable.
    description : Optional[str], optional
        Description of the variable, by default None
    required : bool, optional
        Whether the variable is required, by default True
    """
    self._result.add_env_var(name, value, description, required)

add_import

add_import(
    statement: str,
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None

Add an import statement.

Parameters:

NameTypeDescriptionDefault
statementstr

The import statement to add.

required
positionImportPosition

The position of the import, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION
Source code in waldiez/exporting/core/exporter.py
def add_import(
    self,
    statement: str,
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None:
    """Add an import statement.

    Parameters
    ----------
    statement : str
        The import statement to add.
    position : ImportPosition, optional
        The position of the import, by default THIRD_PARTY
    """
    self._result.add_import(statement, position)

add_imports

add_imports(
    statements: set[str],
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None

Add multiple import statements.

Parameters:

NameTypeDescriptionDefault
statementsSet[str]

The import statements to add.

required
positionImportPosition

The position of the imports, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION
Source code in waldiez/exporting/core/exporter.py
def add_imports(
    self,
    statements: set[str],
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None:
    """Add multiple import statements.

    Parameters
    ----------
    statements : Set[str]
        The import statements to add.
    position : ImportPosition, optional
        The position of the imports, by default THIRD_PARTY
    """
    self._result.add_imports(statements, position)

clear

clear() -> None

Clear all export content and reset initialization state.

Source code in waldiez/exporting/core/exporter.py
def clear(self) -> None:
    """Clear all export content and reset initialization state."""
    self._result.clear()
    self._initialized = False

context property

context: ExporterContext

Get the exporter context.

Returns:

TypeDescription
ExporterContext

The exporter context.

export

export() -> ExportResult

Export and return the complete result.

Returns:

TypeDescription
ExportResult

The complete export result.

Source code in waldiez/exporting/core/exporter.py
def export(self) -> ExportResult:
    """Export and return the complete result.

    Returns
    -------
    ExportResult
        The complete export result.
    """
    self._ensure_initialized()
    return self._result

extras abstractmethod property

extras: Extras

Get the structured extras for this exporter.

Returns:

TypeDescription
Extras

The extras instance.

generate_main_content abstractmethod

generate_main_content() -> Optional[str]

Generate the main export content.

Returns:

TypeDescription
Optional[str]

The main content, or None if no content should be generated.

Source code in waldiez/exporting/core/exporter.py
@abc.abstractmethod
def generate_main_content(self) -> Optional[str]:
    """Generate the main export content.

    Returns
    -------
    Optional[str]
        The main content, or None if no content should be generated.
    """

get_content_by_position

get_content_by_position(
    position: ExportPosition,
) -> list[PositionedContent]

Get content for a specific position.

Parameters:

NameTypeDescriptionDefault
positionExportPosition

The position to filter by.

required

Returns:

TypeDescription
List[PositionedContent]

List of content for the specified position.

Source code in waldiez/exporting/core/exporter.py
def get_content_by_position(
    self, position: ExportPosition
) -> list[PositionedContent]:
    """Get content for a specific position.

    Parameters
    ----------
    position : ExportPosition
        The position to filter by.

    Returns
    -------
    List[PositionedContent]
        List of content for the specified position.
    """
    self._ensure_initialized()
    return self._result.get_content_by_position(position)

get_environment_variables

get_environment_variables() -> list[EnvironmentVariable]

Get environment variables.

Returns:

TypeDescription
List[EnvironmentVariable]

List of environment variables.

Source code in waldiez/exporting/core/exporter.py
def get_environment_variables(self) -> list[EnvironmentVariable]:
    """Get environment variables.

    Returns
    -------
    List[EnvironmentVariable]
        List of environment variables.
    """
    self._ensure_initialized()
    return self._result.environment_variables

get_imports

get_imports() -> list[ImportStatement]

Get sorted imports.

Returns:

TypeDescription
List[ImportStatement]

Sorted list of import statements.

Source code in waldiez/exporting/core/exporter.py
def get_imports(self) -> list[ImportStatement]:
    """Get sorted imports.

    Returns
    -------
    List[ImportStatement]
        Sorted list of import statements.
    """
    self._ensure_initialized()
    return self._result.get_sorted_imports()

get_main_content

get_main_content() -> Optional[str]

Get the main content.

Returns:

TypeDescription
Optional[str]

The main content.

Source code in waldiez/exporting/core/exporter.py
def get_main_content(self) -> Optional[str]:
    """Get the main content.

    Returns
    -------
    Optional[str]
        The main content.
    """
    self._ensure_initialized()
    return self._result.main_content

get_metadata

get_metadata(key: str, default: Any = None) -> Any

Get metadata from the export result.

Parameters:

NameTypeDescriptionDefault
keystr

The metadata key.

required
defaultAny

Default value if key not found, by default None

None

Returns:

TypeDescription
Any

The metadata value or default.

Source code in waldiez/exporting/core/exporter.py
def get_metadata(self, key: str, default: Any = None) -> Any:
    """Get metadata from the export result.

    Parameters
    ----------
    key : str
        The metadata key.
    default : Any, optional
        Default value if key not found, by default None

    Returns
    -------
    Any
        The metadata value or default.
    """
    return self._result.metadata.get(key, default)

get_statistics

get_statistics() -> dict[str, int]

Get statistics about the export.

Returns:

TypeDescription
Dict[str, int]

Dictionary with export statistics.

Source code in waldiez/exporting/core/exporter.py
def get_statistics(self) -> dict[str, int]:
    """Get statistics about the export.

    Returns
    -------
    Dict[str, int]
        Dictionary with export statistics.
    """
    self._ensure_initialized()
    return self._result.get_statistics()

has_content

has_content() -> bool

Check if the exporter has any content.

Returns:

TypeDescription
bool

True if there's any content.

Source code in waldiez/exporting/core/exporter.py
def has_content(self) -> bool:
    """Check if the exporter has any content.

    Returns
    -------
    bool
        True if there's any content.
    """
    self._ensure_initialized()
    return self._result.has_content()

has_errors

has_errors() -> bool

Check if there are validation errors.

Returns:

TypeDescription
bool

True if there are validation errors.

Source code in waldiez/exporting/core/exporter.py
def has_errors(self) -> bool:
    """Check if there are validation errors.

    Returns
    -------
    bool
        True if there are validation errors.
    """
    self._ensure_initialized()
    return self._result.has_errors()

has_warnings

has_warnings() -> bool

Check if there are validation warnings.

Returns:

TypeDescription
bool

True if there are validation warnings.

Source code in waldiez/exporting/core/exporter.py
def has_warnings(self) -> bool:
    """Check if there are validation warnings.

    Returns
    -------
    bool
        True if there are validation warnings.
    """
    self._ensure_initialized()
    return self._result.has_warnings()

reset

reset() -> None

Reset the exporter to initial state.

Source code in waldiez/exporting/core/exporter.py
def reset(self) -> None:
    """Reset the exporter to initial state."""
    self._result = ExportResult()
    self._initialized = False
    self._builder = ExportResultBuilder()

set_metadata

set_metadata(key: str, value: Any) -> None

Set metadata on the export result.

Parameters:

NameTypeDescriptionDefault
keystr

The metadata key.

required
valueAny

The metadata value.

required
Source code in waldiez/exporting/core/exporter.py
def set_metadata(self, key: str, value: Any) -> None:
    """Set metadata on the export result.

    Parameters
    ----------
    key : str
        The metadata key.
    value : Any
        The metadata value.
    """
    self._result.metadata[key] = value

exporters

Exporters for Waldiez.

ConfigurableExporter

ConfigurableExporter(
    config: Optional[dict[str, Any]] = None, **kwargs: Any
)

Bases: Exporter[Extras]

Exporter with configuration support.

Parameters:

NameTypeDescriptionDefault
configOptional[Dict[str, Any]]

Configuration dictionary, by default None

None
**kwargsAny

Additional keyword arguments.

{}
Source code in waldiez/exporting/core/exporters.py
def __init__(self, config: Optional[dict[str, Any]] = None, **kwargs: Any):
    """Initialize with configuration.

    Parameters
    ----------
    config : Optional[Dict[str, Any]], optional
        Configuration dictionary, by default None
    **kwargs : Any
        Additional keyword arguments.
    """
    super().__init__(**kwargs)
    self._config = config or {}

get_config_value

get_config_value(key: str, default: Any = None) -> Any

Get a configuration value.

Parameters:

NameTypeDescriptionDefault
keystr

The configuration key.

required
defaultAny

Default value if key not found, by default None

None

Returns:

TypeDescription
Any

The configuration value or default.

Source code in waldiez/exporting/core/exporters.py
def get_config_value(self, key: str, default: Any = None) -> Any:
    """Get a configuration value.

    Parameters
    ----------
    key : str
        The configuration key.
    default : Any, optional
        Default value if key not found, by default None

    Returns
    -------
    Any
        The configuration value or default.
    """
    return self._config.get(key, default)

set_config_value

set_config_value(key: str, value: Any) -> None

Set a configuration value.

Parameters:

NameTypeDescriptionDefault
keystr

The configuration key.

required
valueAny

The configuration value.

required
Source code in waldiez/exporting/core/exporters.py
def set_config_value(self, key: str, value: Any) -> None:
    """Set a configuration value.

    Parameters
    ----------
    key : str
        The configuration key.
    value : Any
        The configuration value.
    """
    self._config[key] = value

SimpleExporter

SimpleExporter(
    context: Optional[ExporterContext] = None, **kwargs: Any
)

Bases: Exporter[None]

Simple exporter that doesn't use extras system.

Source code in waldiez/exporting/core/exporter.py
def __init__(
    self,
    context: Optional[ExporterContext] = None,
    **kwargs: Any,
):
    """Initialize the exporter.

    Parameters
    ----------
    context : Optional[ExporterContext], optional
        The exporter context with dependencies, by default None
    **kwargs : Any
        Additional keyword arguments for subclasses.
    """
    self._context = context or DefaultExporterContext(
        config=ExportConfig.create(**kwargs)
    )
    config = self._context.get_config()
    config.update(**kwargs)
    self._context.set_config(config)
    self._result = ExportResult()
    self._initialized = False
    self._builder = ExportResultBuilder()
    self.config = self._context.get_config()

    # Allow subclasses to handle additional kwargs
    self._handle_kwargs(**kwargs)

extras property

extras: None

Simple exporters don't have extras.

extras

Extras for Waldiez exporting core module.

BaseExtras dataclass

BaseExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
)

Bases: ExportContributor

Base class for all exporter extras with export contribution.

add_arg

add_arg(arg: InstanceArgument | str, tabs: int = 0) -> None

Add an extra argument.

Parameters:

NameTypeDescriptionDefault
argInstanceArgument

The argument to add.

required
tabsint

The number of tabs to indent the argument, by default 0.

0
Source code in waldiez/exporting/core/extras/base.py
def add_arg(self, arg: InstanceArgument | str, tabs: int = 0) -> None:
    """Add an extra argument.

    Parameters
    ----------
    arg : InstanceArgument
        The argument to add.
    tabs : int, optional
        The number of tabs to indent the argument, by default 0.
    """
    if isinstance(arg, InstanceArgument):
        if arg not in self.extra_args:
            self.extra_args.append(arg)
    elif isinstance(arg, str) and arg.strip():  # pyright: ignore
        # If it's a string, create an InstanceArgument
        # split by '=' (it's an argument line)
        parts = arg.split("=", 1)
        if len(parts) == 2:
            name, value = parts
            comment = ""
            if " #" in value:
                value, _comment = value.split(" #", 1)
                comment = _comment.strip()
            new_arg = InstanceArgument(
                instance_id=self.instance_id,
                name=name.strip(),
                value=value.strip(),
                tabs=tabs,
                comment=comment.strip(),
            )
            if new_arg not in self.extra_args:
                self.extra_args.append(new_arg)

add_import

add_import(import_statement: ImportStatement) -> None

Add an import statement.

Parameters:

NameTypeDescriptionDefault
import_statementstr

The import statement to add.

required
Source code in waldiez/exporting/core/extras/base.py
def add_import(self, import_statement: ImportStatement) -> None:
    """Add an import statement.

    Parameters
    ----------
    import_statement : str
        The import statement to add.
    """
    if import_statement and import_statement.statement.strip():
        self.extra_imports.append(import_statement)

add_imports

add_imports(imports: Sequence[ImportStatement]) -> None

Add multiple import statements.

Parameters:

NameTypeDescriptionDefault
importsSet[str]

The import statements to add.

required
Source code in waldiez/exporting/core/extras/base.py
def add_imports(self, imports: Sequence[ImportStatement]) -> None:
    """Add multiple import statements.

    Parameters
    ----------
    imports : Set[str]
        The import statements to add.
    """
    for imp in imports:
        self.add_import(imp)

append_after_agent

append_after_agent(content: str) -> None

Append content to the after_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_after_agent(self, content: str) -> None:
    """Append content to the after_agent section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.after_agent:
            self.after_agent += "\n" + content.rstrip()
        else:
            self.after_agent = content.rstrip()

append_after_all_agents

append_after_all_agents(content: str) -> None

Append content to the after_all_agents section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_after_all_agents(self, content: str) -> None:
    """Append content to the after_all_agents section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.after_all_agents:
            self.after_all_agents += "\n" + content.rstrip()
        else:
            self.after_all_agents = content.rstrip()

append_before_agent

append_before_agent(content: str) -> None

Append content to the before_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_before_agent(self, content: str) -> None:
    """Append content to the before_agent section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.before_agent:
            self.before_agent += "\n" + content.rstrip()
        else:
            self.before_agent = content.rstrip()

contribute_to_export

contribute_to_export(result: ExportResult) -> None

Contribute this extras' content to the export result.

Parameters:

NameTypeDescriptionDefault
resultExportResult

The export result to contribute to.

required
Source code in waldiez/exporting/core/extras/base.py
def contribute_to_export(self, result: ExportResult) -> None:
    """Contribute this extras' content to the export result.

    Parameters
    ----------
    result : ExportResult
        The export result to contribute to.
    """
    # Add imports
    result.add_imports(self.extra_imports, ImportPosition.THIRD_PARTY)

    # Add before/after content with default positioning
    # Subclasses can override this method for custom positioning
    if self.before_agent:
        result.add_content(
            self.before_agent,
            ExportPosition.AGENTS,
            order=ContentOrder.PRE_CONTENT,
        )

    if self.extra_args:
        for arg in self.extra_args:
            result.add_content(
                arg.get_content(),
                ExportPosition.AGENTS,
                order=ContentOrder.MAIN_CONTENT,
                agent_position=AgentPosition.AS_ARGUMENT,
            )

    if self.after_agent:
        result.add_content(
            self.after_agent,
            ExportPosition.AGENTS,
            order=ContentOrder.POST_CONTENT,
        )

    # Allow subclasses to contribute additional content
    self._contribute_specific_content(result)

get_extra_args_content

get_extra_args_content() -> str

Get the extra arguments content.

Returns:

TypeDescription
str

The extra arguments content.

Source code in waldiez/exporting/core/extras/base.py
def get_extra_args_content(self) -> str:
    """Get the extra arguments content.

    Returns
    -------
    str
        The extra arguments content.
    """
    return "\n".join([arg.get_content() for arg in self.extra_args]) + "\n"

has_content

has_content() -> bool

Check if there's any meaningful content.

Returns:

TypeDescription
bool

True if there's any content in this extras instance.

Source code in waldiez/exporting/core/extras/base.py
def has_content(self) -> bool:
    """Check if there's any meaningful content.

    Returns
    -------
    bool
        True if there's any content in this extras instance.
    """
    return bool(
        self.extra_imports
        or self.before_agent.strip()
        or self.after_agent.strip()
        or self.has_specific_content()
    )

has_specific_content abstractmethod

has_specific_content() -> bool

Check if there's subclass-specific content.

Returns:

TypeDescription
bool

True if there's specific content for this extras type.

Source code in waldiez/exporting/core/extras/base.py
@abc.abstractmethod
def has_specific_content(self) -> bool:
    """Check if there's subclass-specific content.

    Returns
    -------
    bool
        True if there's specific content for this extras type.
    """

prepend_after_all_agents

prepend_after_all_agents(content: str) -> None

Prepend content to the after_all_agents section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to prepend.

required
Source code in waldiez/exporting/core/extras/base.py
def prepend_after_all_agents(self, content: str) -> None:
    """Prepend content to the after_all_agents section.

    Parameters
    ----------
    content : str
        The content to prepend.
    """
    if content and content.strip():
        if self.after_all_agents:
            self.after_all_agents = (
                content.rstrip() + "\n" + self.after_all_agents
            )
        else:
            self.after_all_agents = content.rstrip()

prepend_before_agent

prepend_before_agent(content: str) -> None

Prepend content to the before_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to prepend.

required
Source code in waldiez/exporting/core/extras/base.py
def prepend_before_agent(self, content: str) -> None:
    """Prepend content to the before_agent section.

    Parameters
    ----------
    content : str
        The content to prepend.
    """
    if content and content.strip():
        if self.before_agent:
            self.before_agent = content.rstrip() + "\n" + self.before_agent
        else:
            self.before_agent = content.rstrip()

CaptainExtras dataclass

CaptainExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    nested_config: Optional[dict[str, Any]] = None,
)

Bases: StandardExtras

Extras for captain agents.

has_specific_content

has_specific_content() -> bool

Check for captain specific content.

Returns:

TypeDescription
bool

True if there's captain specific content.

Source code in waldiez/exporting/core/extras/agent_extras/captain_extras.py
def has_specific_content(self) -> bool:
    """Check for captain specific content.

    Returns
    -------
    bool
        True if there's captain specific content.
    """
    if not super().has_specific_content():
        return bool(self.extra_args or self.nested_config)
    return True

set_nested_config

set_nested_config(config: dict[str, Any]) -> None

Set the nested configuration.

Parameters:

NameTypeDescriptionDefault
configDict[str, Any]

The nested configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/captain_extras.py
def set_nested_config(self, config: dict[str, Any]) -> None:
    """Set the nested configuration.

    Parameters
    ----------
    config : Dict[str, Any]
        The nested configuration.
    """
    self.nested_config = config

ChatExtras dataclass

ChatExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    chat_prerequisites: str = "",
    chat_initiation: str = "",
    chat_registration: str = "",
)

Bases: BaseExtras

Extras for chat exporters.

Attributes:

NameTypeDescription
chat_definitionstr

The chat definition content.

chat_initiationstr

The chat initiation content.

add_registration

add_registration(registration: str) -> None

Add chat registration content.

Parameters:

NameTypeDescriptionDefault
registrationstr

The chat registration content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def add_registration(self, registration: str) -> None:
    """Add chat registration content.

    Parameters
    ----------
    registration : str
        The chat registration content.
    """
    if registration and registration.strip():
        self.chat_registration += "\n" + registration.strip() + "\n"

has_specific_content

has_specific_content() -> bool

Check for chat specific content.

Returns:

TypeDescription
bool

True if there's chat specific content.

Source code in waldiez/exporting/core/extras/chat_extras.py
def has_specific_content(self) -> bool:
    """Check for chat specific content.

    Returns
    -------
    bool
        True if there's chat specific content.
    """
    return bool(
        self.chat_initiation.strip()
        or self.chat_prerequisites.strip()
        or self.chat_registration.strip()
    )

set_chat_initiation

set_chat_initiation(initiation: str) -> None

Set the chat initiation.

Parameters:

NameTypeDescriptionDefault
initiationstr

The chat initiation content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_initiation(self, initiation: str) -> None:
    """Set the chat initiation.

    Parameters
    ----------
    initiation : str
        The chat initiation content.
    """
    self.chat_initiation = initiation

set_chat_prerequisites

set_chat_prerequisites(prerequisites: str) -> None

Set the chat prerequisites.

Parameters:

NameTypeDescriptionDefault
prerequisitesstr

The chat prerequisites content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_prerequisites(self, prerequisites: str) -> None:
    """Set the chat prerequisites.

    Parameters
    ----------
    prerequisites : str
        The chat prerequisites content.
    """
    self.chat_prerequisites = prerequisites

set_chat_registration

set_chat_registration(registration: str) -> None

Set the chat registration.

Parameters:

NameTypeDescriptionDefault
registrationstr

The chat registration content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_registration(self, registration: str) -> None:
    """Set the chat registration.

    Parameters
    ----------
    registration : str
        The chat registration content.
    """
    self.chat_registration = registration

CodeExecutionConfig dataclass

CodeExecutionConfig(
    executor_content: str = "",
    executor_argument: str = "False",
    executor_import: ImportStatement | None = None,
)

Code execution configuration.

has_content

has_content() -> bool

Check if there's any code execution content.

Returns:

TypeDescription
bool

True if there's any code execution configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any code execution content.

    Returns
    -------
    bool
        True if there's any code execution configuration.
    """
    return bool(
        self.executor_content.strip()
        or self.executor_argument != "False"
        or self.executor_import
    )

DefaultPathResolver

Bases: PathResolver

Default path resolver for Waldiez items.

resolve

resolve(path: str) -> str

Resolve a path to a local file system path.

Parameters:

NameTypeDescriptionDefault
pathUnion[str, Path]

The path to resolve.

required

Returns:

TypeDescription
Optional[Path]

The resolved local path or None if not found.

Source code in waldiez/exporting/core/extras/path_resolver.py
def resolve(self, path: str) -> str:
    """Resolve a path to a local file system path.

    Parameters
    ----------
    path : Union[str, Path]
        The path to resolve.

    Returns
    -------
    Optional[Path]
        The resolved local path or None if not found.
    """
    resolved = _check_local_path(path)
    if not resolved:
        return _get_raw_path_string(path)
    return _get_raw_path_string(resolved)

DefaultSerializer

Bases: Serializer

Default serializer for Waldiez items.

serialize

serialize(obj: Any, **kwargs: Any) -> str

Serialize an item to a formatted string.

Parameters:

NameTypeDescriptionDefault
objAny

The item to serialize.

required
**kwargsAny

Additional keyword arguments, such as tabs for indentation level.

{}

Returns:

TypeDescription
str

The serialized string representation of the item.

Source code in waldiez/exporting/core/extras/serializer.py
def serialize(self, obj: Any, **kwargs: Any) -> str:
    """Serialize an item to a formatted string.

    Parameters
    ----------
    obj : Any
        The item to serialize.
    **kwargs : Any
        Additional keyword arguments, such as `tabs` for indentation level.

    Returns
    -------
    str
        The serialized string representation of the item.
    """
    tabs = kwargs.get("tabs", 1)
    return serialize_item(obj, tabs)

FlowExtras dataclass

FlowExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    flow_name: str = "",
    description: str = "",
    config: ExportConfig = ExportConfig(),
    version: str = get_waldiez_version(),
    tools_result: Optional[ExportResult] = None,
    models_result: Optional[ExportResult] = None,
    agents_result: Optional[ExportResult] = None,
    chats_result: Optional[ExportResult] = None,
    header_content: str = "",
    main_function: str = "",
    after_run: str = "",
    execution_code: str = "",
)

Bases: BaseExtras

Extras for flow exporter.

has_specific_content

has_specific_content() -> bool

Check if the flow extras contain specific content.

Returns:

TypeDescription
bool

True if any specific content is present, False otherwise.

Source code in waldiez/exporting/core/extras/flow_extras.py
def has_specific_content(self) -> bool:
    """Check if the flow extras contain specific content.

    Returns
    -------
    bool
        True if any specific content is present, False otherwise.
    """
    return bool(
        self.flow_name
        or self.description
        or self.version
        or self.tools_result
        or self.models_result
        or self.agents_result
        or self.chats_result
        or self.header_content
        or self.main_function
        or self.execution_code
    )

GroupManagerExtras dataclass

GroupManagerExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    strategy: GroupManagerStrategy = PATTERN,
    pattern_definition: str = "",
    pattern_class_name: str = "AutoPattern",
    pattern_imports: set[str] = set[str](),
    group_chat_definition: str = "",
    group_chat_name: str = "",
    group_chat_argument: str = "",
    custom_speaker_selection: str = "",
    context_variables_content: str = "",
    after_work_content: str = "",
)

Bases: StandardExtras

Extras for group manager agents.

has_specific_content

has_specific_content() -> bool

Check if group manager has specific content.

Returns:

TypeDescription
bool

True if there is specific content for the group manager,

Source code in waldiez/exporting/core/extras/agent_extras/group_manager_extras.py
def has_specific_content(self) -> bool:
    """Check if group manager has specific content.

    Returns
    -------
    bool
        True if there is specific content for the group manager,
    """
    if not super().has_specific_content():
        return bool(
            self.pattern_definition.strip()
            or self.group_chat_definition.strip()
            or self.custom_speaker_selection.strip()
        )
    return True

ModelExtras dataclass

ModelExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    llm_config: Optional[dict[str, Any]] = None,
    config_file_path: str = "",
)

Bases: BaseExtras

Extras for model exporters.

get_content

get_content() -> str

Get the content of the LLM configuration.

Returns:

TypeDescription
str

The serialized LLM configuration.

Source code in waldiez/exporting/core/extras/model_extras.py
def get_content(self) -> str:
    """Get the content of the LLM configuration.

    Returns
    -------
    str
        The serialized LLM configuration.
    """
    if self.llm_config and "content" in self.llm_config:
        return self.llm_config["content"]
    return ""

has_specific_content

has_specific_content() -> bool

Check for model specific content.

Returns:

TypeDescription
bool

True if there's model specific content.

Source code in waldiez/exporting/core/extras/model_extras.py
def has_specific_content(self) -> bool:
    """Check for model specific content.

    Returns
    -------
    bool
        True if there's model specific content.
    """
    if self.llm_config and "content" in self.llm_config:
        return bool(self.llm_config["content"])
    return False

set_config_file_path

set_config_file_path(path: str) -> None

Set the configuration file path.

Parameters:

NameTypeDescriptionDefault
pathstr

The configuration file path.

required
Source code in waldiez/exporting/core/extras/model_extras.py
def set_config_file_path(self, path: str) -> None:
    """Set the configuration file path.

    Parameters
    ----------
    path : str
        The configuration file path.
    """
    self.config_file_path = path

set_llm_config

set_llm_config(config: dict[str, Any]) -> None

Set the LLM configuration.

Parameters:

NameTypeDescriptionDefault
configdict[str, Any]

The LLM configuration.

required
Source code in waldiez/exporting/core/extras/model_extras.py
def set_llm_config(self, config: dict[str, Any]) -> None:
    """Set the LLM configuration.

    Parameters
    ----------
    config : dict[str, Any]
        The LLM configuration.
    """
    self.llm_config = config

RAGUserExtras dataclass

RAGUserExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    before_content: str = "",
    imports: set[str] = set[str](),
)

Bases: StandardExtras

RAG configuration.

has_specific_content

has_specific_content() -> bool

Check if there's any RAG content.

Returns:

TypeDescription
bool

True if there's any RAG configuration.

Source code in waldiez/exporting/core/extras/agent_extras/rag_user_extras.py
def has_specific_content(self) -> bool:
    """Check if there's any RAG content.

    Returns
    -------
    bool
        True if there's any RAG configuration.
    """
    if not super().has_specific_content():
        return bool(
            self.extra_args or self.before_content.strip() or self.imports
        )
    return True

ReasoningExtras dataclass

ReasoningExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
)

Bases: StandardExtras

Extras for reasoning agents.

has_specific_content

has_specific_content() -> bool

Check for reasoning specific content.

Returns:

TypeDescription
bool

True if there's reasoning specific content.

Source code in waldiez/exporting/core/extras/agent_extras/reasoning_extras.py
def has_specific_content(self) -> bool:
    """Check for reasoning specific content.

    Returns
    -------
    bool
        True if there's reasoning specific content.
    """
    if not super().has_specific_content():
        return bool(
            self.extra_args
            or self.extra_imports
            or self.before_agent.strip()
            or self.after_agent.strip()
        )
    return True

StandardExtras dataclass

StandardExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
)

Bases: BaseExtras

Extras for standard agents (UserProxy, Assistant, etc.).

get_code_execution_arg

get_code_execution_arg() -> InstanceArgument

Get the code execution argument string.

Returns:

TypeDescription
InstanceArgument

The code execution argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_code_execution_arg(self) -> InstanceArgument:
    """Get the code execution argument string.

    Returns
    -------
    InstanceArgument
        The code execution argument.
    """
    if (
        self.code_execution_config
        and self.code_execution_config.executor_argument
    ):
        argunent = self.code_execution_config.executor_argument
    else:
        argunent = "False"
    return InstanceArgument(
        instance_id=self.instance_id,
        name="code_execution_config",
        value=argunent,
        tabs=1,
    )

get_system_message_arg

get_system_message_arg() -> InstanceArgument

Get the system message argument.

Returns:

TypeDescription
InstanceArgument

The system message argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_system_message_arg(self) -> InstanceArgument:
    """Get the system message argument.

    Returns
    -------
    InstanceArgument
        The system message argument.
    """
    if (
        self.system_message_config
        and self.system_message_config.system_message_arg
    ):
        argument = self.system_message_config.system_message_arg
    else:
        argument = ""
    return InstanceArgument(
        instance_id=self.instance_id,
        name="system_message",
        value=argument,
        skip_if_empty_string=True,
        with_new_line_before=True,
        tabs=1,
    )

get_termination_arg

get_termination_arg() -> InstanceArgument

Get the termination argument.

Returns:

TypeDescription
InstanceArgument

The termination argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_termination_arg(self) -> InstanceArgument:
    """Get the termination argument.

    Returns
    -------
    InstanceArgument
        The termination argument.
    """
    if self.termination_config and self.termination_config.termination_arg:
        argument = self.termination_config.termination_arg
    else:
        argument = "None"
    comment: str | None = None
    if argument == "None":
        comment = "pyright: ignore"
    return InstanceArgument(
        instance_id=self.instance_id,
        name="is_termination_msg",
        value=argument,
        comment=comment,
        tabs=1,
    )

has_specific_content

has_specific_content() -> bool

Check for standard agent specific content.

Returns:

TypeDescription
bool

True if there's standard agent specific content.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_specific_content(self) -> bool:
    """Check for standard agent specific content.

    Returns
    -------
    bool
        True if there's standard agent specific content.
    """
    return bool(
        self.extra_args
        or (
            self.code_execution_config
            and self.code_execution_config.has_content()
        )
        or (
            self.termination_config
            and self.termination_config.has_content()
        )
        or (
            self.system_message_config
            and self.system_message_config.has_content()
        )
    )

set_code_execution

set_code_execution(config: CodeExecutionConfig) -> None

Set code execution configuration.

Parameters:

NameTypeDescriptionDefault
configCodeExecutionConfig

The code execution configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_code_execution(self, config: CodeExecutionConfig) -> None:
    """Set code execution configuration.

    Parameters
    ----------
    config : CodeExecutionConfig
        The code execution configuration.
    """
    self.code_execution_config = config
    if config.executor_import:
        self.add_import(config.executor_import)
    # we either add the executor content here or
    # in _contribute_specific_content below
    if config.executor_content:
        self.append_before_agent(config.executor_content)

set_system_message_config

set_system_message_config(
    config: SystemMessageConfig,
) -> None

Set system message configuration.

Parameters:

NameTypeDescriptionDefault
configSystemMessageConfig

The system message configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_system_message_config(self, config: SystemMessageConfig) -> None:
    """Set system message configuration.

    Parameters
    ----------
    config : SystemMessageConfig
        The system message configuration.
    """
    self.system_message_config = config
    if config.before_agent_conent:
        self.append_before_agent(config.before_agent_conent)

set_termination_config

set_termination_config(config: TerminationConfig) -> None

Set termination configuration.

Parameters:

NameTypeDescriptionDefault
configTerminationConfig

The termination configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_termination_config(self, config: TerminationConfig) -> None:
    """Set termination configuration.

    Parameters
    ----------
    config : TerminationConfig
        The termination configuration.
    """
    self.termination_config = config
    if config.before_content:
        self.append_before_agent(config.before_content)

SystemMessageConfig dataclass

SystemMessageConfig(
    before_agent_conent: str = "",
    system_message_arg: str = "",
)

System message configuration.

has_content

has_content() -> bool

Check if there's any system message content.

Returns:

TypeDescription
bool

True if there's any system message configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any system message content.

    Returns
    -------
    bool
        True if there's any system message configuration.
    """
    return bool(str(self.system_message_arg).strip())

TerminationConfig dataclass

TerminationConfig(
    termination_arg: str = "None", before_content: str = ""
)

Termination configuration.

has_content

has_content() -> bool

Check if there's any termination content.

Returns:

TypeDescription
bool

True if there's any termination configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any termination content.

    Returns
    -------
    bool
        True if there's any termination configuration.
    """
    return bool(self.before_content.strip())

ToolExtras dataclass

ToolExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    function_content: str = "",
    registration_content: str = "",
)

Bases: BaseExtras

Extras for tool exporters.

add_function_content

add_function_content(content: str) -> None

Add function definition content.

Parameters:

NameTypeDescriptionDefault
contentstr

The function content to add.

required
Source code in waldiez/exporting/core/extras/tool_extras.py
def add_function_content(self, content: str) -> None:
    """Add function definition content.

    Parameters
    ----------
    content : str
        The function content to add.
    """
    if content and content.strip():  # pragma: no branch
        if self.function_content:
            self.function_content += "\n\n" + content.rstrip()
        else:
            self.function_content = content.rstrip()
        while not self.function_content.endswith("\n\n"):
            self.function_content += "\n\n"

add_registration_content

add_registration_content(content: str) -> None

Add function registration content.

Parameters:

NameTypeDescriptionDefault
contentstr

The registration content to add.

required
Source code in waldiez/exporting/core/extras/tool_extras.py
def add_registration_content(self, content: str) -> None:
    """Add function registration content.

    Parameters
    ----------
    content : str
        The registration content to add.
    """
    if content and content.strip():  # pragma: no branch
        self.registration_content += "\n" + content.rstrip() + "\n"

has_specific_content

has_specific_content() -> bool

Check for tool specific content.

Returns:

TypeDescription
bool

True if there's tool specific content.

Source code in waldiez/exporting/core/extras/tool_extras.py
def has_specific_content(self) -> bool:
    """Check for tool specific content.

    Returns
    -------
    bool
        True if there's tool specific content.
    """
    return bool(
        self.function_content.strip() or self.registration_content.strip()
    )

agent_extras

Agent specific extras module.

CaptainExtras dataclass

CaptainExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    nested_config: Optional[dict[str, Any]] = None,
)

Bases: StandardExtras

Extras for captain agents.

has_specific_content
has_specific_content() -> bool

Check for captain specific content.

Returns:

TypeDescription
bool

True if there's captain specific content.

Source code in waldiez/exporting/core/extras/agent_extras/captain_extras.py
def has_specific_content(self) -> bool:
    """Check for captain specific content.

    Returns
    -------
    bool
        True if there's captain specific content.
    """
    if not super().has_specific_content():
        return bool(self.extra_args or self.nested_config)
    return True
set_nested_config
set_nested_config(config: dict[str, Any]) -> None

Set the nested configuration.

Parameters:

NameTypeDescriptionDefault
configDict[str, Any]

The nested configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/captain_extras.py
def set_nested_config(self, config: dict[str, Any]) -> None:
    """Set the nested configuration.

    Parameters
    ----------
    config : Dict[str, Any]
        The nested configuration.
    """
    self.nested_config = config

CodeExecutionConfig dataclass

CodeExecutionConfig(
    executor_content: str = "",
    executor_argument: str = "False",
    executor_import: ImportStatement | None = None,
)

Code execution configuration.

has_content
has_content() -> bool

Check if there's any code execution content.

Returns:

TypeDescription
bool

True if there's any code execution configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any code execution content.

    Returns
    -------
    bool
        True if there's any code execution configuration.
    """
    return bool(
        self.executor_content.strip()
        or self.executor_argument != "False"
        or self.executor_import
    )

GroupManagerExtras dataclass

GroupManagerExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    strategy: GroupManagerStrategy = PATTERN,
    pattern_definition: str = "",
    pattern_class_name: str = "AutoPattern",
    pattern_imports: set[str] = set[str](),
    group_chat_definition: str = "",
    group_chat_name: str = "",
    group_chat_argument: str = "",
    custom_speaker_selection: str = "",
    context_variables_content: str = "",
    after_work_content: str = "",
)

Bases: StandardExtras

Extras for group manager agents.

has_specific_content
has_specific_content() -> bool

Check if group manager has specific content.

Returns:

TypeDescription
bool

True if there is specific content for the group manager,

Source code in waldiez/exporting/core/extras/agent_extras/group_manager_extras.py
def has_specific_content(self) -> bool:
    """Check if group manager has specific content.

    Returns
    -------
    bool
        True if there is specific content for the group manager,
    """
    if not super().has_specific_content():
        return bool(
            self.pattern_definition.strip()
            or self.group_chat_definition.strip()
            or self.custom_speaker_selection.strip()
        )
    return True

RAGUserExtras dataclass

RAGUserExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    before_content: str = "",
    imports: set[str] = set[str](),
)

Bases: StandardExtras

RAG configuration.

has_specific_content
has_specific_content() -> bool

Check if there's any RAG content.

Returns:

TypeDescription
bool

True if there's any RAG configuration.

Source code in waldiez/exporting/core/extras/agent_extras/rag_user_extras.py
def has_specific_content(self) -> bool:
    """Check if there's any RAG content.

    Returns
    -------
    bool
        True if there's any RAG configuration.
    """
    if not super().has_specific_content():
        return bool(
            self.extra_args or self.before_content.strip() or self.imports
        )
    return True

ReasoningExtras dataclass

ReasoningExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
)

Bases: StandardExtras

Extras for reasoning agents.

has_specific_content
has_specific_content() -> bool

Check for reasoning specific content.

Returns:

TypeDescription
bool

True if there's reasoning specific content.

Source code in waldiez/exporting/core/extras/agent_extras/reasoning_extras.py
def has_specific_content(self) -> bool:
    """Check for reasoning specific content.

    Returns
    -------
    bool
        True if there's reasoning specific content.
    """
    if not super().has_specific_content():
        return bool(
            self.extra_args
            or self.extra_imports
            or self.before_agent.strip()
            or self.after_agent.strip()
        )
    return True

StandardExtras dataclass

StandardExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
)

Bases: BaseExtras

Extras for standard agents (UserProxy, Assistant, etc.).

get_code_execution_arg
get_code_execution_arg() -> InstanceArgument

Get the code execution argument string.

Returns:

TypeDescription
InstanceArgument

The code execution argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_code_execution_arg(self) -> InstanceArgument:
    """Get the code execution argument string.

    Returns
    -------
    InstanceArgument
        The code execution argument.
    """
    if (
        self.code_execution_config
        and self.code_execution_config.executor_argument
    ):
        argunent = self.code_execution_config.executor_argument
    else:
        argunent = "False"
    return InstanceArgument(
        instance_id=self.instance_id,
        name="code_execution_config",
        value=argunent,
        tabs=1,
    )
get_system_message_arg
get_system_message_arg() -> InstanceArgument

Get the system message argument.

Returns:

TypeDescription
InstanceArgument

The system message argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_system_message_arg(self) -> InstanceArgument:
    """Get the system message argument.

    Returns
    -------
    InstanceArgument
        The system message argument.
    """
    if (
        self.system_message_config
        and self.system_message_config.system_message_arg
    ):
        argument = self.system_message_config.system_message_arg
    else:
        argument = ""
    return InstanceArgument(
        instance_id=self.instance_id,
        name="system_message",
        value=argument,
        skip_if_empty_string=True,
        with_new_line_before=True,
        tabs=1,
    )
get_termination_arg
get_termination_arg() -> InstanceArgument

Get the termination argument.

Returns:

TypeDescription
InstanceArgument

The termination argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_termination_arg(self) -> InstanceArgument:
    """Get the termination argument.

    Returns
    -------
    InstanceArgument
        The termination argument.
    """
    if self.termination_config and self.termination_config.termination_arg:
        argument = self.termination_config.termination_arg
    else:
        argument = "None"
    comment: str | None = None
    if argument == "None":
        comment = "pyright: ignore"
    return InstanceArgument(
        instance_id=self.instance_id,
        name="is_termination_msg",
        value=argument,
        comment=comment,
        tabs=1,
    )
has_specific_content
has_specific_content() -> bool

Check for standard agent specific content.

Returns:

TypeDescription
bool

True if there's standard agent specific content.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_specific_content(self) -> bool:
    """Check for standard agent specific content.

    Returns
    -------
    bool
        True if there's standard agent specific content.
    """
    return bool(
        self.extra_args
        or (
            self.code_execution_config
            and self.code_execution_config.has_content()
        )
        or (
            self.termination_config
            and self.termination_config.has_content()
        )
        or (
            self.system_message_config
            and self.system_message_config.has_content()
        )
    )
set_code_execution
set_code_execution(config: CodeExecutionConfig) -> None

Set code execution configuration.

Parameters:

NameTypeDescriptionDefault
configCodeExecutionConfig

The code execution configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_code_execution(self, config: CodeExecutionConfig) -> None:
    """Set code execution configuration.

    Parameters
    ----------
    config : CodeExecutionConfig
        The code execution configuration.
    """
    self.code_execution_config = config
    if config.executor_import:
        self.add_import(config.executor_import)
    # we either add the executor content here or
    # in _contribute_specific_content below
    if config.executor_content:
        self.append_before_agent(config.executor_content)
set_system_message_config
set_system_message_config(
    config: SystemMessageConfig,
) -> None

Set system message configuration.

Parameters:

NameTypeDescriptionDefault
configSystemMessageConfig

The system message configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_system_message_config(self, config: SystemMessageConfig) -> None:
    """Set system message configuration.

    Parameters
    ----------
    config : SystemMessageConfig
        The system message configuration.
    """
    self.system_message_config = config
    if config.before_agent_conent:
        self.append_before_agent(config.before_agent_conent)
set_termination_config
set_termination_config(config: TerminationConfig) -> None

Set termination configuration.

Parameters:

NameTypeDescriptionDefault
configTerminationConfig

The termination configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_termination_config(self, config: TerminationConfig) -> None:
    """Set termination configuration.

    Parameters
    ----------
    config : TerminationConfig
        The termination configuration.
    """
    self.termination_config = config
    if config.before_content:
        self.append_before_agent(config.before_content)

SystemMessageConfig dataclass

SystemMessageConfig(
    before_agent_conent: str = "",
    system_message_arg: str = "",
)

System message configuration.

has_content
has_content() -> bool

Check if there's any system message content.

Returns:

TypeDescription
bool

True if there's any system message configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any system message content.

    Returns
    -------
    bool
        True if there's any system message configuration.
    """
    return bool(str(self.system_message_arg).strip())

TerminationConfig dataclass

TerminationConfig(
    termination_arg: str = "None", before_content: str = ""
)

Termination configuration.

has_content
has_content() -> bool

Check if there's any termination content.

Returns:

TypeDescription
bool

True if there's any termination configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any termination content.

    Returns
    -------
    bool
        True if there's any termination configuration.
    """
    return bool(self.before_content.strip())

captain_extras

Captain agent extras module.

CaptainExtras dataclass
CaptainExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    nested_config: Optional[dict[str, Any]] = None,
)

Bases: StandardExtras

Extras for captain agents.

has_specific_content
has_specific_content() -> bool

Check for captain specific content.

Returns:

TypeDescription
bool

True if there's captain specific content.

Source code in waldiez/exporting/core/extras/agent_extras/captain_extras.py
def has_specific_content(self) -> bool:
    """Check for captain specific content.

    Returns
    -------
    bool
        True if there's captain specific content.
    """
    if not super().has_specific_content():
        return bool(self.extra_args or self.nested_config)
    return True
set_nested_config
set_nested_config(config: dict[str, Any]) -> None

Set the nested configuration.

Parameters:

NameTypeDescriptionDefault
configDict[str, Any]

The nested configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/captain_extras.py
def set_nested_config(self, config: dict[str, Any]) -> None:
    """Set the nested configuration.

    Parameters
    ----------
    config : Dict[str, Any]
        The nested configuration.
    """
    self.nested_config = config

group_manager_extras

Group manager agent specific extras module.

GroupManagerExtras dataclass
GroupManagerExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    strategy: GroupManagerStrategy = PATTERN,
    pattern_definition: str = "",
    pattern_class_name: str = "AutoPattern",
    pattern_imports: set[str] = set[str](),
    group_chat_definition: str = "",
    group_chat_name: str = "",
    group_chat_argument: str = "",
    custom_speaker_selection: str = "",
    context_variables_content: str = "",
    after_work_content: str = "",
)

Bases: StandardExtras

Extras for group manager agents.

has_specific_content
has_specific_content() -> bool

Check if group manager has specific content.

Returns:

TypeDescription
bool

True if there is specific content for the group manager,

Source code in waldiez/exporting/core/extras/agent_extras/group_manager_extras.py
def has_specific_content(self) -> bool:
    """Check if group manager has specific content.

    Returns
    -------
    bool
        True if there is specific content for the group manager,
    """
    if not super().has_specific_content():
        return bool(
            self.pattern_definition.strip()
            or self.group_chat_definition.strip()
            or self.custom_speaker_selection.strip()
        )
    return True

rag_user_extras

RAG related extas.

RAGUserExtras dataclass
RAGUserExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
    before_content: str = "",
    imports: set[str] = set[str](),
)

Bases: StandardExtras

RAG configuration.

has_specific_content
has_specific_content() -> bool

Check if there's any RAG content.

Returns:

TypeDescription
bool

True if there's any RAG configuration.

Source code in waldiez/exporting/core/extras/agent_extras/rag_user_extras.py
def has_specific_content(self) -> bool:
    """Check if there's any RAG content.

    Returns
    -------
    bool
        True if there's any RAG configuration.
    """
    if not super().has_specific_content():
        return bool(
            self.extra_args or self.before_content.strip() or self.imports
        )
    return True

reasoning_extras

Resoning agent extras module.

ReasoningExtras dataclass
ReasoningExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
)

Bases: StandardExtras

Extras for reasoning agents.

has_specific_content
has_specific_content() -> bool

Check for reasoning specific content.

Returns:

TypeDescription
bool

True if there's reasoning specific content.

Source code in waldiez/exporting/core/extras/agent_extras/reasoning_extras.py
def has_specific_content(self) -> bool:
    """Check for reasoning specific content.

    Returns
    -------
    bool
        True if there's reasoning specific content.
    """
    if not super().has_specific_content():
        return bool(
            self.extra_args
            or self.extra_imports
            or self.before_agent.strip()
            or self.after_agent.strip()
        )
    return True

standard_extras

Standard agent extras module.

CodeExecutionConfig dataclass
CodeExecutionConfig(
    executor_content: str = "",
    executor_argument: str = "False",
    executor_import: ImportStatement | None = None,
)

Code execution configuration.

has_content
has_content() -> bool

Check if there's any code execution content.

Returns:

TypeDescription
bool

True if there's any code execution configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any code execution content.

    Returns
    -------
    bool
        True if there's any code execution configuration.
    """
    return bool(
        self.executor_content.strip()
        or self.executor_argument != "False"
        or self.executor_import
    )
StandardExtras dataclass
StandardExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    code_execution_config: Optional[
        CodeExecutionConfig
    ] = None,
    termination_config: Optional[TerminationConfig] = None,
    system_message_config: Optional[
        SystemMessageConfig
    ] = None,
)

Bases: BaseExtras

Extras for standard agents (UserProxy, Assistant, etc.).

get_code_execution_arg
get_code_execution_arg() -> InstanceArgument

Get the code execution argument string.

Returns:

TypeDescription
InstanceArgument

The code execution argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_code_execution_arg(self) -> InstanceArgument:
    """Get the code execution argument string.

    Returns
    -------
    InstanceArgument
        The code execution argument.
    """
    if (
        self.code_execution_config
        and self.code_execution_config.executor_argument
    ):
        argunent = self.code_execution_config.executor_argument
    else:
        argunent = "False"
    return InstanceArgument(
        instance_id=self.instance_id,
        name="code_execution_config",
        value=argunent,
        tabs=1,
    )
get_system_message_arg
get_system_message_arg() -> InstanceArgument

Get the system message argument.

Returns:

TypeDescription
InstanceArgument

The system message argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_system_message_arg(self) -> InstanceArgument:
    """Get the system message argument.

    Returns
    -------
    InstanceArgument
        The system message argument.
    """
    if (
        self.system_message_config
        and self.system_message_config.system_message_arg
    ):
        argument = self.system_message_config.system_message_arg
    else:
        argument = ""
    return InstanceArgument(
        instance_id=self.instance_id,
        name="system_message",
        value=argument,
        skip_if_empty_string=True,
        with_new_line_before=True,
        tabs=1,
    )
get_termination_arg
get_termination_arg() -> InstanceArgument

Get the termination argument.

Returns:

TypeDescription
InstanceArgument

The termination argument.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def get_termination_arg(self) -> InstanceArgument:
    """Get the termination argument.

    Returns
    -------
    InstanceArgument
        The termination argument.
    """
    if self.termination_config and self.termination_config.termination_arg:
        argument = self.termination_config.termination_arg
    else:
        argument = "None"
    comment: str | None = None
    if argument == "None":
        comment = "pyright: ignore"
    return InstanceArgument(
        instance_id=self.instance_id,
        name="is_termination_msg",
        value=argument,
        comment=comment,
        tabs=1,
    )
has_specific_content
has_specific_content() -> bool

Check for standard agent specific content.

Returns:

TypeDescription
bool

True if there's standard agent specific content.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_specific_content(self) -> bool:
    """Check for standard agent specific content.

    Returns
    -------
    bool
        True if there's standard agent specific content.
    """
    return bool(
        self.extra_args
        or (
            self.code_execution_config
            and self.code_execution_config.has_content()
        )
        or (
            self.termination_config
            and self.termination_config.has_content()
        )
        or (
            self.system_message_config
            and self.system_message_config.has_content()
        )
    )
set_code_execution
set_code_execution(config: CodeExecutionConfig) -> None

Set code execution configuration.

Parameters:

NameTypeDescriptionDefault
configCodeExecutionConfig

The code execution configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_code_execution(self, config: CodeExecutionConfig) -> None:
    """Set code execution configuration.

    Parameters
    ----------
    config : CodeExecutionConfig
        The code execution configuration.
    """
    self.code_execution_config = config
    if config.executor_import:
        self.add_import(config.executor_import)
    # we either add the executor content here or
    # in _contribute_specific_content below
    if config.executor_content:
        self.append_before_agent(config.executor_content)
set_system_message_config
set_system_message_config(
    config: SystemMessageConfig,
) -> None

Set system message configuration.

Parameters:

NameTypeDescriptionDefault
configSystemMessageConfig

The system message configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_system_message_config(self, config: SystemMessageConfig) -> None:
    """Set system message configuration.

    Parameters
    ----------
    config : SystemMessageConfig
        The system message configuration.
    """
    self.system_message_config = config
    if config.before_agent_conent:
        self.append_before_agent(config.before_agent_conent)
set_termination_config
set_termination_config(config: TerminationConfig) -> None

Set termination configuration.

Parameters:

NameTypeDescriptionDefault
configTerminationConfig

The termination configuration.

required
Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def set_termination_config(self, config: TerminationConfig) -> None:
    """Set termination configuration.

    Parameters
    ----------
    config : TerminationConfig
        The termination configuration.
    """
    self.termination_config = config
    if config.before_content:
        self.append_before_agent(config.before_content)
SystemMessageConfig dataclass
SystemMessageConfig(
    before_agent_conent: str = "",
    system_message_arg: str = "",
)

System message configuration.

has_content
has_content() -> bool

Check if there's any system message content.

Returns:

TypeDescription
bool

True if there's any system message configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any system message content.

    Returns
    -------
    bool
        True if there's any system message configuration.
    """
    return bool(str(self.system_message_arg).strip())
TerminationConfig dataclass
TerminationConfig(
    termination_arg: str = "None", before_content: str = ""
)

Termination configuration.

has_content
has_content() -> bool

Check if there's any termination content.

Returns:

TypeDescription
bool

True if there's any termination configuration.

Source code in waldiez/exporting/core/extras/agent_extras/standard_extras.py
def has_content(self) -> bool:
    """Check if there's any termination content.

    Returns
    -------
    bool
        True if there's any termination configuration.
    """
    return bool(self.before_content.strip())

base

Base extras system for all exporters.

BaseExtras dataclass

BaseExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
)

Bases: ExportContributor

Base class for all exporter extras with export contribution.

add_arg
add_arg(arg: InstanceArgument | str, tabs: int = 0) -> None

Add an extra argument.

Parameters:

NameTypeDescriptionDefault
argInstanceArgument

The argument to add.

required
tabsint

The number of tabs to indent the argument, by default 0.

0
Source code in waldiez/exporting/core/extras/base.py
def add_arg(self, arg: InstanceArgument | str, tabs: int = 0) -> None:
    """Add an extra argument.

    Parameters
    ----------
    arg : InstanceArgument
        The argument to add.
    tabs : int, optional
        The number of tabs to indent the argument, by default 0.
    """
    if isinstance(arg, InstanceArgument):
        if arg not in self.extra_args:
            self.extra_args.append(arg)
    elif isinstance(arg, str) and arg.strip():  # pyright: ignore
        # If it's a string, create an InstanceArgument
        # split by '=' (it's an argument line)
        parts = arg.split("=", 1)
        if len(parts) == 2:
            name, value = parts
            comment = ""
            if " #" in value:
                value, _comment = value.split(" #", 1)
                comment = _comment.strip()
            new_arg = InstanceArgument(
                instance_id=self.instance_id,
                name=name.strip(),
                value=value.strip(),
                tabs=tabs,
                comment=comment.strip(),
            )
            if new_arg not in self.extra_args:
                self.extra_args.append(new_arg)
add_import
add_import(import_statement: ImportStatement) -> None

Add an import statement.

Parameters:

NameTypeDescriptionDefault
import_statementstr

The import statement to add.

required
Source code in waldiez/exporting/core/extras/base.py
def add_import(self, import_statement: ImportStatement) -> None:
    """Add an import statement.

    Parameters
    ----------
    import_statement : str
        The import statement to add.
    """
    if import_statement and import_statement.statement.strip():
        self.extra_imports.append(import_statement)
add_imports
add_imports(imports: Sequence[ImportStatement]) -> None

Add multiple import statements.

Parameters:

NameTypeDescriptionDefault
importsSet[str]

The import statements to add.

required
Source code in waldiez/exporting/core/extras/base.py
def add_imports(self, imports: Sequence[ImportStatement]) -> None:
    """Add multiple import statements.

    Parameters
    ----------
    imports : Set[str]
        The import statements to add.
    """
    for imp in imports:
        self.add_import(imp)
append_after_agent
append_after_agent(content: str) -> None

Append content to the after_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_after_agent(self, content: str) -> None:
    """Append content to the after_agent section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.after_agent:
            self.after_agent += "\n" + content.rstrip()
        else:
            self.after_agent = content.rstrip()
append_after_all_agents
append_after_all_agents(content: str) -> None

Append content to the after_all_agents section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_after_all_agents(self, content: str) -> None:
    """Append content to the after_all_agents section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.after_all_agents:
            self.after_all_agents += "\n" + content.rstrip()
        else:
            self.after_all_agents = content.rstrip()
append_before_agent
append_before_agent(content: str) -> None

Append content to the before_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to append.

required
Source code in waldiez/exporting/core/extras/base.py
def append_before_agent(self, content: str) -> None:
    """Append content to the before_agent section.

    Parameters
    ----------
    content : str
        The content to append.
    """
    if content and content.strip():
        if self.before_agent:
            self.before_agent += "\n" + content.rstrip()
        else:
            self.before_agent = content.rstrip()
contribute_to_export
contribute_to_export(result: ExportResult) -> None

Contribute this extras' content to the export result.

Parameters:

NameTypeDescriptionDefault
resultExportResult

The export result to contribute to.

required
Source code in waldiez/exporting/core/extras/base.py
def contribute_to_export(self, result: ExportResult) -> None:
    """Contribute this extras' content to the export result.

    Parameters
    ----------
    result : ExportResult
        The export result to contribute to.
    """
    # Add imports
    result.add_imports(self.extra_imports, ImportPosition.THIRD_PARTY)

    # Add before/after content with default positioning
    # Subclasses can override this method for custom positioning
    if self.before_agent:
        result.add_content(
            self.before_agent,
            ExportPosition.AGENTS,
            order=ContentOrder.PRE_CONTENT,
        )

    if self.extra_args:
        for arg in self.extra_args:
            result.add_content(
                arg.get_content(),
                ExportPosition.AGENTS,
                order=ContentOrder.MAIN_CONTENT,
                agent_position=AgentPosition.AS_ARGUMENT,
            )

    if self.after_agent:
        result.add_content(
            self.after_agent,
            ExportPosition.AGENTS,
            order=ContentOrder.POST_CONTENT,
        )

    # Allow subclasses to contribute additional content
    self._contribute_specific_content(result)
get_extra_args_content
get_extra_args_content() -> str

Get the extra arguments content.

Returns:

TypeDescription
str

The extra arguments content.

Source code in waldiez/exporting/core/extras/base.py
def get_extra_args_content(self) -> str:
    """Get the extra arguments content.

    Returns
    -------
    str
        The extra arguments content.
    """
    return "\n".join([arg.get_content() for arg in self.extra_args]) + "\n"
has_content
has_content() -> bool

Check if there's any meaningful content.

Returns:

TypeDescription
bool

True if there's any content in this extras instance.

Source code in waldiez/exporting/core/extras/base.py
def has_content(self) -> bool:
    """Check if there's any meaningful content.

    Returns
    -------
    bool
        True if there's any content in this extras instance.
    """
    return bool(
        self.extra_imports
        or self.before_agent.strip()
        or self.after_agent.strip()
        or self.has_specific_content()
    )
has_specific_content abstractmethod
has_specific_content() -> bool

Check if there's subclass-specific content.

Returns:

TypeDescription
bool

True if there's specific content for this extras type.

Source code in waldiez/exporting/core/extras/base.py
@abc.abstractmethod
def has_specific_content(self) -> bool:
    """Check if there's subclass-specific content.

    Returns
    -------
    bool
        True if there's specific content for this extras type.
    """
prepend_after_all_agents
prepend_after_all_agents(content: str) -> None

Prepend content to the after_all_agents section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to prepend.

required
Source code in waldiez/exporting/core/extras/base.py
def prepend_after_all_agents(self, content: str) -> None:
    """Prepend content to the after_all_agents section.

    Parameters
    ----------
    content : str
        The content to prepend.
    """
    if content and content.strip():
        if self.after_all_agents:
            self.after_all_agents = (
                content.rstrip() + "\n" + self.after_all_agents
            )
        else:
            self.after_all_agents = content.rstrip()
prepend_before_agent
prepend_before_agent(content: str) -> None

Prepend content to the before_agent section.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to prepend.

required
Source code in waldiez/exporting/core/extras/base.py
def prepend_before_agent(self, content: str) -> None:
    """Prepend content to the before_agent section.

    Parameters
    ----------
    content : str
        The content to prepend.
    """
    if content and content.strip():
        if self.before_agent:
            self.before_agent = content.rstrip() + "\n" + self.before_agent
        else:
            self.before_agent = content.rstrip()

chat_extras

Chat specific extras module.

ChatExtras dataclass

ChatExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    chat_prerequisites: str = "",
    chat_initiation: str = "",
    chat_registration: str = "",
)

Bases: BaseExtras

Extras for chat exporters.

Attributes:

NameTypeDescription
chat_definitionstr

The chat definition content.

chat_initiationstr

The chat initiation content.

add_registration
add_registration(registration: str) -> None

Add chat registration content.

Parameters:

NameTypeDescriptionDefault
registrationstr

The chat registration content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def add_registration(self, registration: str) -> None:
    """Add chat registration content.

    Parameters
    ----------
    registration : str
        The chat registration content.
    """
    if registration and registration.strip():
        self.chat_registration += "\n" + registration.strip() + "\n"
has_specific_content
has_specific_content() -> bool

Check for chat specific content.

Returns:

TypeDescription
bool

True if there's chat specific content.

Source code in waldiez/exporting/core/extras/chat_extras.py
def has_specific_content(self) -> bool:
    """Check for chat specific content.

    Returns
    -------
    bool
        True if there's chat specific content.
    """
    return bool(
        self.chat_initiation.strip()
        or self.chat_prerequisites.strip()
        or self.chat_registration.strip()
    )
set_chat_initiation
set_chat_initiation(initiation: str) -> None

Set the chat initiation.

Parameters:

NameTypeDescriptionDefault
initiationstr

The chat initiation content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_initiation(self, initiation: str) -> None:
    """Set the chat initiation.

    Parameters
    ----------
    initiation : str
        The chat initiation content.
    """
    self.chat_initiation = initiation
set_chat_prerequisites
set_chat_prerequisites(prerequisites: str) -> None

Set the chat prerequisites.

Parameters:

NameTypeDescriptionDefault
prerequisitesstr

The chat prerequisites content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_prerequisites(self, prerequisites: str) -> None:
    """Set the chat prerequisites.

    Parameters
    ----------
    prerequisites : str
        The chat prerequisites content.
    """
    self.chat_prerequisites = prerequisites
set_chat_registration
set_chat_registration(registration: str) -> None

Set the chat registration.

Parameters:

NameTypeDescriptionDefault
registrationstr

The chat registration content.

required
Source code in waldiez/exporting/core/extras/chat_extras.py
def set_chat_registration(self, registration: str) -> None:
    """Set the chat registration.

    Parameters
    ----------
    registration : str
        The chat registration content.
    """
    self.chat_registration = registration

flow_extras

Flow specific extras module.

FlowExtras dataclass

FlowExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    flow_name: str = "",
    description: str = "",
    config: ExportConfig = ExportConfig(),
    version: str = get_waldiez_version(),
    tools_result: Optional[ExportResult] = None,
    models_result: Optional[ExportResult] = None,
    agents_result: Optional[ExportResult] = None,
    chats_result: Optional[ExportResult] = None,
    header_content: str = "",
    main_function: str = "",
    after_run: str = "",
    execution_code: str = "",
)

Bases: BaseExtras

Extras for flow exporter.

has_specific_content
has_specific_content() -> bool

Check if the flow extras contain specific content.

Returns:

TypeDescription
bool

True if any specific content is present, False otherwise.

Source code in waldiez/exporting/core/extras/flow_extras.py
def has_specific_content(self) -> bool:
    """Check if the flow extras contain specific content.

    Returns
    -------
    bool
        True if any specific content is present, False otherwise.
    """
    return bool(
        self.flow_name
        or self.description
        or self.version
        or self.tools_result
        or self.models_result
        or self.agents_result
        or self.chats_result
        or self.header_content
        or self.main_function
        or self.execution_code
    )

model_extras

Agent specific extras module.

ModelExtras dataclass

ModelExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    llm_config: Optional[dict[str, Any]] = None,
    config_file_path: str = "",
)

Bases: BaseExtras

Extras for model exporters.

get_content
get_content() -> str

Get the content of the LLM configuration.

Returns:

TypeDescription
str

The serialized LLM configuration.

Source code in waldiez/exporting/core/extras/model_extras.py
def get_content(self) -> str:
    """Get the content of the LLM configuration.

    Returns
    -------
    str
        The serialized LLM configuration.
    """
    if self.llm_config and "content" in self.llm_config:
        return self.llm_config["content"]
    return ""
has_specific_content
has_specific_content() -> bool

Check for model specific content.

Returns:

TypeDescription
bool

True if there's model specific content.

Source code in waldiez/exporting/core/extras/model_extras.py
def has_specific_content(self) -> bool:
    """Check for model specific content.

    Returns
    -------
    bool
        True if there's model specific content.
    """
    if self.llm_config and "content" in self.llm_config:
        return bool(self.llm_config["content"])
    return False
set_config_file_path
set_config_file_path(path: str) -> None

Set the configuration file path.

Parameters:

NameTypeDescriptionDefault
pathstr

The configuration file path.

required
Source code in waldiez/exporting/core/extras/model_extras.py
def set_config_file_path(self, path: str) -> None:
    """Set the configuration file path.

    Parameters
    ----------
    path : str
        The configuration file path.
    """
    self.config_file_path = path
set_llm_config
set_llm_config(config: dict[str, Any]) -> None

Set the LLM configuration.

Parameters:

NameTypeDescriptionDefault
configdict[str, Any]

The LLM configuration.

required
Source code in waldiez/exporting/core/extras/model_extras.py
def set_llm_config(self, config: dict[str, Any]) -> None:
    """Set the LLM configuration.

    Parameters
    ----------
    config : dict[str, Any]
        The LLM configuration.
    """
    self.llm_config = config

path_resolver

Default path resolver for Waldiez items.

DefaultPathResolver

Bases: PathResolver

Default path resolver for Waldiez items.

resolve
resolve(path: str) -> str

Resolve a path to a local file system path.

Parameters:

NameTypeDescriptionDefault
pathUnion[str, Path]

The path to resolve.

required

Returns:

TypeDescription
Optional[Path]

The resolved local path or None if not found.

Source code in waldiez/exporting/core/extras/path_resolver.py
def resolve(self, path: str) -> str:
    """Resolve a path to a local file system path.

    Parameters
    ----------
    path : Union[str, Path]
        The path to resolve.

    Returns
    -------
    Optional[Path]
        The resolved local path or None if not found.
    """
    resolved = _check_local_path(path)
    if not resolved:
        return _get_raw_path_string(path)
    return _get_raw_path_string(resolved)

serializer

serializer for converting items to formatted strings.

DefaultSerializer

Bases: Serializer

Default serializer for Waldiez items.

serialize
serialize(obj: Any, **kwargs: Any) -> str

Serialize an item to a formatted string.

Parameters:

NameTypeDescriptionDefault
objAny

The item to serialize.

required
**kwargsAny

Additional keyword arguments, such as tabs for indentation level.

{}

Returns:

TypeDescription
str

The serialized string representation of the item.

Source code in waldiez/exporting/core/extras/serializer.py
def serialize(self, obj: Any, **kwargs: Any) -> str:
    """Serialize an item to a formatted string.

    Parameters
    ----------
    obj : Any
        The item to serialize.
    **kwargs : Any
        Additional keyword arguments, such as `tabs` for indentation level.

    Returns
    -------
    str
        The serialized string representation of the item.
    """
    tabs = kwargs.get("tabs", 1)
    return serialize_item(obj, tabs)

serialize_item

serialize_item(
    item: Any,
    tabs: int = 1,
    _visited: Optional[set[int]] = None,
) -> str

Convert an item to a formatted string with given indentation.

Parameters:

NameTypeDescriptionDefault
itemAny

The item to convert.

required
tabsint

The number of tabs, by default 1.

1

Returns:

TypeDescription
str

The formatted string.

Example
>>> obj = {"a": 1, "b": [1, 2, 3]}
>>> serialize_item(obj)
{
    "a": 1,
    "b": [
        1,
        2,
        3
    ]
}
>>> obj = {"a": 1, "b": [1, 2, 3], "c": {"d": 4}}
>>> serialize_item(obj, 2)
{
        "a": 1,
        "b": [
            1,
            2,
            3
        ],
        "c": {
            "d": 4
        }
}
Source code in waldiez/exporting/core/extras/serializer.py
def serialize_item(
    item: Any,
    tabs: int = 1,
    _visited: Optional[set[int]] = None,
) -> str:
    """Convert an item to a formatted string with given indentation.

    Parameters
    ----------
    item : Any
        The item to convert.
    tabs : int, optional
        The number of tabs, by default 1.

    Returns
    -------
    str
        The formatted string.

    Example
    -------
    ```python
    >>> obj = {"a": 1, "b": [1, 2, 3]}
    >>> serialize_item(obj)
    {
        "a": 1,
        "b": [
            1,
            2,
            3
        ]
    }
    >>> obj = {"a": 1, "b": [1, 2, 3], "c": {"d": 4}}
    >>> serialize_item(obj, 2)
    {
            "a": 1,
            "b": [
                1,
                2,
                3
            ],
            "c": {
                "d": 4
            }
    }
    ```
    """
    if _visited is None:
        _visited = set()

    if callable(item):
        return item.__name__

    # Handle primitives and preformatted literals
    if isinstance(item, (str, int, float, bool)) or item is None:
        return _format_primitive(item)

    # Handle circular references in containers
    if isinstance(item, (dict, list)) and id(item) in _visited:
        return '"<circular reference>"'

    next_indent = " " * 4 * (tabs + 1)
    _visited.add(id(item))

    if isinstance(item, dict):
        items: list[str] = []
        for key, value in item.items():
            key_str = f'{next_indent}"{key}"'
            value_str = serialize_item(value, tabs + 1, _visited)
            items.append(f"{key_str}: {value_str}")
        return _format_container(items, "{", "}", tabs)

    if isinstance(item, list):
        items = [
            f"{next_indent}{serialize_item(sub_item, tabs + 1, _visited)}"
            for sub_item in item
        ]
        return _format_container(items, "[", "]", tabs)

    # Fallback for unknown object types
    return repr(item)

tool_extras

Agent specific extras module.

ToolExtras dataclass

ToolExtras(
    instance_id: str,
    extra_imports: list[ImportStatement] = list[
        ImportStatement
    ](),
    before_agent: str = "",
    after_agent: str = "",
    after_all_agents: str = "",
    extra_args: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    function_content: str = "",
    registration_content: str = "",
)

Bases: BaseExtras

Extras for tool exporters.

add_function_content
add_function_content(content: str) -> None

Add function definition content.

Parameters:

NameTypeDescriptionDefault
contentstr

The function content to add.

required
Source code in waldiez/exporting/core/extras/tool_extras.py
def add_function_content(self, content: str) -> None:
    """Add function definition content.

    Parameters
    ----------
    content : str
        The function content to add.
    """
    if content and content.strip():  # pragma: no branch
        if self.function_content:
            self.function_content += "\n\n" + content.rstrip()
        else:
            self.function_content = content.rstrip()
        while not self.function_content.endswith("\n\n"):
            self.function_content += "\n\n"
add_registration_content
add_registration_content(content: str) -> None

Add function registration content.

Parameters:

NameTypeDescriptionDefault
contentstr

The registration content to add.

required
Source code in waldiez/exporting/core/extras/tool_extras.py
def add_registration_content(self, content: str) -> None:
    """Add function registration content.

    Parameters
    ----------
    content : str
        The registration content to add.
    """
    if content and content.strip():  # pragma: no branch
        self.registration_content += "\n" + content.rstrip() + "\n"
has_specific_content
has_specific_content() -> bool

Check for tool specific content.

Returns:

TypeDescription
bool

True if there's tool specific content.

Source code in waldiez/exporting/core/extras/tool_extras.py
def has_specific_content(self) -> bool:
    """Check for tool specific content.

    Returns
    -------
    bool
        True if there's tool specific content.
    """
    return bool(
        self.function_content.strip() or self.registration_content.strip()
    )

get_agent_llm_config_arg

get_agent_llm_config_arg(
    agent: WaldiezAgent,
    all_models: list[WaldiezModel],
    model_names: dict[str, str],
    cache_seed: int | None,
    as_dict: bool = False,
    tabs: int = 1,
) -> str

Get the string representation of the agent's llm config argument.

Parameters:

NameTypeDescriptionDefault
agentWaldiezAgent

The agent.

required
all_modelslist[WaldiezModel]

All the models in the flow.

required
model_namesdict[str, str]

A mapping of model ids to model names.

required
cache_seedOptional[int]

The cache seed.

required
as_dictbool

Whether to return the argument as a dictionary, by default False.

False
tabsint

The number of tabs for indentation, by default 1.

1

Returns:

TypeDescription
str

The agent's llm config argument to use.

Source code in waldiez/exporting/core/utils/llm_config.py
def get_agent_llm_config_arg(
    agent: WaldiezAgent,
    all_models: list[WaldiezModel],
    model_names: dict[str, str],
    cache_seed: int | None,
    as_dict: bool = False,
    tabs: int = 1,
) -> str:
    """Get the string representation of the agent's llm config argument.

    Parameters
    ----------
    agent : WaldiezAgent
        The agent.
    all_models : list[WaldiezModel]
        All the models in the flow.
    model_names : dict[str, str]
        A mapping of model ids to model names.
    cache_seed : Optional[int]
        The cache seed.
    as_dict : bool, optional
        Whether to return the argument as a dictionary, by default False.
    tabs : int, optional
        The number of tabs for indentation, by default 1.

    Returns
    -------
    str
        The agent's llm config argument to use.
    """
    if as_dict is False:
        return _get_agent_llm_config_arg_as_arg(
            agent,
            all_models,
            model_names,
            cache_seed,
            tabs=tabs,
        )
    return _get_agent_llm_config_arg_as_dict(
        agent,
        all_models,
        model_names,
        cache_seed,
        tabs=tabs + 1,
    )

get_comment

get_comment(
    comment: str,
    for_notebook: bool = False,
    md_headings: int = 3,
) -> str

Get a comment for the script or notebook.

Parameters:

NameTypeDescriptionDefault
commentstr

The comment to add.

required
for_notebookbool

Whether the comment is for a notebook, by default False

False
md_headingsint

The number of markdown headings to use (if for_notebook is True), by default 2

3

Returns:

TypeDescription
str

The formatted comment.

Source code in waldiez/exporting/core/utils/comment.py
def get_comment(
    comment: str,
    for_notebook: bool = False,
    md_headings: int = 3,
) -> str:
    """Get a comment for the script or notebook.

    Parameters
    ----------
    comment : str
        The comment to add.
    for_notebook : bool, optional
        Whether the comment is for a notebook, by default False
    md_headings : int, optional
        The number of markdown headings to use (if for_notebook is True),
        by default 2

    Returns
    -------
    str
        The formatted comment.
    """
    if for_notebook:
        # For notebooks, we use markdown headings
        heading = "#" + "#" * md_headings
        return f"# %% [markdown]\n{heading} {comment}\n# %% \n"
    # For scripts, we use a simple comment
    return f"# {comment}\n"

get_default_exporter_context

get_default_exporter_context(
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
) -> ExporterContext

Get the default exporter context.

Parameters:

NameTypeDescriptionDefault
configOptional[ExportConfig]

The export configuration, by default None

None
loggerOptional[ExportingLogger]

The logger instance, by default None

None

Returns:

TypeDescription
ExporterContext

The default exporter context.

Source code in waldiez/exporting/core/context.py
def get_default_exporter_context(
    config: Optional[ExportConfig] = None,
    logger: Optional[ExportingLogger] = None,
) -> ExporterContext:
    """Get the default exporter context.

    Parameters
    ----------
    config : Optional[ExportConfig], optional
        The export configuration, by default None
    logger : Optional[ExportingLogger], optional
        The logger instance, by default None

    Returns
    -------
    ExporterContext
        The default exporter context.
    """
    return DefaultExporterContext(
        serializer=DefaultSerializer(),
        path_resolver=DefaultPathResolver(),
        logger=logger or WaldiezLogger(),
        config=config,
    )

merge_export_results

merge_export_results(
    *results: ExportResult,
) -> ExportResult

Merge multiple ExportResult objects into one.

Parameters:

NameTypeDescriptionDefault
*resultsExportResult

Variable number of ExportResult objects to merge.

()

Returns:

TypeDescription
ExportResult

A new ExportResult containing all merged content.

Source code in waldiez/exporting/core/result.py
def merge_export_results(*results: ExportResult) -> ExportResult:
    """Merge multiple ExportResult objects into one.

    Parameters
    ----------
    *results : ExportResult
        Variable number of ExportResult objects to merge.

    Returns
    -------
    ExportResult
        A new ExportResult containing all merged content.
    """
    if not results:
        return ExportResult()

    merged = ExportResult()
    for result in results:
        merged.merge_with(result)

    return merged

protocols

Core exporting protocols.

ContentGenerator

Bases: Protocol

Protocol for generating content.

generate

generate(
    merged_result: ExportResult,
    is_async: bool,
    after_run: str,
    **kwargs: Any
) -> str

Generate content based on provided parameters.

Parameters:

NameTypeDescriptionDefault
merged_resultExportResult

The merged export result containing all content.

required
is_asyncbool

Whether to generate async content.

required
after_runstr

Additional content to add after the main flow execution.

required
**kwargsAny

Parameters to influence content generation.

{}

Returns:

TypeDescription
str

The generated content.

Source code in waldiez/exporting/core/protocols.py
def generate(
    self,
    merged_result: ExportResult,
    is_async: bool,
    after_run: str,
    **kwargs: Any,
) -> str:  # pyright: ignore
    """Generate content based on provided parameters.

    Parameters
    ----------
    merged_result : ExportResult
        The merged export result containing all content.
    is_async : bool
        Whether to generate async content.
    after_run : str
        Additional content to add after the main flow execution.
    **kwargs : Any
        Parameters to influence content generation.

    Returns
    -------
    str
        The generated content.
    """

ExportContributor

Bases: Protocol

Protocol for objects that can contribute to exports.

contribute_to_export

contribute_to_export(result: ExportResult) -> None

Contribute content to the export result.

Parameters:

NameTypeDescriptionDefault
resultExportResult

The export result to contribute to.

required
Source code in waldiez/exporting/core/protocols.py
def contribute_to_export(self, result: ExportResult) -> None:
    """Contribute content to the export result.

    Parameters
    ----------
    result : ExportResult
        The export result to contribute to.
    """

ExportingLogger

Bases: Protocol

Protocol for logging during exporting.

critical

critical(message: Any, *args: Any, **kwargs: Any) -> None

Log a critical error message.

Parameters:

NameTypeDescriptionDefault
messageAny

The critical error message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def critical(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log a critical error message.

    Parameters
    ----------
    message : Any
        The critical error message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """
    self.log(message, *args, level="critical", **kwargs)

debug

debug(message: Any, *args: Any, **kwargs: Any) -> None

Log a debug message.

Parameters:

NameTypeDescriptionDefault
messageAny

The debug message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def debug(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log a debug message.

    Parameters
    ----------
    message : Any
        The debug message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """
    self.log(message, *args, level="debug", **kwargs)

error

error(message: Any, *args: Any, **kwargs: Any) -> None

Log an error message.

Parameters:

NameTypeDescriptionDefault
messageAny

The error message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def error(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log an error message.

    Parameters
    ----------
    message : Any
        The error message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

exception

exception(message: Any, *args: Any, **kwargs: Any) -> None

Log an exception message.

Parameters:

NameTypeDescriptionDefault
messageAny

The exception message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def exception(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log an exception message.

    Parameters
    ----------
    message : Any
        The exception message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """
    self.log(message, *args, level="exception", **kwargs)

get_level

get_level() -> str

Get the current logging level.

Returns:

TypeDescription
str

The current logging level.

Source code in waldiez/exporting/core/protocols.py
def get_level(self) -> str:  # pyright: ignore
    """Get the current logging level.

    Returns
    -------
    str
        The current logging level.
    """

info

info(message: Any, *args: Any, **kwargs: Any) -> None

Log an informational message.

Parameters:

NameTypeDescriptionDefault
messageAny

The informational message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def info(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log an informational message.

    Parameters
    ----------
    message : Any
        The informational message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

log

log(
    message: Any,
    *args: Any,
    level: str = "info",
    **kwargs: Any
) -> None

Log a message with the specified level.

Parameters:

NameTypeDescriptionDefault
messageAny

The message to log or message template for formatting.

required
levelstr

The logging level to use (e.g., "debug", "info", "warning", "error", "critical"). Defaults to "info".

'info'
*argsAny

Arguments to format into the message using % formatting.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def log(
    self, message: Any, *args: Any, level: str = "info", **kwargs: Any
) -> None:
    """Log a message with the specified level.

    Parameters
    ----------
    message : Any
        The message to log or message template for formatting.
    level : str, optional
        The logging level to use (e.g., "debug", "info", "warning", "error",
        "critical"). Defaults to "info".
    *args : Any
        Arguments to format into the message using % formatting.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

set_level

set_level(level: str) -> None

Set the logging level.

Parameters:

NameTypeDescriptionDefault
levelstr

The logging level to set (e.g., "debug", "info", "warning", "error", "critical").

required

Raises:

TypeDescription
ValueError

If the provided level is invalid.

Source code in waldiez/exporting/core/protocols.py
def set_level(self, level: str) -> None:
    """Set the logging level.

    Parameters
    ----------
    level : str
        The logging level to set
        (e.g., "debug", "info", "warning", "error", "critical").

    Raises
    ------
    ValueError
        If the provided level is invalid.
    """

success

success(message: Any, *args: Any, **kwargs: Any) -> None

Log a success message.

Parameters:

NameTypeDescriptionDefault
messageAny

The success message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def success(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log a success message.

    Parameters
    ----------
    message : Any
        The success message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

warning

warning(message: Any, *args: Any, **kwargs: Any) -> None

Log a warning message.

Parameters:

NameTypeDescriptionDefault
messageAny

The warning message to log or message template.

required
*argsAny

Arguments to format into the message.

()
**kwargsAny

Keyword arguments to format into the message using str.format().

{}
Source code in waldiez/exporting/core/protocols.py
def warning(self, message: Any, *args: Any, **kwargs: Any) -> None:
    """Log a warning message.

    Parameters
    ----------
    message : Any
        The warning message to log or message template.
    *args : Any
        Arguments to format into the message.
    **kwargs : Any
        Keyword arguments to format into the message using str.format().
    """

PathResolver

Bases: Protocol

Protocol for resolving a path.

resolve

resolve(path: str) -> str

Resolve a path.

Parameters:

NameTypeDescriptionDefault
pathstr

The path to resolve.

required

Returns:

TypeDescription
str

The resolved path.

Raises:

TypeDescription
ValueError

If the path cannot be resolved.

Source code in waldiez/exporting/core/protocols.py
def resolve(self, path: str) -> str:  # pyright: ignore
    """Resolve a path.

    Parameters
    ----------
    path : str
        The path to resolve.

    Returns
    -------
    str
        The resolved path.

    Raises
    ------
    ValueError
        If the path cannot be resolved.
    """

Serializer

Bases: Protocol

Protocol for serialization components.

serialize

serialize(obj: Any, **kwargs: Any) -> str

Serialize an object to string representation.

Parameters:

NameTypeDescriptionDefault
objAny

The object to serialize.

required
**kwargsAny

Additional keyword arguments for serialization.

{}

Returns:

TypeDescription
str

The serialized representation.

Source code in waldiez/exporting/core/protocols.py
def serialize(self, obj: Any, **kwargs: Any) -> str:  # pyright: ignore
    """Serialize an object to string representation.

    Parameters
    ----------
    obj : Any
        The object to serialize.
    **kwargs : Any
        Additional keyword arguments for serialization.

    Returns
    -------
    str
        The serialized representation.
    """

Validator

Bases: Protocol

Protocol for validation components.

validate

validate(content: Any) -> ValidationResult

Validate content and return result.

Parameters:

NameTypeDescriptionDefault
contentAny

The content to validate.

required

Returns:

TypeDescription
ValidationResult

The validation result.

Source code in waldiez/exporting/core/protocols.py
def validate(self, content: Any) -> ValidationResult:  # pyright: ignore
    """Validate content and return result.

    Parameters
    ----------
    content : Any
        The content to validate.

    Returns
    -------
    ValidationResult
        The validation result.
    """

result

Export result containers and related classes.

ExportResult dataclass

ExportResult(
    main_content: Optional[str] = None,
    imports: set[ImportStatement] = set[ImportStatement](),
    positioned_content: list[PositionedContent] = list[
        PositionedContent
    ](),
    instance_arguments: list[InstanceArgument] = list[
        InstanceArgument
    ](),
    environment_variables: list[EnvironmentVariable] = list[
        EnvironmentVariable
    ](),
    validation_result: Optional[ValidationResult] = None,
    metadata: dict[str, Any] = dict[str, Any](),
)

Complete export result with all components.

add_content

add_content(
    content: str,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
    order: Union[ContentOrder, int] = MAIN_CONTENT,
    skip_strip: bool = False,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    metadata: Optional[dict[str, Any]] = None,
) -> None

Add positioned content.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to add.

required
positionExportPosition

The position of the content, by default AGENTS

DEFAULT_EXPORT_POSITION
orderint

The order within the position, by default 0

MAIN_CONTENT
skip_stripbool

Whether to skip stripping whitespace from content, by default False

False
agent_idOptional[str]

The agent ID if positioned relative to an agent, by default None

None
agent_positionOptional[AgentPosition]

The position relative to the agent, by default None

None
metadataOptional[dict[str, Any]]

Additional metadata for the content, by default None

None
Source code in waldiez/exporting/core/result.py
def add_content(
    self,
    content: str,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
    order: Union[ContentOrder, int] = ContentOrder.MAIN_CONTENT,
    skip_strip: bool = False,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
    metadata: Optional[dict[str, Any]] = None,
) -> None:
    """Add positioned content.

    Parameters
    ----------
    content : str
        The content to add.
    position : ExportPosition, optional
        The position of the content, by default AGENTS
    order : int, optional
        The order within the position, by default 0
    skip_strip : bool, optional
        Whether to skip stripping whitespace from content, by default False
    agent_id : Optional[str], optional
        The agent ID if positioned relative to an agent, by default None
    agent_position : Optional[AgentPosition], optional
        The position relative to the agent, by default None
    metadata : Optional[dict[str, Any]], optional
        Additional metadata for the content, by default None
    """
    order_value = order.value if isinstance(order, ContentOrder) else order
    if content and content.strip():
        positioned = PositionedContent(
            content=content.strip() if not skip_strip else content,
            position=position,
            order=order_value,
            agent_id=agent_id,
            agent_position=agent_position,
            **(metadata or {}),
        )
        if positioned not in self.positioned_content:
            self.positioned_content.append(positioned)

add_env_var

add_env_var(
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
) -> None

Add environment variable.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the environment variable.

required
valuestr

The value of the environment variable.

required
descriptionOptional[str]

Description of the variable, by default None

None
requiredbool

Whether the variable is required, by default True

True
Source code in waldiez/exporting/core/result.py
def add_env_var(
    self,
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
) -> None:
    """Add environment variable.

    Parameters
    ----------
    name : str
        The name of the environment variable.
    value : str
        The value of the environment variable.
    description : Optional[str], optional
        Description of the variable, by default None
    required : bool, optional
        Whether the variable is required, by default True
    """
    if name and value:
        env_var = EnvironmentVariable(
            name=name,
            value=value,
            description=description,
            required=required,
        )
        # Avoid duplicates based on name
        for existing in self.environment_variables:
            if existing.name == name:
                # Update existing
                existing.value = value
                existing.description = description
                existing.required = required
                return
        self.environment_variables.append(env_var)

add_import

add_import(
    statement: str,
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None

Add an import statement.

Parameters:

NameTypeDescriptionDefault
statementstr

The import statement to add.

required
positionImportPosition

The position of the import, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION
Source code in waldiez/exporting/core/result.py
def add_import(
    self, statement: str, position: ImportPosition = DEFAULT_IMPORT_POSITION
) -> None:
    """Add an import statement.

    Parameters
    ----------
    statement : str
        The import statement to add.
    position : ImportPosition, optional
        The position of the import, by default THIRD_PARTY
    """
    if statement and statement.strip():
        self.imports.add(
            ImportStatement(
                statement=statement.strip(),
                position=position,
            )
        )

add_imports

add_imports(
    statements: Union[
        set[str],
        list[str],
        set[ImportStatement],
        list[ImportStatement],
    ],
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None

Add multiple import statements.

Parameters:

NameTypeDescriptionDefault
statementsUnion[
set[str],
list[str]],
set[ImportStatement],
list[ImportStatement]

] The import statements to add.

required
positionImportPosition

The position of the imports, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION
Source code in waldiez/exporting/core/result.py
def add_imports(
    self,
    statements: Union[
        set[str],
        list[str],
        set[ImportStatement],
        list[ImportStatement],
    ],
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> None:
    """Add multiple import statements.

    Parameters
    ----------
    statements : Union[
            set[str],
            list[str]],
            set[ImportStatement],
            list[ImportStatement]
        ]
        The import statements to add.
    position : ImportPosition, optional
        The position of the imports, by default THIRD_PARTY
    """
    for statement in statements:
        if isinstance(statement, ImportStatement):
            # If it's already an ImportStatement, use it directly
            self.add_import(statement.statement, statement.position)
        else:
            # Otherwise, treat it as a string
            self.add_import(statement, position)

add_instance_argument

add_instance_argument(
    name: str,
    value: Any,
    instance_id: str,
    tabs: int = 0,
    comment: Optional[str] = None,
) -> None

Add an instance argument.

Parameters:

NameTypeDescriptionDefault
namestr

The name of the argument.

required
valueAny

The value of the argument.

required
instance_idstr

The ID of the instance this argument belongs to.

required
tabsint

Number of tabs for indentation, by default 0

0
commentOptional[str]

Optional comment for the argument, by default None

None
Source code in waldiez/exporting/core/result.py
def add_instance_argument(
    self,
    name: str,
    value: Any,
    instance_id: str,
    tabs: int = 0,
    comment: Optional[str] = None,
) -> None:
    """Add an instance argument.

    Parameters
    ----------
    name : str
        The name of the argument.
    value : Any
        The value of the argument.
    instance_id : str
        The ID of the instance this argument belongs to.
    tabs : int, optional
        Number of tabs for indentation, by default 0
    comment : Optional[str], optional
        Optional comment for the argument, by default None
    """
    if name and value is not None:
        arg = InstanceArgument(
            instance_id=instance_id,
            name=name,
            value=value,
            comment=comment,
            tabs=tabs,
        )
        # Avoid duplicates based on name
        for existing in self.instance_arguments:
            if existing.name == name:
                # Update existing
                existing.value = value
                existing.comment = comment
                return
        self.instance_arguments.append(arg)

add_instance_arguments

add_instance_arguments(
    arguments: Union[
        list[InstanceArgument], set[InstanceArgument]
    ],
) -> None

Add multiple instance arguments.

Parameters:

NameTypeDescriptionDefault
argumentsUnion[list[InstanceArgument], set[InstanceArgument]]

The instance arguments to add.

required
Source code in waldiez/exporting/core/result.py
def add_instance_arguments(
    self,
    arguments: Union[list[InstanceArgument], set[InstanceArgument]],
) -> None:
    """Add multiple instance arguments.

    Parameters
    ----------
    arguments : Union[list[InstanceArgument], set[InstanceArgument]]
        The instance arguments to add.
    """
    for arg in arguments:
        self.add_instance_argument(
            instance_id=arg.instance_id,
            name=arg.name,
            value=arg.value,
            comment=arg.comment,
        )

clear

clear() -> None

Clear all content from the result.

Source code in waldiez/exporting/core/result.py
def clear(self) -> None:
    """Clear all content from the result."""
    self.main_content = None
    self.imports.clear()
    self.positioned_content.clear()
    self.environment_variables.clear()
    self.validation_result = None
    self.metadata.clear()

get_agent_content

get_agent_content(
    agent_id: str,
    agent_position: Optional[AgentPosition] = None,
) -> list[PositionedContent]

Get content positioned relative to a specific agent.

Parameters:

NameTypeDescriptionDefault
agent_idstr

The ID of the agent.

required
agent_positionOptional[AgentPosition]

Filter by specific agent position, by default None (all positions)

None

Returns:

TypeDescription
list[PositionedContent]

Sorted list of content for the specified agent.

Source code in waldiez/exporting/core/result.py
def get_agent_content(
    self, agent_id: str, agent_position: Optional[AgentPosition] = None
) -> list[PositionedContent]:
    """Get content positioned relative to a specific agent.

    Parameters
    ----------
    agent_id : str
        The ID of the agent.
    agent_position : Optional[AgentPosition], optional
        Filter by specific agent position, by default None (all positions)

    Returns
    -------
    list[PositionedContent]
        Sorted list of content for the specified agent.
    """
    content = [
        c
        for c in self.positioned_content
        if c.agent_id == agent_id
        and (agent_position is None or c.agent_position == agent_position)
    ]
    return sorted(content)

get_all_content_sorted

get_all_content_sorted() -> list[PositionedContent]

Get all positioned content sorted by position and order.

Returns:

TypeDescription
list[PositionedContent]

All positioned content sorted.

Source code in waldiez/exporting/core/result.py
def get_all_content_sorted(self) -> list[PositionedContent]:
    """Get all positioned content sorted by position and order.

    Returns
    -------
    list[PositionedContent]
        All positioned content sorted.
    """
    return sorted(self.positioned_content)

get_content_by_position

get_content_by_position(
    position: ExportPosition,
    skip_agent_arguments: bool = True,
) -> list[PositionedContent]

Get all content for a specific position.

Parameters:

NameTypeDescriptionDefault
positionExportPosition

The position to filter by.

required
skip_agent_argumentsbool

Whether to skip content positioned as agent arguments, by default True

True

Returns:

TypeDescription
list[PositionedContent]

Sorted list of content for the specified position.

Source code in waldiez/exporting/core/result.py
def get_content_by_position(
    self,
    position: ExportPosition,
    skip_agent_arguments: bool = True,
) -> list[PositionedContent]:
    """Get all content for a specific position.

    Parameters
    ----------
    position : ExportPosition
        The position to filter by.
    skip_agent_arguments : bool, optional
        Whether to skip content positioned as agent arguments,
        by default True

    Returns
    -------
    list[PositionedContent]
        Sorted list of content for the specified position.
    """
    if not skip_agent_arguments:
        content = [
            c for c in self.positioned_content if c.position == position
        ]
    else:
        content = [
            c
            for c in self.positioned_content
            if c.position == position
            and (c.agent_position != AgentPosition.AS_ARGUMENT)
        ]
    return sorted(content)

get_imports_by_position

get_imports_by_position(
    position: ImportPosition,
) -> list[ImportStatement]

Get imports filtered by position.

Parameters:

NameTypeDescriptionDefault
positionImportPosition

The position to filter by.

required

Returns:

TypeDescription
list[ImportStatement]

list of imports for the specified position.

Source code in waldiez/exporting/core/result.py
def get_imports_by_position(
    self, position: ImportPosition
) -> list[ImportStatement]:
    """Get imports filtered by position.

    Parameters
    ----------
    position : ImportPosition
        The position to filter by.

    Returns
    -------
    list[ImportStatement]
        list of imports for the specified position.
    """
    return [
        imp for imp in self.get_sorted_imports() if imp.position == position
    ]

get_sorted_imports

get_sorted_imports() -> list[ImportStatement]

Get imports sorted by position and statement.

Returns:

TypeDescription
list[ImportStatement]

Sorted list of import statements.

Source code in waldiez/exporting/core/result.py
def get_sorted_imports(self) -> list[ImportStatement]:
    """Get imports sorted by position and statement.

    Returns
    -------
    list[ImportStatement]
        Sorted list of import statements.
    """
    return sorted(self.imports)

get_statistics

get_statistics() -> dict[str, int]

Get statistics about the export result.

Returns:

TypeDescription
dict[str, int]

dictionary with statistics about the export.

Source code in waldiez/exporting/core/result.py
def get_statistics(self) -> dict[str, int]:
    """Get statistics about the export result.

    Returns
    -------
    dict[str, int]
        dictionary with statistics about the export.
    """
    return {
        "total_imports": len(self.imports),
        "builtin_imports": len(
            self.get_imports_by_position(ImportPosition.BUILTINS)
        ),
        "third_party_imports": len(
            self.get_imports_by_position(ImportPosition.THIRD_PARTY)
        ),
        "local_imports": len(
            self.get_imports_by_position(ImportPosition.LOCAL)
        ),
        "positioned_content_items": len(self.positioned_content),
        "environment_variables": len(self.environment_variables),
        "validation_errors": (
            len(self.validation_result.errors)
            if self.validation_result
            else 0
        ),
        "validation_warnings": (
            len(self.validation_result.warnings)
            if self.validation_result
            else 0
        ),
    }

has_content

has_content() -> bool

Check if there's any meaningful content.

Returns:

TypeDescription
bool

True if there's any content, imports, or environment variables.

Source code in waldiez/exporting/core/result.py
def has_content(self) -> bool:
    """Check if there's any meaningful content.

    Returns
    -------
    bool
        True if there's any content, imports, or environment variables.
    """
    return bool(
        self.main_content
        or self.imports
        or self.positioned_content
        or self.environment_variables
    )

has_errors

has_errors() -> bool

Check if there are validation errors.

Returns:

TypeDescription
bool

True if there are validation errors.

Source code in waldiez/exporting/core/result.py
def has_errors(self) -> bool:
    """Check if there are validation errors.

    Returns
    -------
    bool
        True if there are validation errors.
    """
    return (
        self.validation_result is not None
        and self.validation_result.has_errors()
    )

has_warnings

has_warnings() -> bool

Check if there are validation warnings.

Returns:

TypeDescription
bool

True if there are validation warnings.

Source code in waldiez/exporting/core/result.py
def has_warnings(self) -> bool:
    """Check if there are validation warnings.

    Returns
    -------
    bool
        True if there are validation warnings.
    """
    return (
        self.validation_result is not None
        and self.validation_result.has_warnings()
    )

merge

merge(
    other: ExportResult,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
) -> None

Merge another ExportResult into this one.

Parameters:

NameTypeDescriptionDefault
otherExportResult

The other result to merge.

required
positionExportPosition

The position for the merged content, by default AGENTS

DEFAULT_EXPORT_POSITION
Source code in waldiez/exporting/core/result.py
def merge(
    self,
    other: "ExportResult",
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
) -> None:
    """Merge another ExportResult into this one.

    Parameters
    ----------
    other : ExportResult
        The other result to merge.
    position : ExportPosition, optional
        The position for the merged content, by default AGENTS
    """
    if other.main_content:
        self.main_content = (
            (self.main_content or "") + "\n" + other.main_content
        ).strip()

    self.imports.update(other.imports)

    self.positioned_content.extend(
        PositionedContent(
            content=c.content,
            position=position,
            order=c.order,
            agent_id=c.agent_id,
            agent_position=c.agent_position,
            **c.metadata,
        )
        for c in other.positioned_content
    )

    self.environment_variables.extend(other.environment_variables)

    if other.validation_result:
        if self.validation_result:
            self.validation_result.merge(other.validation_result)
        else:
            self.validation_result = other.validation_result

    # Merge instance arguments
    for arg in other.instance_arguments:
        self.add_instance_argument(
            name=arg.name,
            value=arg.value,
            instance_id=arg.instance_id,
            comment=arg.comment,
        )

    self.metadata.update(other.metadata)

merge_with

merge_with(other: ExportResult) -> None

Merge another ExportResult into this one.

Parameters:

NameTypeDescriptionDefault
otherExportResult

The other result to merge.

required
Source code in waldiez/exporting/core/result.py
def merge_with(self, other: "ExportResult") -> None:
    """Merge another ExportResult into this one.

    Parameters
    ----------
    other : ExportResult
        The other result to merge.
    """
    # Merge imports (set automatically handles duplicates)
    self.imports.update(other.imports)

    # Merge positioned content
    self.positioned_content.extend(other.positioned_content)

    # Merge environment variables (avoid duplicates by name)
    for env_var in other.environment_variables:
        self.add_env_var(
            env_var.name,
            env_var.value,
            env_var.description,
            env_var.required,
        )

    # Merge metadata
    self.metadata.update(other.metadata)

    # Handle validation results
    if other.validation_result:
        if self.validation_result:
            # Merge validation results
            self.validation_result.errors.extend(
                other.validation_result.errors
            )
            self.validation_result.warnings.extend(
                other.validation_result.warnings
            )
            self.validation_result.is_valid = (
                self.validation_result.is_valid
                and other.validation_result.is_valid
            )
        else:
            self.validation_result = other.validation_result

ExportResultBuilder dataclass

ExportResultBuilder(_result: ExportResult = ExportResult())

Builder pattern for constructing ExportResult objects.

build

build() -> ExportResult

Build the final ExportResult.

Returns:

TypeDescription
ExportResult

The constructed ExportResult.

Source code in waldiez/exporting/core/result.py
def build(self) -> ExportResult:
    """Build the final ExportResult.

    Returns
    -------
    ExportResult
        The constructed ExportResult.
    """
    return self._result

with_content

with_content(
    content: str,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
    order: ContentOrder = MAIN_CONTENT,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
) -> ExportResultBuilder

Add positioned content.

Parameters:

NameTypeDescriptionDefault
contentstr

The content to add.

required
positionExportPosition

The content position, by default AGENTS

DEFAULT_EXPORT_POSITION
orderint

The order within position, by default 0

MAIN_CONTENT
agent_idOptional[str]

Agent ID for agent-relative positioning, by default None

None
agent_positionOptional[AgentPosition]

Position relative to agent, by default None

None

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_content(
    self,
    content: str,
    position: ExportPosition = DEFAULT_EXPORT_POSITION,
    order: ContentOrder = ContentOrder.MAIN_CONTENT,
    agent_id: Optional[str] = None,
    agent_position: Optional[AgentPosition] = None,
) -> "ExportResultBuilder":
    """Add positioned content.

    Parameters
    ----------
    content : str
        The content to add.
    position : ExportPosition, optional
        The content position, by default AGENTS
    order : int, optional
        The order within position, by default 0
    agent_id : Optional[str], optional
        Agent ID for agent-relative positioning, by default None
    agent_position : Optional[AgentPosition], optional
        Position relative to agent, by default None

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.add_content(
        content=content,
        position=position,
        order=order,
        agent_id=agent_id,
        agent_position=agent_position,
    )
    return self

with_env_var

with_env_var(
    name: str, value: str, description: Optional[str] = None
) -> ExportResultBuilder

Add environment variable.

Parameters:

NameTypeDescriptionDefault
namestr

Variable name.

required
valuestr

Variable value.

required
descriptionOptional[str]

Variable description, by default None

None

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_env_var(
    self, name: str, value: str, description: Optional[str] = None
) -> "ExportResultBuilder":
    """Add environment variable.

    Parameters
    ----------
    name : str
        Variable name.
    value : str
        Variable value.
    description : Optional[str], optional
        Variable description, by default None

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.add_env_var(name, value, description)
    return self

with_import

with_import(
    statement: str,
    position: ImportPosition = DEFAULT_IMPORT_POSITION,
) -> ExportResultBuilder

Add an import statement.

Parameters:

NameTypeDescriptionDefault
statementstr

The import statement.

required
positionImportPosition

The import position, by default THIRD_PARTY

DEFAULT_IMPORT_POSITION

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_import(
    self, statement: str, position: ImportPosition = DEFAULT_IMPORT_POSITION
) -> "ExportResultBuilder":
    """Add an import statement.

    Parameters
    ----------
    statement : str
        The import statement.
    position : ImportPosition, optional
        The import position, by default THIRD_PARTY

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.add_import(statement, position)
    return self

with_main_content

with_main_content(content: str) -> ExportResultBuilder

Set the main content.

Parameters:

NameTypeDescriptionDefault
contentstr

The main content to set.

required

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_main_content(self, content: str) -> "ExportResultBuilder":
    """Set the main content.

    Parameters
    ----------
    content : str
        The main content to set.

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.main_content = content
    return self

with_metadata

with_metadata(key: str, value: Any) -> ExportResultBuilder

Add metadata.

Parameters:

NameTypeDescriptionDefault
keystr

Metadata key.

required
valueAny

Metadata value.

required

Returns:

TypeDescription
ExportResultBuilder

Self for method chaining.

Source code in waldiez/exporting/core/result.py
def with_metadata(self, key: str, value: Any) -> "ExportResultBuilder":
    """Add metadata.

    Parameters
    ----------
    key : str
        Metadata key.
    value : Any
        Metadata value.

    Returns
    -------
    ExportResultBuilder
        Self for method chaining.
    """
    self._result.metadata[key] = value
    return self

create_empty_result

create_empty_result() -> ExportResult

Create an empty ExportResult.

Returns:

TypeDescription
ExportResult

An empty ExportResult instance.

Source code in waldiez/exporting/core/result.py
def create_empty_result() -> ExportResult:
    """Create an empty ExportResult.

    Returns
    -------
    ExportResult
        An empty ExportResult instance.
    """
    return ExportResult()

create_result_with_content

create_result_with_content(
    main_content: str, imports: Optional[list[str]] = None
) -> ExportResult

Create an ExportResult with basic content.

Parameters:

NameTypeDescriptionDefault
main_contentstr

The main content.

required
importsOptional[list[str]]

list of import statements, by default None

None

Returns:

TypeDescription
ExportResult

The created ExportResult.

Source code in waldiez/exporting/core/result.py
def create_result_with_content(
    main_content: str,
    imports: Optional[list[str]] = None,
) -> ExportResult:
    """Create an ExportResult with basic content.

    Parameters
    ----------
    main_content : str
        The main content.
    imports : Optional[list[str]], optional
        list of import statements, by default None

    Returns
    -------
    ExportResult
        The created ExportResult.
    """
    result = ExportResult(main_content=main_content)

    if imports:
        result.add_imports(imports)

    return result

merge_export_results

merge_export_results(
    *results: ExportResult,
) -> ExportResult

Merge multiple ExportResult objects into one.

Parameters:

NameTypeDescriptionDefault
*resultsExportResult

Variable number of ExportResult objects to merge.

()

Returns:

TypeDescription
ExportResult

A new ExportResult containing all merged content.

Source code in waldiez/exporting/core/result.py
def merge_export_results(*results: ExportResult) -> ExportResult:
    """Merge multiple ExportResult objects into one.

    Parameters
    ----------
    *results : ExportResult
        Variable number of ExportResult objects to merge.

    Returns
    -------
    ExportResult
        A new ExportResult containing all merged content.
    """
    if not results:
        return ExportResult()

    merged = ExportResult()
    for result in results:
        merged.merge_with(result)

    return merged

types

Core dataclasses for the exporting system.

EnvironmentVariable dataclass

EnvironmentVariable(
    name: str,
    value: str,
    description: Optional[str] = None,
    required: bool = True,
)

Environment variable with metadata.

as_tuple

as_tuple() -> tuple[str, str]

Get the environment variable as a tuple.

Returns:

TypeDescription
tuple[str, str]

The environment variable as a tuple.

Source code in waldiez/exporting/core/types.py
def as_tuple(self) -> tuple[str, str]:
    """Get the environment variable as a tuple.

    Returns
    -------
    tuple[str, str]
        The environment variable as a tuple.
    """
    return (self.name, self.value)

ExportConfig dataclass

ExportConfig(
    name: str = "Waldiez Flow",
    description: str = "Make AG2 Agents Collaborate: Drag, Drop, and Orchestrate with Waldiez",
    requirements: list[str] = list[str](),
    tags: list[str] = list[str](),
    output_extension: str = "py",
    is_async: bool = False,
    output_directory: Optional[str | Path] = None,
    uploads_root: Optional[Path] = None,
    cache_seed: Optional[int] = None,
    structured_io: bool = False,
    skip_patch_io: bool = True,
)

Configuration for export operations.

Attributes:

NameTypeDescription
namestr

The name of the export.

descriptionstr

A brief description of the export.

requirementslist[str]

A list of requirements for the export.

tagslist[str]

A list of tags associated with the export.

output_directoryOptional[str | Path]

The directory where the exported content will be saved.

uploads_rootOptional[str | Path]

The root directory for uploads, if applicable.

cache_seedOptional[int]

The seed for caching, if applicable.

structured_iobool

Whether the export should use structured I/O.

output_extensionstr

The file extension for the exported content.

is_asyncbool

Whether the exported content should be asynchronous.

skip_patch_iobool

Whether to skip patching I/O operations.

create classmethod

create(**kwargs: Any) -> ExportConfig

Create a new ExportConfig instance with the provided values.

Parameters:

NameTypeDescriptionDefault
**kwargsAny

Keyword arguments to initialize the ExportConfig.

{}

Returns:

TypeDescription
ExportConfig

A new instance of ExportConfig.

Source code in waldiez/exporting/core/types.py
@classmethod
def create(cls, **kwargs: Any) -> "ExportConfig":
    """Create a new ExportConfig instance with the provided values.

    Parameters
    ----------
    **kwargs : Any
        Keyword arguments to initialize the ExportConfig.

    Returns
    -------
    ExportConfig
        A new instance of ExportConfig.
    """
    valid_fields = {f.name for f in fields(cls)}
    output_extension = kwargs.pop("output_extension", "py")
    for_notebook = kwargs.pop("for_notebook", output_extension == "ipynb")
    if for_notebook is True:
        output_extension = "ipynb"
    cache_seed = kwargs.pop("cache_seed", None)
    if cache_seed is not None and not isinstance(cache_seed, int):
        cache_seed = None
    return cls(
        cache_seed=cache_seed,
        output_extension=output_extension,
        **{k: v for k, v in kwargs.items() if k in valid_fields},
    )

for_notebook property

for_notebook: bool

Check if the export is intended for a notebook environment.

Returns:

TypeDescription
bool

True if the output extension is 'ipynb', otherwise False.

update

update(**kwargs: Any) -> None

Update the export configuration with new values.

Parameters:

NameTypeDescriptionDefault
**kwargsAny

Keyword arguments to update the configuration.

{}

Raises:

TypeDescription
ValueError

If an invalid configuration key is provided.

Source code in waldiez/exporting/core/types.py
def update(self, **kwargs: Any) -> None:
    """Update the export configuration with new values.

    Parameters
    ----------
    **kwargs : Any
        Keyword arguments to update the configuration.

    Raises
    ------
    ValueError
        If an invalid configuration key is provided.
    """
    valid_fields = {f.name for f in fields(self)}
    for key, value in kwargs.items():
        if key in valid_fields:
            setattr(self, key, value)
    if (
        "for_notebook" in kwargs
        and isinstance(kwargs["for_notebook"], bool)
        and "output_extension" not in kwargs
    ):  # pragma: no cover
        self.output_extension = "ipynb" if kwargs["for_notebook"] else "py"

ImportStatement dataclass

ImportStatement(
    statement: str,
    position: ImportPosition = THIRD_PARTY,
    metadata: Optional[dict[str, Any]] = None,
)

Represents an import statement with its position.

InstanceArgument dataclass

InstanceArgument(
    instance_id: str,
    name: str,
    value: Any,
    tabs: int = 0,
    tabs_length: int = 4,
    with_new_line_before: bool = False,
    with_new_line_after: bool = False,
    with_new_line_if_empty: bool = False,
    skip_if_empty_string: bool = True,
    comment: Optional[str] = None,
)

Represents an instance argument for an agent, model or tool.

get_content

get_content(
    prepend_new_line: bool = False,
    append_new_line: bool = False,
) -> str

Get the content representation of the instance argument.

Parameters:

NameTypeDescriptionDefault
prepend_new_linebool

Whether to prepend a new line before the content, by default False.

False
append_new_linebool

Whether to append a new line at the end of the content, by default False.

False

Returns:

TypeDescription
str

The formatted content string for the instance argument.

Source code in waldiez/exporting/core/types.py
def get_content(
    self,
    prepend_new_line: bool = False,
    append_new_line: bool = False,
) -> str:
    """Get the content representation of the instance argument.

    Parameters
    ----------
    prepend_new_line : bool, optional
        Whether to prepend a new line before the content,
        by default False.
    append_new_line : bool, optional
        Whether to append a new line at the end of the content,
        by default False.

    Returns
    -------
    str
        The formatted content string for the instance argument.
    """
    if (
        self.skip_if_empty_string
        and isinstance(self.value, str)
        and not self.value.strip()
    ):
        return "\n" if self.with_new_line_if_empty else ""
    space = " " * (self.tabs * self.tabs_length)
    content = f"{space}{self.name}={self.value}," + (
        f"  # {self.comment}" if self.comment else ""
    )
    if self.with_new_line_before or prepend_new_line:
        content = "\n" + content
    if self.with_new_line_after or append_new_line:
        content += "\n"
    return content

has_content

has_content() -> bool

Check if the instance argument has content.

Returns:

TypeDescription
bool

True if the instance argument has content, otherwise False.

Source code in waldiez/exporting/core/types.py
def has_content(self) -> bool:
    """Check if the instance argument has content.

    Returns
    -------
    bool
        True if the instance argument has content, otherwise False.
    """
    if self.skip_if_empty_string and isinstance(self.value, str):
        return bool(self.value.strip())
    return self.value is not None and self.value != ""

utils

Utility functions for Waldiez exporting.

comment

Get comment string for scripts or notebooks.

get_comment

get_comment(
    comment: str,
    for_notebook: bool = False,
    md_headings: int = 3,
) -> str

Get a comment for the script or notebook.

Parameters:

NameTypeDescriptionDefault
commentstr

The comment to add.

required
for_notebookbool

Whether the comment is for a notebook, by default False

False
md_headingsint

The number of markdown headings to use (if for_notebook is True), by default 2

3

Returns:

TypeDescription
str

The formatted comment.

Source code in waldiez/exporting/core/utils/comment.py
def get_comment(
    comment: str,
    for_notebook: bool = False,
    md_headings: int = 3,
) -> str:
    """Get a comment for the script or notebook.

    Parameters
    ----------
    comment : str
        The comment to add.
    for_notebook : bool, optional
        Whether the comment is for a notebook, by default False
    md_headings : int, optional
        The number of markdown headings to use (if for_notebook is True),
        by default 2

    Returns
    -------
    str
        The formatted comment.
    """
    if for_notebook:
        # For notebooks, we use markdown headings
        heading = "#" + "#" * md_headings
        return f"# %% [markdown]\n{heading} {comment}\n# %% \n"
    # For scripts, we use a simple comment
    return f"# {comment}\n"

get_agent_llm_config_arg

get_agent_llm_config_arg(
    agent: WaldiezAgent,
    all_models: list[WaldiezModel],
    model_names: dict[str, str],
    cache_seed: int | None,
    as_dict: bool = False,
    tabs: int = 1,
) -> str

Get the string representation of the agent's llm config argument.

Parameters:

NameTypeDescriptionDefault
agentWaldiezAgent

The agent.

required
all_modelslist[WaldiezModel]

All the models in the flow.

required
model_namesdict[str, str]

A mapping of model ids to model names.

required
cache_seedOptional[int]

The cache seed.

required
as_dictbool

Whether to return the argument as a dictionary, by default False.

False
tabsint

The number of tabs for indentation, by default 1.

1

Returns:

TypeDescription
str

The agent's llm config argument to use.

Source code in waldiez/exporting/core/utils/llm_config.py
def get_agent_llm_config_arg(
    agent: WaldiezAgent,
    all_models: list[WaldiezModel],
    model_names: dict[str, str],
    cache_seed: int | None,
    as_dict: bool = False,
    tabs: int = 1,
) -> str:
    """Get the string representation of the agent's llm config argument.

    Parameters
    ----------
    agent : WaldiezAgent
        The agent.
    all_models : list[WaldiezModel]
        All the models in the flow.
    model_names : dict[str, str]
        A mapping of model ids to model names.
    cache_seed : Optional[int]
        The cache seed.
    as_dict : bool, optional
        Whether to return the argument as a dictionary, by default False.
    tabs : int, optional
        The number of tabs for indentation, by default 1.

    Returns
    -------
    str
        The agent's llm config argument to use.
    """
    if as_dict is False:
        return _get_agent_llm_config_arg_as_arg(
            agent,
            all_models,
            model_names,
            cache_seed,
            tabs=tabs,
        )
    return _get_agent_llm_config_arg_as_dict(
        agent,
        all_models,
        model_names,
        cache_seed,
        tabs=tabs + 1,
    )

get_comment

get_comment(
    comment: str,
    for_notebook: bool = False,
    md_headings: int = 3,
) -> str

Get a comment for the script or notebook.

Parameters:

NameTypeDescriptionDefault
commentstr

The comment to add.

required
for_notebookbool

Whether the comment is for a notebook, by default False

False
md_headingsint

The number of markdown headings to use (if for_notebook is True), by default 2

3

Returns:

TypeDescription
str

The formatted comment.

Source code in waldiez/exporting/core/utils/comment.py
def get_comment(
    comment: str,
    for_notebook: bool = False,
    md_headings: int = 3,
) -> str:
    """Get a comment for the script or notebook.

    Parameters
    ----------
    comment : str
        The comment to add.
    for_notebook : bool, optional
        Whether the comment is for a notebook, by default False
    md_headings : int, optional
        The number of markdown headings to use (if for_notebook is True),
        by default 2

    Returns
    -------
    str
        The formatted comment.
    """
    if for_notebook:
        # For notebooks, we use markdown headings
        heading = "#" + "#" * md_headings
        return f"# %% [markdown]\n{heading} {comment}\n# %% \n"
    # For scripts, we use a simple comment
    return f"# {comment}\n"

llm_config

LLM config argument utility functions for Waldiez agents.

get_agent_llm_config_arg

get_agent_llm_config_arg(
    agent: WaldiezAgent,
    all_models: list[WaldiezModel],
    model_names: dict[str, str],
    cache_seed: int | None,
    as_dict: bool = False,
    tabs: int = 1,
) -> str

Get the string representation of the agent's llm config argument.

Parameters:

NameTypeDescriptionDefault
agentWaldiezAgent

The agent.

required
all_modelslist[WaldiezModel]

All the models in the flow.

required
model_namesdict[str, str]

A mapping of model ids to model names.

required
cache_seedOptional[int]

The cache seed.

required
as_dictbool

Whether to return the argument as a dictionary, by default False.

False
tabsint

The number of tabs for indentation, by default 1.

1

Returns:

TypeDescription
str

The agent's llm config argument to use.

Source code in waldiez/exporting/core/utils/llm_config.py
def get_agent_llm_config_arg(
    agent: WaldiezAgent,
    all_models: list[WaldiezModel],
    model_names: dict[str, str],
    cache_seed: int | None,
    as_dict: bool = False,
    tabs: int = 1,
) -> str:
    """Get the string representation of the agent's llm config argument.

    Parameters
    ----------
    agent : WaldiezAgent
        The agent.
    all_models : list[WaldiezModel]
        All the models in the flow.
    model_names : dict[str, str]
        A mapping of model ids to model names.
    cache_seed : Optional[int]
        The cache seed.
    as_dict : bool, optional
        Whether to return the argument as a dictionary, by default False.
    tabs : int, optional
        The number of tabs for indentation, by default 1.

    Returns
    -------
    str
        The agent's llm config argument to use.
    """
    if as_dict is False:
        return _get_agent_llm_config_arg_as_arg(
            agent,
            all_models,
            model_names,
            cache_seed,
            tabs=tabs,
        )
    return _get_agent_llm_config_arg_as_dict(
        agent,
        all_models,
        model_names,
        cache_seed,
        tabs=tabs + 1,
    )

validation

Validation types and results for Waldiez exporting core.

ValidationError dataclass

ValidationError(
    message: str,
    severity: str = "error",
    location: Optional[str] = None,
    suggestion: Optional[str] = None,
)

Represents a validation error.

ValidationResult dataclass

ValidationResult(
    is_valid: bool,
    errors: list[ValidationError] = list[ValidationError](),
    warnings: list[ValidationError] = list[
        ValidationError
    ](),
)

Result of validation operations.

add_error

add_error(
    message: str,
    location: Optional[str] = None,
    suggestion: Optional[str] = None,
) -> None

Add a validation error.

Parameters:

NameTypeDescriptionDefault
messagestr

The error message to add.

required
locationOptional[str]

The location in the code where the error occurred, by default None

None
suggestionOptional[str]

A suggestion for fixing the error, by default None

None
Source code in waldiez/exporting/core/validation.py
def add_error(
    self,
    message: str,
    location: Optional[str] = None,
    suggestion: Optional[str] = None,
) -> None:
    """Add a validation error.

    Parameters
    ----------
    message : str
        The error message to add.
    location : Optional[str], optional
        The location in the code where the error occurred, by default None
    suggestion : Optional[str], optional
        A suggestion for fixing the error, by default None
    """
    self.errors.append(
        ValidationError(message, "error", location, suggestion)
    )
    self.is_valid = False

add_warning

add_warning(
    message: str, location: Optional[str] = None
) -> None

Add a validation warning.

Parameters:

NameTypeDescriptionDefault
messagestr

The warning message to add.

required
locationOptional[str]

The location in the code where the warning occurred, by default None

None
Source code in waldiez/exporting/core/validation.py
def add_warning(self, message: str, location: Optional[str] = None) -> None:
    """Add a validation warning.

    Parameters
    ----------
    message : str
        The warning message to add.
    location : Optional[str], optional
        The location in the code where the warning occurred, by default None
    """
    self.warnings.append(ValidationError(message, "warning", location))

has_errors

has_errors() -> bool

Check if there are any errors.

Returns:

TypeDescription
bool

True if there are validation errors, otherwise False.

Source code in waldiez/exporting/core/validation.py
def has_errors(self) -> bool:
    """Check if there are any errors.

    Returns
    -------
    bool
        True if there are validation errors, otherwise False.
    """
    return len(self.errors) > 0

has_warnings

has_warnings() -> bool

Check if there are any warnings.

Returns:

TypeDescription
bool

True if there are validation warnings, otherwise False.

Source code in waldiez/exporting/core/validation.py
def has_warnings(self) -> bool:
    """Check if there are any warnings.

    Returns
    -------
    bool
        True if there are validation warnings, otherwise False.
    """
    return len(self.warnings) > 0

merge

merge(other: ValidationResult) -> None

Merge another ValidationResult into this one.

Parameters:

NameTypeDescriptionDefault
otherValidationResult

The other validation result to merge.

required
Source code in waldiez/exporting/core/validation.py
def merge(self, other: "ValidationResult") -> None:
    """Merge another ValidationResult into this one.

    Parameters
    ----------
    other : ValidationResult
        The other validation result to merge.
    """
    self.is_valid = self.is_valid and other.is_valid
    self.errors.extend(other.errors)
    self.warnings.extend(other.warnings)