Skip to content

Common

Common utils for all models.

WaldiezAgentTarget

Bases: WaldiezBase

Agent target for handoff.

Attributes:

NameTypeDescription
target_typeLiteral['AgentTarget']

The type of the transition target.

valuestr

The agent id to transfer control to.

orderint

The order of the target in the list of targets. If -1, the order is automatically determined by the json data.

WaldiezBase

Bases: BaseModel

Base model class to inherit from.

It contains the default configuration for all models. It also model_dumps by alias by default.

model_dump

model_dump(**kwargs: Any) -> dict[str, Any]

Dump the model to a dictionary.

Parameters:

NameTypeDescriptionDefault
**kwargsAny

Additional keyword arguments.

The following are from the Pydantic model_dump method: - mode: str | Literal['json', 'python'] = 'json', - include: IncEx | None - exclude: IncEx | None - context: Any | None - by_alias: bool | None (None defaults to True) - exclude_unset: bool = False - exclude_defaults: bool = False - exclude_none: bool = False - round_trip: bool = False - warnings: bool | Literal['none', 'warn', 'error'] = True - fallback: ((Any) -> Any) | None = None - serialize_as_any: bool = False

{}

Returns:

TypeDescription
dict[str, Any]

The dictionary representation of the model.

Source code in waldiez/models/common/base.py
def model_dump(self, **kwargs: Any) -> dict[str, Any]:
    """Dump the model to a dictionary.

    Parameters
    ----------
    **kwargs : Any
        Additional keyword arguments.

        The following are from the Pydantic `model_dump` method:
          - mode: str | Literal['json', 'python'] = 'json',
          - include: IncEx | None
          - exclude: IncEx | None
          - context: Any | None
          - by_alias: bool | None (None defaults to True)
          - exclude_unset: bool = False
          - exclude_defaults: bool = False
          - exclude_none: bool = False
          - round_trip: bool = False
          - warnings: bool | Literal['none', 'warn', 'error'] = True
          - fallback: ((Any) -> Any) | None = None
          - serialize_as_any: bool = False

    Returns
    -------
    dict[str, Any]
        The dictionary representation of the model.
    """
    by_alias = kwargs.pop("by_alias", None)
    mode = kwargs.pop("mode", None)
    if mode is None:  # pragma: no branch
        mode = "json"
    if by_alias is None:  # pragma: no branch
        by_alias = True
    if not isinstance(by_alias, bool):
        by_alias = True
    return super().model_dump(by_alias=by_alias, mode=mode, **kwargs)

model_dump_json

model_dump_json(**kwargs: Any) -> str

Dump the model to a JSON string.

Parameters:

NameTypeDescriptionDefault
**kwargsAny

Additional keyword arguments.

The following are from the Pydantic model_dump_json method: - indent: int | None = None, - include: IncEx | None = None, - exclude: IncEx | None = None, - context: Any | None = None, - by_alias: bool | None = None, (None defaults to True) - exclude_unset: bool = False, - exclude_defaults: bool = False, - exclude_none: bool = False, - round_trip: bool = False, - warnings: bool | Literal['none', 'warn', 'error'] = True, - fallback: ((Any) -> Any) | None = None, - serialize_as_any: bool = False

{}

Returns:

TypeDescription
str

The JSON string.

Source code in waldiez/models/common/base.py
def model_dump_json(self, **kwargs: Any) -> str:
    """Dump the model to a JSON string.

    Parameters
    ----------
    **kwargs : Any
        Additional keyword arguments.

        The following are from the Pydantic `model_dump_json` method:
        - indent: int | None = None,
        - include: IncEx | None = None,
        - exclude: IncEx | None = None,
        - context: Any | None = None,
        - by_alias: bool | None = None, (None defaults to True)
        - exclude_unset: bool = False,
        - exclude_defaults: bool = False,
        - exclude_none: bool = False,
        - round_trip: bool = False,
        - warnings: bool | Literal['none', 'warn', 'error'] = True,
        - fallback: ((Any) -> Any) | None = None,
        - serialize_as_any: bool = False

    Returns
    -------
    str
        The JSON string.
    """
    by_alias = kwargs.pop("by_alias", None)
    if by_alias is None:
        by_alias = True
    if not isinstance(by_alias, bool):
        by_alias = True
    return super().model_dump_json(by_alias=by_alias, **kwargs)

WaldiezContextBasedTransition

Bases: WaldiezBase

Condition wrapper for context conditions.

WaldiezContextStrLLMCondition

Bases: WaldiezBase

Context variable-based LLM condition.

is_empty

is_empty() -> bool

Check if the condition is empty.

Returns:

TypeDescription
bool

True if the condition has an empty context string, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the condition is empty.

    Returns
    -------
    bool
        True if the condition has an empty context string,
        False otherwise.
    """
    return not self.is_not_empty()

is_not_empty

is_not_empty() -> bool

Check if the condition is not empty.

Returns:

TypeDescription
bool

True if the condition has a non-empty context string, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the condition is not empty.

    Returns
    -------
    bool
        True if the condition has a non-empty context string,
        False otherwise.
    """
    return bool(self.context_str.strip()) or bool(self.data)

WaldiezDefaultCondition

Get the default condition for handoff transitions.

create classmethod

create() -> WaldiezHandoffCondition

Get the default condition for handoff transitions.

Returns:

TypeDescription
WaldiezStringLLMCondition

A default LLM condition with empty prompt and data.

Source code in waldiez/models/common/handoff.py
@classmethod
def create(cls) -> WaldiezHandoffCondition:
    """Get the default condition for handoff transitions.

    Returns
    -------
    WaldiezStringLLMCondition
        A default LLM condition with empty prompt and data.
    """
    return WaldiezStringLLMCondition(
        condition_type="string_llm",
        prompt="",
        data={},
    )

WaldiezExpressionContextCondition

Bases: WaldiezBase

Expression-based context condition.

is_empty

is_empty() -> bool

Check if the condition is empty.

Returns:

TypeDescription
bool

True if the condition has an empty expression, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the condition is empty.

    Returns
    -------
    bool
        True if the condition has an empty expression,
        False otherwise.
    """
    return not self.is_not_empty()

is_not_empty

is_not_empty() -> bool

Check if the condition is not empty.

Returns:

TypeDescription
bool

True if the condition has a non-empty expression, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the condition is not empty.

    Returns
    -------
    bool
        True if the condition has a non-empty expression,
        False otherwise.
    """
    return bool(self.expression.strip()) or bool(self.data)

WaldiezGroupOrNestedTarget

Bases: WaldiezBase

Group or nested chat target for handoff.

Attributes:

NameTypeDescription
target_typeLiteral['GroupChatTarget', 'NestedChatTarget']

The type of the transition target.

valuestr

The id of the group or nested chat to transfer control to.

orderint

The order of the target in the list of targets.

WaldiezHandoff

Bases: WaldiezBase

Handoff class for Waldiez agents and chats.

is_context_based

is_context_based() -> bool

Check if the handoff is context-based.

Returns:

TypeDescription
bool

True if the handoff condition is context-based, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_context_based(self) -> bool:
    """Check if the handoff is context-based.

    Returns
    -------
    bool
        True if the handoff condition is context-based,
        False otherwise.
    """
    return self.condition.condition_type in {
        "string_context",
        "expression_context",
    }

is_empty

is_empty() -> bool

Check if the handoff is empty.

Returns:

TypeDescription
bool

True if the handoff has an empty target, condition, and availability, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the handoff is empty.

    Returns
    -------
    bool
        True if the handoff has an empty target,
        condition, and availability, False otherwise.
    """
    return not self.is_not_empty()

is_llm_based

is_llm_based() -> bool

Check if the handoff is LLM-based.

Returns:

TypeDescription
bool

True if the handoff condition is LLM-based, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_llm_based(self) -> bool:
    """Check if the handoff is LLM-based.

    Returns
    -------
    bool
        True if the handoff condition is LLM-based,
        False otherwise.
    """
    return self.condition.condition_type in {
        "string_llm",
        "context_str_llm",
    }

is_not_empty

is_not_empty() -> bool

Check if the handoff is not empty.

Returns:

TypeDescription
bool

True if the handoff has a non-empty target, condition, or availability, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the handoff is not empty.

    Returns
    -------
    bool
        True if the handoff has a non-empty target,
        condition, or availability, False otherwise.
    """
    return self.condition.is_not_empty() or self.available.type != "none"

WaldiezLLMBasedTransition

Bases: WaldiezBase

Condition wrapper for LLM conditions.

WaldiezRandomAgentTarget

Bases: WaldiezBase

Random agent target for handoff.

Attributes:

NameTypeDescription
target_typeLiteral['RandomAgentTarget']

The type of the transition target.

valuelist[str]

A list of agent ids to randomly select from.

orderint

The order of the target in the list of targets. If -1, the order is automatically determined by the json data.

WaldiezSimpleTarget

Bases: WaldiezBase

Simple target for handoff.

Attributes:

NameTypeDescription
target_typeLiteral[

"AskUserTarget", "GroupManagerTarget", "RevertToUserTarget", "StayTarget", "TerminateTarget"

]

The type of the transition target.

orderint

The order of the target in the list of targets. If -1, the order is automatically determined by the json data.

targetstr

The id of the group or nested chat to transfer control to.

WaldiezStringContextCondition

Bases: WaldiezBase

String-based context condition.

is_empty

is_empty() -> bool

Check if the condition is empty.

Returns:

TypeDescription
bool

True if the condition has an empty variable name, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the condition is empty.

    Returns
    -------
    bool
        True if the condition has an empty variable name,
        False otherwise.
    """
    return not self.is_not_empty()

is_not_empty

is_not_empty() -> bool

Check if the condition is not empty.

Returns:

TypeDescription
bool

True if the condition has a non-empty variable name, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the condition is not empty.

    Returns
    -------
    bool
        True if the condition has a non-empty variable name,
        False otherwise.
    """
    return bool(self.variable_name.strip())

WaldiezStringLLMCondition

Bases: WaldiezBase

String-based LLM condition.

is_empty

is_empty() -> bool

Check if the condition is empty.

Returns:

TypeDescription
bool

True if the condition has an empty prompt, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the condition is empty.

    Returns
    -------
    bool
        True if the condition has an empty prompt,
        False otherwise.
    """
    return not self.is_not_empty()

is_not_empty

is_not_empty() -> bool

Check if the condition is not empty.

Returns:

TypeDescription
bool

True if the condition has a non-empty prompt, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the condition is not empty.

    Returns
    -------
    bool
        True if the condition has a non-empty prompt,
        False otherwise.
    """
    return bool(self.prompt.strip()) or bool(self.data)

WaldiezTransitionAvailability

Bases: WaldiezBase

Availability condition for transitions.

Attributes:

NameTypeDescription
availablebool

Whether the transition is available.

datadict[str, Any]

Additional data for the availability condition.

ag2_version

Get the autogen version.

get_autogen_version cached

get_autogen_version() -> str

Get the autogen version.

Returns:

TypeDescription
str

The autogen version.

Raises:

TypeDescription
ValueError

If ag2 is not installed.

Source code in waldiez/models/common/ag2_version.py
@cache
def get_autogen_version() -> str:
    """Get the autogen version.

    Returns
    -------
    str
        The autogen version.

    Raises
    ------
    ValueError
        If ag2 is not installed.
    """
    # pylint: disable=import-outside-toplevel
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        try:
            from autogen.version import __version__ as ag2  # type: ignore
        except ImportError as error:  # pragma: no cover
            raise ValueError("ag2 is not installed.") from error
        return ag2

base

Base class to inherit from.

WaldiezBase

Bases: BaseModel

Base model class to inherit from.

It contains the default configuration for all models. It also model_dumps by alias by default.

model_dump

model_dump(**kwargs: Any) -> dict[str, Any]

Dump the model to a dictionary.

Parameters:

NameTypeDescriptionDefault
**kwargsAny

Additional keyword arguments.

The following are from the Pydantic model_dump method: - mode: str | Literal['json', 'python'] = 'json', - include: IncEx | None - exclude: IncEx | None - context: Any | None - by_alias: bool | None (None defaults to True) - exclude_unset: bool = False - exclude_defaults: bool = False - exclude_none: bool = False - round_trip: bool = False - warnings: bool | Literal['none', 'warn', 'error'] = True - fallback: ((Any) -> Any) | None = None - serialize_as_any: bool = False

{}

Returns:

TypeDescription
dict[str, Any]

The dictionary representation of the model.

Source code in waldiez/models/common/base.py
def model_dump(self, **kwargs: Any) -> dict[str, Any]:
    """Dump the model to a dictionary.

    Parameters
    ----------
    **kwargs : Any
        Additional keyword arguments.

        The following are from the Pydantic `model_dump` method:
          - mode: str | Literal['json', 'python'] = 'json',
          - include: IncEx | None
          - exclude: IncEx | None
          - context: Any | None
          - by_alias: bool | None (None defaults to True)
          - exclude_unset: bool = False
          - exclude_defaults: bool = False
          - exclude_none: bool = False
          - round_trip: bool = False
          - warnings: bool | Literal['none', 'warn', 'error'] = True
          - fallback: ((Any) -> Any) | None = None
          - serialize_as_any: bool = False

    Returns
    -------
    dict[str, Any]
        The dictionary representation of the model.
    """
    by_alias = kwargs.pop("by_alias", None)
    mode = kwargs.pop("mode", None)
    if mode is None:  # pragma: no branch
        mode = "json"
    if by_alias is None:  # pragma: no branch
        by_alias = True
    if not isinstance(by_alias, bool):
        by_alias = True
    return super().model_dump(by_alias=by_alias, mode=mode, **kwargs)

model_dump_json

model_dump_json(**kwargs: Any) -> str

Dump the model to a JSON string.

Parameters:

NameTypeDescriptionDefault
**kwargsAny

Additional keyword arguments.

The following are from the Pydantic model_dump_json method: - indent: int | None = None, - include: IncEx | None = None, - exclude: IncEx | None = None, - context: Any | None = None, - by_alias: bool | None = None, (None defaults to True) - exclude_unset: bool = False, - exclude_defaults: bool = False, - exclude_none: bool = False, - round_trip: bool = False, - warnings: bool | Literal['none', 'warn', 'error'] = True, - fallback: ((Any) -> Any) | None = None, - serialize_as_any: bool = False

{}

Returns:

TypeDescription
str

The JSON string.

Source code in waldiez/models/common/base.py
def model_dump_json(self, **kwargs: Any) -> str:
    """Dump the model to a JSON string.

    Parameters
    ----------
    **kwargs : Any
        Additional keyword arguments.

        The following are from the Pydantic `model_dump_json` method:
        - indent: int | None = None,
        - include: IncEx | None = None,
        - exclude: IncEx | None = None,
        - context: Any | None = None,
        - by_alias: bool | None = None, (None defaults to True)
        - exclude_unset: bool = False,
        - exclude_defaults: bool = False,
        - exclude_none: bool = False,
        - round_trip: bool = False,
        - warnings: bool | Literal['none', 'warn', 'error'] = True,
        - fallback: ((Any) -> Any) | None = None,
        - serialize_as_any: bool = False

    Returns
    -------
    str
        The JSON string.
    """
    by_alias = kwargs.pop("by_alias", None)
    if by_alias is None:
        by_alias = True
    if not isinstance(by_alias, bool):
        by_alias = True
    return super().model_dump_json(by_alias=by_alias, **kwargs)

check_function

check_function(
    code_string: str,
    function_name: str,
    function_args: list[str],
) -> tuple[bool, str]

Check the function.

Parameters:

NameTypeDescriptionDefault
code_stringstr

The code string to check.

required
function_namestr

The expected method name.

required
function_argslist[str]

The expected method arguments.

required

Returns:

TypeDescription
tuple[bool, str]

If valid, True and the function body (only), no extra lines. If invalid, False and the error message.

Source code in waldiez/models/common/method_utils.py
def check_function(
    code_string: str,
    function_name: str,
    function_args: list[str],
) -> tuple[bool, str]:
    """Check the function.

    Parameters
    ----------
    code_string : str
        The code string to check.
    function_name : str
        The expected method name.
    function_args : list[str]
        The expected method arguments.

    Returns
    -------
    tuple[bool, str]
        If valid, True and the function body (only), no extra lines.
        If invalid, False and the error message.
    """
    error, tree = parse_code_string(code_string)
    if error is not None or tree is None:
        return False, error or "Invalid code"
    return _validate_function_body(
        tree,
        code_string,
        function_name,
        function_args,
    )

date_utils

Date utilities.

now

now() -> str

Get the current date and time in UTC.

Returns:

TypeDescription
str

The current date and time in UTC.

Source code in waldiez/models/common/date_utils.py
def now() -> str:
    """Get the current date and time in UTC.

    Returns
    -------
    str
        The current date and time in UTC.
    """
    return (
        datetime.now(tz=timezone.utc)
        .isoformat(timespec="milliseconds")
        .replace("+00:00", "Z")
    )

dict_utils

Dictionary related utilities.

update_dict

update_dict(original: dict[str, Any]) -> dict[str, Any]

Try to determine the type of the dictionary values.

Parameters:

NameTypeDescriptionDefault
originaldict[str, Any]

The original dictionary.

required

Returns:

TypeDescription
dict[str, Any]

The updated dictionary with values converted to the detected types.

Source code in waldiez/models/common/dict_utils.py
def update_dict(original: dict[str, Any]) -> dict[str, Any]:
    """
    Try to determine the type of the dictionary values.

    Parameters
    ----------
    original : dict[str, Any]
        The original dictionary.

    Returns
    -------
    dict[str, Any]
        The updated dictionary with values converted to the detected types.
    """
    new_dict: dict[str, Any] = {}

    for key, value in original.items():
        # Skip conversion if already the desired type
        if not isinstance(value, str):
            new_dict[key] = value
            continue

        value_stripped = value.strip()
        if (
            value_stripped.startswith('"') and value_stripped.endswith('"')
        ) or (value_stripped.startswith("'") and value_stripped.endswith("'")):
            value_stripped = value_stripped[1:-1]
        if not value_stripped:  # Empty or whitespace-only
            new_dict[key] = value
            continue

        value_lower = value_stripped.lower()

        # Check for None/null
        if value_lower in NULL_VALUES:
            new_dict[key] = None
        # Check for boolean
        elif value_lower in BOOL_VALUES:
            new_dict[key] = value_lower == "true"
        # Check for integer
        elif re.fullmatch(r"[-+]?\d+", value_stripped):
            new_dict[key] = int(value_stripped)
        # Check for float
        else:
            try:
                # This handles floats, scientific notation, etc.
                float_val = float(value_stripped)
                new_dict[key] = float_val
            except ValueError:
                # Keep as string if conversion fails
                new_dict[key] = value_stripped

    return new_dict

gather_code_imports

gather_code_imports(
    code_string: str, is_interop: bool
) -> tuple[list[str], list[str]]

Gather the imports from the code string.

Parameters:

NameTypeDescriptionDefault
code_stringstr

The code string.

required
is_interopbool

If True, make sure the interoperability import is present.

required

Returns:

TypeDescription
tuple[list[str], list[str]]

The standard library imports and the third party imports.

Source code in waldiez/models/common/method_utils.py
def gather_code_imports(
    code_string: str,
    is_interop: bool,
) -> tuple[list[str], list[str]]:
    """Gather the imports from the code string.

    Parameters
    ----------
    code_string : str
        The code string.
    is_interop : bool
        If True, make sure the interoperability import is present.

    Returns
    -------
    tuple[list[str], list[str]]
        The standard library imports and the third party imports.
    """
    standard_lib_imports, third_party_imports = _extract_imports_from_ast(
        code_string
    )

    if is_interop and (
        "from autogen.interop import Interoperability"
        not in third_party_imports
    ):
        third_party_imports.append(
            "from autogen.interop import Interoperability"
        )

    sorted_standard_lib_imports = _sort_imports(standard_lib_imports)
    sorted_third_party_imports = _sort_imports(third_party_imports)

    return sorted_standard_lib_imports, sorted_third_party_imports

generate_function

generate_function(
    function_name: str,
    function_args: list[str],
    function_types: tuple[list[str], str],
    function_body: str,
    types_as_comments: bool = False,
) -> str

Generate a function.

Parameters:

NameTypeDescriptionDefault
function_namestr

The function name.

required
function_argslist[str]

The function arguments.

required
function_typestuple[list[str], str]

The function types.

required
function_bodystr

The function body.

required
types_as_commentsbool

Include the type hints as comments (or in the function signature) (default is False).

False

Returns:

TypeDescription
str

The generated function.

Source code in waldiez/models/common/method_utils.py
def generate_function(
    function_name: str,
    function_args: list[str],
    function_types: tuple[list[str], str],
    function_body: str,
    types_as_comments: bool = False,
) -> str:
    """Generate a function.

    Parameters
    ----------
    function_name : str
        The function name.
    function_args : list[str]
        The function arguments.
    function_types : tuple[list[str], str]
        The function types.
    function_body : str
        The function body.
    types_as_comments : bool, optional
        Include the type hints as comments (or in the function signature)
        (default is False).

    Returns
    -------
    str
        The generated function.
    """
    if len(function_name) > MAX_VAR_NAME_LENGTH:
        function_name = function_name[:MAX_VAR_NAME_LENGTH]
    function_string = f"def {function_name}("
    if not function_args:
        function_string += ")"
    else:
        function_string += "\n"
        for arg, arg_type in zip(
            function_args, function_types[0], strict=False
        ):
            if types_as_comments:
                function_string += f"    {arg},  # type: {arg_type}" + "\n"
            else:
                function_string += f"    {arg}: {arg_type}," + "\n"
        function_string += ")"
    if types_as_comments:
        function_string += ":\n"
        function_string += "    # type: (...) -> " + function_types[1]
    else:
        function_string += " -> " + function_types[1] + ":"
    function_string += "\n" if not function_body.startswith("\n") else ""
    function_string += f"{function_body}"
    if not function_string.endswith("\n"):  # pragma: no branch
        function_string += "\n"
    return function_string

get_autogen_version cached

get_autogen_version() -> str

Get the autogen version.

Returns:

TypeDescription
str

The autogen version.

Raises:

TypeDescription
ValueError

If ag2 is not installed.

Source code in waldiez/models/common/ag2_version.py
@cache
def get_autogen_version() -> str:
    """Get the autogen version.

    Returns
    -------
    str
        The autogen version.

    Raises
    ------
    ValueError
        If ag2 is not installed.
    """
    # pylint: disable=import-outside-toplevel
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        try:
            from autogen.version import __version__ as ag2  # type: ignore
        except ImportError as error:  # pragma: no cover
            raise ValueError("ag2 is not installed.") from error
        return ag2

get_function

get_function(code_string: str, function_name: str) -> str

Get the function signature and body.

Parameters:

NameTypeDescriptionDefault
code_stringstr

The code string.

required
function_namestr

The function name.

required

Returns:

TypeDescription
str

The function signature and body.

Source code in waldiez/models/common/method_utils.py
def get_function(
    code_string: str,
    function_name: str,
) -> str:
    """Get the function signature and body.

    Parameters
    ----------
    code_string : str
        The code string.
    function_name : str
        The function name.

    Returns
    -------
    str
        The function signature and body.
    """
    tree = parso.parse(code_string)  # type: ignore
    for node in tree.iter_funcdefs():
        if node.name.value == function_name:
            return node.get_code()
    return ""

get_id

get_id() -> str

Generate a unique ID.

Returns:

TypeDescription
str

The unique ID.

Source code in waldiez/models/common/id_generator.py
def get_id() -> str:
    """Generate a unique ID.

    Returns
    -------
    str
        The unique ID.
    """
    now_td = datetime.now(timezone.utc)
    now_str = now_td.strftime("%Y%m%d%H%M%S%f")
    return f"{now_str}-{uuid.uuid4().hex}"

get_valid_instance_name

get_valid_instance_name(
    instance: tuple[str, str],
    current_names: dict[str, str],
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> dict[str, str]

Get a valid instance name.

If the instance id is already in the current names nothing is done. If the name already exists in the current names, the name is updated (with an index suffix).

Parameters:

NameTypeDescriptionDefault
instancetuple[str, str]

The instance id and possible name.

required
current_namesdict[str, str]

The current names.

required
prefixstr

The prefix to use if the name starts with a digit, if the name is already in the current names, or if the name is already in the current names with an index suffix.

'w'
max_lengthint

The maximum length of the variable name.

MAX_VARIABLE_LENGTH

Returns:

TypeDescription
dict[str, str]

The updated names.

Source code in waldiez/models/common/naming.py
def get_valid_instance_name(
    instance: tuple[str, str],
    current_names: dict[str, str],
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> dict[str, str]:
    """Get a valid instance name.

    If the instance id is already in the current names nothing is done.
    If the name already exists in the current names,
        the name is updated (with an index suffix).

    Parameters
    ----------
    instance : tuple[str, str]
        The instance id and possible name.
    current_names : dict[str, str]
        The current names.
    prefix : str, optional
        The prefix to use if the name starts with a digit,
        if the name is already in the current names,
        or if the name is already in the current names with an index suffix.
    max_length : int, optional
        The maximum length of the variable name.

    Returns
    -------
    dict[str, str]
        The updated names.
    """
    instance_id, possible_name = instance[0], instance[1][:max_length]

    if instance_id in current_names:
        # already in the current names (by its id)
        return current_names

    new_names = current_names.copy()
    name = get_valid_python_variable_name(
        possible_name, prefix=prefix, max_length=max_length
    )

    if name in current_names.values():
        name = f"{prefix}_{name}"

    if name in current_names.values():
        index = 1
        while f"{name}_{index}" in current_names.values():
            index += 1
        name = f"{name}_{index}"

    new_names[instance_id] = name
    return new_names

get_valid_python_variable_name

get_valid_python_variable_name(
    possible: str,
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> str

Get a valid Python variable name from a possible name.

Parameters:

NameTypeDescriptionDefault
possiblestr

The possible name.

required
prefixstr

The prefix to use if the name starts with a digit or special character

'w'
max_lengthint

The maximum length of the variable name.

MAX_VARIABLE_LENGTH

Returns:

TypeDescription
str

The valid Python variable name.

Source code in waldiez/models/common/naming.py
def get_valid_python_variable_name(
    possible: str,
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> str:
    """Get a valid Python variable name from a possible name.

    Parameters
    ----------
    possible : str
        The possible name.
    prefix : str, optional
        The prefix to use if the name starts with a digit or special character
    max_length : int, optional
        The maximum length of the variable name.

    Returns
    -------
    str
        The valid Python variable name.
    """
    if not possible or not possible.strip():
        return prefix + "_"

    # First handle arrow operators specifically
    possible = possible.replace("->", "to")
    possible = possible.replace("=>", "to")
    possible = possible.replace("<-", "from")
    possible = possible.replace("<=", "from")

    # Replace non-ASCII characters and non-word characters with underscores
    # \W matches any non-word character, but in Python's re module,
    # \w includes Unicode letters by default, so we need to be more explicit
    # to replace Unicode letters with underscores for valid Python identifiers
    possible = re.sub(r"[^\w]", "_", possible)  # Replace non-word chars
    possible = re.sub(r"[^\x00-\x7F]", "_", possible)  # Replace non-ASCII chars

    # Convert to lowercase and truncate
    possible = possible.lower()[:max_length]

    # Remove trailing underscores from truncation
    possible = possible.rstrip("_")

    if not possible:
        return prefix + "_"

    # Handle names starting with underscore
    if possible.startswith("_"):
        return f"{prefix}{possible}"

    # Handle names starting with digit
    if possible[0].isdigit():
        return f"{prefix}_{possible}"

    return possible

get_waldiez_version

get_waldiez_version() -> str

Read the version from the version file.

Returns:

TypeDescription
str

The version.

Source code in waldiez/models/common/waldiez_version.py
def get_waldiez_version() -> (
    str
):  # pragma: no cover  # depends on file existence
    """Read the version from the version file.

    Returns
    -------
    str
        The version.
    """
    here = Path(__file__).parent  # waldiez/models/common
    package_dir = here.parent.parent  # waldiez/models -> waldiez
    version_file = package_dir / "_version.py"
    if not version_file.exists():
        return "0.0.0"  # dev / ignored
    with version_file.open() as f:
        for line in f:
            if line.startswith("__version__"):
                version = line.split("=")[1].strip().strip('"').strip("'")
                # send version without "v" prefix
                if version.startswith("v"):
                    version = version[1:]
                # make sure it is a valid semver
                if not version or not all(
                    part.isdigit() for part in version.split(".")
                ):
                    return "0.0.0"
                return version
    return "0.0.0"  # fallback if not found

handoff

Waldiez Agent Handoff class.

WaldiezAgentTarget

Bases: WaldiezBase

Agent target for handoff.

Attributes:

NameTypeDescription
target_typeLiteral['AgentTarget']

The type of the transition target.

valuestr

The agent id to transfer control to.

orderint

The order of the target in the list of targets. If -1, the order is automatically determined by the json data.

WaldiezContextBasedTransition

Bases: WaldiezBase

Condition wrapper for context conditions.

WaldiezContextStrLLMCondition

Bases: WaldiezBase

Context variable-based LLM condition.

is_empty

is_empty() -> bool

Check if the condition is empty.

Returns:

TypeDescription
bool

True if the condition has an empty context string, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the condition is empty.

    Returns
    -------
    bool
        True if the condition has an empty context string,
        False otherwise.
    """
    return not self.is_not_empty()

is_not_empty

is_not_empty() -> bool

Check if the condition is not empty.

Returns:

TypeDescription
bool

True if the condition has a non-empty context string, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the condition is not empty.

    Returns
    -------
    bool
        True if the condition has a non-empty context string,
        False otherwise.
    """
    return bool(self.context_str.strip()) or bool(self.data)

WaldiezExpressionContextCondition

Bases: WaldiezBase

Expression-based context condition.

is_empty

is_empty() -> bool

Check if the condition is empty.

Returns:

TypeDescription
bool

True if the condition has an empty expression, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the condition is empty.

    Returns
    -------
    bool
        True if the condition has an empty expression,
        False otherwise.
    """
    return not self.is_not_empty()

is_not_empty

is_not_empty() -> bool

Check if the condition is not empty.

Returns:

TypeDescription
bool

True if the condition has a non-empty expression, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the condition is not empty.

    Returns
    -------
    bool
        True if the condition has a non-empty expression,
        False otherwise.
    """
    return bool(self.expression.strip()) or bool(self.data)

WaldiezGroupOrNestedTarget

Bases: WaldiezBase

Group or nested chat target for handoff.

Attributes:

NameTypeDescription
target_typeLiteral['GroupChatTarget', 'NestedChatTarget']

The type of the transition target.

valuestr

The id of the group or nested chat to transfer control to.

orderint

The order of the target in the list of targets.

WaldiezHandoff

Bases: WaldiezBase

Handoff class for Waldiez agents and chats.

is_context_based

is_context_based() -> bool

Check if the handoff is context-based.

Returns:

TypeDescription
bool

True if the handoff condition is context-based, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_context_based(self) -> bool:
    """Check if the handoff is context-based.

    Returns
    -------
    bool
        True if the handoff condition is context-based,
        False otherwise.
    """
    return self.condition.condition_type in {
        "string_context",
        "expression_context",
    }

is_empty

is_empty() -> bool

Check if the handoff is empty.

Returns:

TypeDescription
bool

True if the handoff has an empty target, condition, and availability, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the handoff is empty.

    Returns
    -------
    bool
        True if the handoff has an empty target,
        condition, and availability, False otherwise.
    """
    return not self.is_not_empty()

is_llm_based

is_llm_based() -> bool

Check if the handoff is LLM-based.

Returns:

TypeDescription
bool

True if the handoff condition is LLM-based, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_llm_based(self) -> bool:
    """Check if the handoff is LLM-based.

    Returns
    -------
    bool
        True if the handoff condition is LLM-based,
        False otherwise.
    """
    return self.condition.condition_type in {
        "string_llm",
        "context_str_llm",
    }

is_not_empty

is_not_empty() -> bool

Check if the handoff is not empty.

Returns:

TypeDescription
bool

True if the handoff has a non-empty target, condition, or availability, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the handoff is not empty.

    Returns
    -------
    bool
        True if the handoff has a non-empty target,
        condition, or availability, False otherwise.
    """
    return self.condition.is_not_empty() or self.available.type != "none"

WaldiezLLMBasedTransition

Bases: WaldiezBase

Condition wrapper for LLM conditions.

WaldiezRandomAgentTarget

Bases: WaldiezBase

Random agent target for handoff.

Attributes:

NameTypeDescription
target_typeLiteral['RandomAgentTarget']

The type of the transition target.

valuelist[str]

A list of agent ids to randomly select from.

orderint

The order of the target in the list of targets. If -1, the order is automatically determined by the json data.

WaldiezSimpleTarget

Bases: WaldiezBase

Simple target for handoff.

Attributes:

NameTypeDescription
target_typeLiteral[

"AskUserTarget", "GroupManagerTarget", "RevertToUserTarget", "StayTarget", "TerminateTarget"

]

The type of the transition target.

orderint

The order of the target in the list of targets. If -1, the order is automatically determined by the json data.

targetstr

The id of the group or nested chat to transfer control to.

WaldiezStringContextCondition

Bases: WaldiezBase

String-based context condition.

is_empty

is_empty() -> bool

Check if the condition is empty.

Returns:

TypeDescription
bool

True if the condition has an empty variable name, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the condition is empty.

    Returns
    -------
    bool
        True if the condition has an empty variable name,
        False otherwise.
    """
    return not self.is_not_empty()

is_not_empty

is_not_empty() -> bool

Check if the condition is not empty.

Returns:

TypeDescription
bool

True if the condition has a non-empty variable name, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the condition is not empty.

    Returns
    -------
    bool
        True if the condition has a non-empty variable name,
        False otherwise.
    """
    return bool(self.variable_name.strip())

WaldiezStringLLMCondition

Bases: WaldiezBase

String-based LLM condition.

is_empty

is_empty() -> bool

Check if the condition is empty.

Returns:

TypeDescription
bool

True if the condition has an empty prompt, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_empty(self) -> bool:
    """Check if the condition is empty.

    Returns
    -------
    bool
        True if the condition has an empty prompt,
        False otherwise.
    """
    return not self.is_not_empty()

is_not_empty

is_not_empty() -> bool

Check if the condition is not empty.

Returns:

TypeDescription
bool

True if the condition has a non-empty prompt, False otherwise.

Source code in waldiez/models/common/handoff.py
def is_not_empty(self) -> bool:
    """Check if the condition is not empty.

    Returns
    -------
    bool
        True if the condition has a non-empty prompt,
        False otherwise.
    """
    return bool(self.prompt.strip()) or bool(self.data)

WaldiezTransitionAvailability

Bases: WaldiezBase

Availability condition for transitions.

Attributes:

NameTypeDescription
availablebool

Whether the transition is available.

datadict[str, Any]

Additional data for the availability condition.

id_generator

Generate a unique ID.

get_id

get_id() -> str

Generate a unique ID.

Returns:

TypeDescription
str

The unique ID.

Source code in waldiez/models/common/id_generator.py
def get_id() -> str:
    """Generate a unique ID.

    Returns
    -------
    str
        The unique ID.
    """
    now_td = datetime.now(timezone.utc)
    now_str = now_td.strftime("%Y%m%d%H%M%S%f")
    return f"{now_str}-{uuid.uuid4().hex}"

method_utils

Function related utilities.

ParseResult

Bases: NamedTuple

Result of parsing a code string.

check_function

check_function(
    code_string: str,
    function_name: str,
    function_args: list[str],
) -> tuple[bool, str]

Check the function.

Parameters:

NameTypeDescriptionDefault
code_stringstr

The code string to check.

required
function_namestr

The expected method name.

required
function_argslist[str]

The expected method arguments.

required

Returns:

TypeDescription
tuple[bool, str]

If valid, True and the function body (only), no extra lines. If invalid, False and the error message.

Source code in waldiez/models/common/method_utils.py
def check_function(
    code_string: str,
    function_name: str,
    function_args: list[str],
) -> tuple[bool, str]:
    """Check the function.

    Parameters
    ----------
    code_string : str
        The code string to check.
    function_name : str
        The expected method name.
    function_args : list[str]
        The expected method arguments.

    Returns
    -------
    tuple[bool, str]
        If valid, True and the function body (only), no extra lines.
        If invalid, False and the error message.
    """
    error, tree = parse_code_string(code_string)
    if error is not None or tree is None:
        return False, error or "Invalid code"
    return _validate_function_body(
        tree,
        code_string,
        function_name,
        function_args,
    )

gather_code_imports

gather_code_imports(
    code_string: str, is_interop: bool
) -> tuple[list[str], list[str]]

Gather the imports from the code string.

Parameters:

NameTypeDescriptionDefault
code_stringstr

The code string.

required
is_interopbool

If True, make sure the interoperability import is present.

required

Returns:

TypeDescription
tuple[list[str], list[str]]

The standard library imports and the third party imports.

Source code in waldiez/models/common/method_utils.py
def gather_code_imports(
    code_string: str,
    is_interop: bool,
) -> tuple[list[str], list[str]]:
    """Gather the imports from the code string.

    Parameters
    ----------
    code_string : str
        The code string.
    is_interop : bool
        If True, make sure the interoperability import is present.

    Returns
    -------
    tuple[list[str], list[str]]
        The standard library imports and the third party imports.
    """
    standard_lib_imports, third_party_imports = _extract_imports_from_ast(
        code_string
    )

    if is_interop and (
        "from autogen.interop import Interoperability"
        not in third_party_imports
    ):
        third_party_imports.append(
            "from autogen.interop import Interoperability"
        )

    sorted_standard_lib_imports = _sort_imports(standard_lib_imports)
    sorted_third_party_imports = _sort_imports(third_party_imports)

    return sorted_standard_lib_imports, sorted_third_party_imports

generate_function

generate_function(
    function_name: str,
    function_args: list[str],
    function_types: tuple[list[str], str],
    function_body: str,
    types_as_comments: bool = False,
) -> str

Generate a function.

Parameters:

NameTypeDescriptionDefault
function_namestr

The function name.

required
function_argslist[str]

The function arguments.

required
function_typestuple[list[str], str]

The function types.

required
function_bodystr

The function body.

required
types_as_commentsbool

Include the type hints as comments (or in the function signature) (default is False).

False

Returns:

TypeDescription
str

The generated function.

Source code in waldiez/models/common/method_utils.py
def generate_function(
    function_name: str,
    function_args: list[str],
    function_types: tuple[list[str], str],
    function_body: str,
    types_as_comments: bool = False,
) -> str:
    """Generate a function.

    Parameters
    ----------
    function_name : str
        The function name.
    function_args : list[str]
        The function arguments.
    function_types : tuple[list[str], str]
        The function types.
    function_body : str
        The function body.
    types_as_comments : bool, optional
        Include the type hints as comments (or in the function signature)
        (default is False).

    Returns
    -------
    str
        The generated function.
    """
    if len(function_name) > MAX_VAR_NAME_LENGTH:
        function_name = function_name[:MAX_VAR_NAME_LENGTH]
    function_string = f"def {function_name}("
    if not function_args:
        function_string += ")"
    else:
        function_string += "\n"
        for arg, arg_type in zip(
            function_args, function_types[0], strict=False
        ):
            if types_as_comments:
                function_string += f"    {arg},  # type: {arg_type}" + "\n"
            else:
                function_string += f"    {arg}: {arg_type}," + "\n"
        function_string += ")"
    if types_as_comments:
        function_string += ":\n"
        function_string += "    # type: (...) -> " + function_types[1]
    else:
        function_string += " -> " + function_types[1] + ":"
    function_string += "\n" if not function_body.startswith("\n") else ""
    function_string += f"{function_body}"
    if not function_string.endswith("\n"):  # pragma: no branch
        function_string += "\n"
    return function_string

get_function

get_function(code_string: str, function_name: str) -> str

Get the function signature and body.

Parameters:

NameTypeDescriptionDefault
code_stringstr

The code string.

required
function_namestr

The function name.

required

Returns:

TypeDescription
str

The function signature and body.

Source code in waldiez/models/common/method_utils.py
def get_function(
    code_string: str,
    function_name: str,
) -> str:
    """Get the function signature and body.

    Parameters
    ----------
    code_string : str
        The code string.
    function_name : str
        The function name.

    Returns
    -------
    str
        The function signature and body.
    """
    tree = parso.parse(code_string)  # type: ignore
    for node in tree.iter_funcdefs():
        if node.name.value == function_name:
            return node.get_code()
    return ""

is_standard_library

is_standard_library(module_name: str) -> bool

Check if the module is part of the standard library.

Parameters:

NameTypeDescriptionDefault
module_namestr

The module name.

required

Returns:

TypeDescription
bool

True if the module is part of the standard library.

Source code in waldiez/models/common/method_utils.py
def is_standard_library(module_name: str) -> bool:
    """Check if the module is part of the standard library.

    Parameters
    ----------
    module_name : str
        The module name.

    Returns
    -------
    bool
        True if the module is part of the standard library.
    """
    if module_name in sys.builtin_module_names:
        return True
    try:
        spec = importlib.util.find_spec(module_name)
    except (ImportError, ValueError, ModuleNotFoundError):  # pragma: no cover
        return False
    if spec is None or not spec.origin:  # pragma: no cover
        return False
    if "site-packages" in spec.origin:
        return False
    if spec.origin == "frozen":
        return True
    stdlib_path = Path(sysconfig.get_path("stdlib")).resolve()
    return Path(spec.origin).resolve().is_relative_to(stdlib_path)

parse_code_string

parse_code_string(code_string: str) -> ParseResult

Parse the code string.

Parameters:

NameTypeDescriptionDefault
code_stringstr

The code string.

required

Returns:

TypeDescription
ParseResult

If valid, None and the ast module. If invalid, the error message and None.

Source code in waldiez/models/common/method_utils.py
def parse_code_string(
    code_string: str,
) -> ParseResult:
    """Parse the code string.

    Parameters
    ----------
    code_string : str
        The code string.

    Returns
    -------
    ParseResult
        If valid, None and the ast module.
        If invalid, the error message and None.
    """
    # pylint: disable=broad-except
    try:
        tree = ast.parse(code_string)
    except SyntaxError as e:
        return ParseResult(
            f"SyntaxError: {e}, in " + "\n" + f"{code_string}", None
        )
    except BaseException as e:  # pragma: no cover
        return ParseResult(
            f"Invalid code: {e}, in " + "\n" + f"{code_string}", None
        )
    return ParseResult(None, tree)

naming

Ensure unique names for agents, models, tools, and chats.

get_valid_instance_name

get_valid_instance_name(
    instance: tuple[str, str],
    current_names: dict[str, str],
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> dict[str, str]

Get a valid instance name.

If the instance id is already in the current names nothing is done. If the name already exists in the current names, the name is updated (with an index suffix).

Parameters:

NameTypeDescriptionDefault
instancetuple[str, str]

The instance id and possible name.

required
current_namesdict[str, str]

The current names.

required
prefixstr

The prefix to use if the name starts with a digit, if the name is already in the current names, or if the name is already in the current names with an index suffix.

'w'
max_lengthint

The maximum length of the variable name.

MAX_VARIABLE_LENGTH

Returns:

TypeDescription
dict[str, str]

The updated names.

Source code in waldiez/models/common/naming.py
def get_valid_instance_name(
    instance: tuple[str, str],
    current_names: dict[str, str],
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> dict[str, str]:
    """Get a valid instance name.

    If the instance id is already in the current names nothing is done.
    If the name already exists in the current names,
        the name is updated (with an index suffix).

    Parameters
    ----------
    instance : tuple[str, str]
        The instance id and possible name.
    current_names : dict[str, str]
        The current names.
    prefix : str, optional
        The prefix to use if the name starts with a digit,
        if the name is already in the current names,
        or if the name is already in the current names with an index suffix.
    max_length : int, optional
        The maximum length of the variable name.

    Returns
    -------
    dict[str, str]
        The updated names.
    """
    instance_id, possible_name = instance[0], instance[1][:max_length]

    if instance_id in current_names:
        # already in the current names (by its id)
        return current_names

    new_names = current_names.copy()
    name = get_valid_python_variable_name(
        possible_name, prefix=prefix, max_length=max_length
    )

    if name in current_names.values():
        name = f"{prefix}_{name}"

    if name in current_names.values():
        index = 1
        while f"{name}_{index}" in current_names.values():
            index += 1
        name = f"{name}_{index}"

    new_names[instance_id] = name
    return new_names

get_valid_python_variable_name

get_valid_python_variable_name(
    possible: str,
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> str

Get a valid Python variable name from a possible name.

Parameters:

NameTypeDescriptionDefault
possiblestr

The possible name.

required
prefixstr

The prefix to use if the name starts with a digit or special character

'w'
max_lengthint

The maximum length of the variable name.

MAX_VARIABLE_LENGTH

Returns:

TypeDescription
str

The valid Python variable name.

Source code in waldiez/models/common/naming.py
def get_valid_python_variable_name(
    possible: str,
    prefix: str = "w",
    max_length: int = MAX_VARIABLE_LENGTH,
) -> str:
    """Get a valid Python variable name from a possible name.

    Parameters
    ----------
    possible : str
        The possible name.
    prefix : str, optional
        The prefix to use if the name starts with a digit or special character
    max_length : int, optional
        The maximum length of the variable name.

    Returns
    -------
    str
        The valid Python variable name.
    """
    if not possible or not possible.strip():
        return prefix + "_"

    # First handle arrow operators specifically
    possible = possible.replace("->", "to")
    possible = possible.replace("=>", "to")
    possible = possible.replace("<-", "from")
    possible = possible.replace("<=", "from")

    # Replace non-ASCII characters and non-word characters with underscores
    # \W matches any non-word character, but in Python's re module,
    # \w includes Unicode letters by default, so we need to be more explicit
    # to replace Unicode letters with underscores for valid Python identifiers
    possible = re.sub(r"[^\w]", "_", possible)  # Replace non-word chars
    possible = re.sub(r"[^\x00-\x7F]", "_", possible)  # Replace non-ASCII chars

    # Convert to lowercase and truncate
    possible = possible.lower()[:max_length]

    # Remove trailing underscores from truncation
    possible = possible.rstrip("_")

    if not possible:
        return prefix + "_"

    # Handle names starting with underscore
    if possible.startswith("_"):
        return f"{prefix}{possible}"

    # Handle names starting with digit
    if possible[0].isdigit():
        return f"{prefix}_{possible}"

    return possible

now

now() -> str

Get the current date and time in UTC.

Returns:

TypeDescription
str

The current date and time in UTC.

Source code in waldiez/models/common/date_utils.py
def now() -> str:
    """Get the current date and time in UTC.

    Returns
    -------
    str
        The current date and time in UTC.
    """
    return (
        datetime.now(tz=timezone.utc)
        .isoformat(timespec="milliseconds")
        .replace("+00:00", "Z")
    )

parse_code_string

parse_code_string(code_string: str) -> ParseResult

Parse the code string.

Parameters:

NameTypeDescriptionDefault
code_stringstr

The code string.

required

Returns:

TypeDescription
ParseResult

If valid, None and the ast module. If invalid, the error message and None.

Source code in waldiez/models/common/method_utils.py
def parse_code_string(
    code_string: str,
) -> ParseResult:
    """Parse the code string.

    Parameters
    ----------
    code_string : str
        The code string.

    Returns
    -------
    ParseResult
        If valid, None and the ast module.
        If invalid, the error message and None.
    """
    # pylint: disable=broad-except
    try:
        tree = ast.parse(code_string)
    except SyntaxError as e:
        return ParseResult(
            f"SyntaxError: {e}, in " + "\n" + f"{code_string}", None
        )
    except BaseException as e:  # pragma: no cover
        return ParseResult(
            f"Invalid code: {e}, in " + "\n" + f"{code_string}", None
        )
    return ParseResult(None, tree)

update_dict

update_dict(original: dict[str, Any]) -> dict[str, Any]

Try to determine the type of the dictionary values.

Parameters:

NameTypeDescriptionDefault
originaldict[str, Any]

The original dictionary.

required

Returns:

TypeDescription
dict[str, Any]

The updated dictionary with values converted to the detected types.

Source code in waldiez/models/common/dict_utils.py
def update_dict(original: dict[str, Any]) -> dict[str, Any]:
    """
    Try to determine the type of the dictionary values.

    Parameters
    ----------
    original : dict[str, Any]
        The original dictionary.

    Returns
    -------
    dict[str, Any]
        The updated dictionary with values converted to the detected types.
    """
    new_dict: dict[str, Any] = {}

    for key, value in original.items():
        # Skip conversion if already the desired type
        if not isinstance(value, str):
            new_dict[key] = value
            continue

        value_stripped = value.strip()
        if (
            value_stripped.startswith('"') and value_stripped.endswith('"')
        ) or (value_stripped.startswith("'") and value_stripped.endswith("'")):
            value_stripped = value_stripped[1:-1]
        if not value_stripped:  # Empty or whitespace-only
            new_dict[key] = value
            continue

        value_lower = value_stripped.lower()

        # Check for None/null
        if value_lower in NULL_VALUES:
            new_dict[key] = None
        # Check for boolean
        elif value_lower in BOOL_VALUES:
            new_dict[key] = value_lower == "true"
        # Check for integer
        elif re.fullmatch(r"[-+]?\d+", value_stripped):
            new_dict[key] = int(value_stripped)
        # Check for float
        else:
            try:
                # This handles floats, scientific notation, etc.
                float_val = float(value_stripped)
                new_dict[key] = float_val
            except ValueError:
                # Keep as string if conversion fails
                new_dict[key] = value_stripped

    return new_dict

waldiez_version

Read the version from the version file.

get_waldiez_version

get_waldiez_version() -> str

Read the version from the version file.

Returns:

TypeDescription
str

The version.

Source code in waldiez/models/common/waldiez_version.py
def get_waldiez_version() -> (
    str
):  # pragma: no cover  # depends on file existence
    """Read the version from the version file.

    Returns
    -------
    str
        The version.
    """
    here = Path(__file__).parent  # waldiez/models/common
    package_dir = here.parent.parent  # waldiez/models -> waldiez
    version_file = package_dir / "_version.py"
    if not version_file.exists():
        return "0.0.0"  # dev / ignored
    with version_file.open() as f:
        for line in f:
            if line.startswith("__version__"):
                version = line.split("=")[1].strip().strip('"').strip("'")
                # send version without "v" prefix
                if version.startswith("v"):
                    version = version[1:]
                # make sure it is a valid semver
                if not version or not all(
                    part.isdigit() for part in version.split(".")
                ):
                    return "0.0.0"
                return version
    return "0.0.0"  # fallback if not found