Skip to content

Common types

conatus.utils.common_types

Common types shared across the project.

JSONPrimitives module-attribute

JSONPrimitives = str | int | float | bool | None

JSON primitives type alias.

JSONLevel1 module-attribute

JSON level with one level of nesting.

JSONLevel2 module-attribute

JSONLevel2 = (
    JSONPrimitives
    | dict[str, JSONLevel1]
    | list[JSONLevel1]
    | tuple[JSONLevel1, ...]
)

JSON level with two levels of nesting.

JSONLevel3 module-attribute

JSONLevel3 = (
    JSONPrimitives
    | dict[str, JSONLevel2]
    | list[JSONLevel2]
    | tuple[JSONLevel2, ...]
)

JSON level with three levels of nesting.

JSONLevel4 module-attribute

JSONLevel4 = (
    JSONPrimitives
    | dict[str, JSONLevel3]
    | list[JSONLevel3]
    | tuple[JSONLevel3, ...]
)

JSON level with four levels of nesting.

JSONLevel5 module-attribute

JSONLevel5 = (
    JSONPrimitives
    | dict[str, JSONLevel4]
    | list[JSONLevel4]
    | tuple[JSONLevel4, ...]
)

JSON level with five levels of nesting.

JSONLevel6 module-attribute

JSONLevel6 = (
    JSONPrimitives
    | dict[str, JSONLevel5]
    | list[JSONLevel5]
    | tuple[JSONLevel5, ...]
)

JSON level with six levels of nesting.

JSONLevel7 module-attribute

JSONLevel7 = (
    JSONPrimitives
    | dict[str, JSONLevel6]
    | list[JSONLevel6]
    | tuple[JSONLevel6, ...]
)

JSON level with seven levels of nesting.

JSONLevel8 module-attribute

JSONLevel8 = (
    JSONPrimitives
    | dict[str, JSONLevel7]
    | list[JSONLevel7]
    | tuple[JSONLevel7, ...]
)

JSON level with eight levels of nesting.

JSONLevel9 module-attribute

JSONLevel9 = (
    JSONPrimitives
    | dict[str, JSONLevel8]
    | list[JSONLevel8]
    | tuple[JSONLevel8, ...]
)

JSON level with nine levels of nesting.

JSONLevel10 module-attribute

JSONLevel10 = (
    JSONPrimitives
    | dict[str, JSONLevel9]
    | list[JSONLevel9]
    | tuple[JSONLevel9, ...]
)

JSON levels with up to 10 levels of nesting.

DeepConstJSONSchema module-attribute

DeepConstJSONSchema = (
    JSONPrimitives
    | dict[str, JSONLevel10]
    | list[JSONLevel10]
)

JSON schema with a maximum of 10 levels of nesting.

ConstJSONSchema module-attribute

ConstJSONSchema = (
    JSONPrimitives
    | dict[str, JSONLevel2]
    | list[JSONLevel2]
)

JSON schema with a maximum of 2 levels of nesting.

JSONType module-attribute

JSONType = JSONLevel3

Default JSON type alias, with a maximum of 3 levels of nesting.

InvariantJSONDict module-attribute

InvariantJSONDict = (
    dict[str, float]
    | dict[str, str]
    | dict[str, bool]
    | dict[str, None]
)

Invariant JSON dictionary type alias.

ArbitraryBaseModel

Bases: BaseModel

Base model for arbitrary types.

This model is used to allow arbitrary types in the models.

NoExtraBaseModel

Bases: BaseModel

Base model that forbids extra fields.

IgnoreExtraBaseModel

Bases: BaseModel

Base model that ignores extra fields.

FrozenArbitraryBaseModel

Bases: BaseModel

Base model that is frozen and allows arbitrary types.

conatus.utils.common_processing

Common processing functions across all modules.

check_name_is_not_reserved

check_name_is_not_reserved(
    name: str, kind: Literal["action", "variable"]
) -> None

Check if the name of an action or variable is not reserved.

For Action classes and subclasses

In general, this function will be called when the name attribute is set on the class. But if you want to do modifications before the class is created, you can call this function directly.

For inputs and outputs of Agent

This function will be called when the inputs and outputs are normalized.

PARAMETER DESCRIPTION
name

The name to check.

TYPE: str

kind

The kind of the name. Either "action" or "variable".

TYPE: Literal['action', 'variable']

RAISES DESCRIPTION
ValueError

If the name is reserved.

Source code in conatus/utils/common_processing.py
def check_name_is_not_reserved(
    name: str, kind: Literal["action", "variable"]
) -> None:
    """Check if the name of an action or variable is not reserved.

    # For [`Action`][conatus.actions.Action] classes and subclasses

    In general, this function will be called when the `name` attribute is
    set on the class. But if you want to do modifications before the
    class is created, you can call this function directly.

    # For inputs and outputs of [`Agent`][conatus.agents.base.BaseAgent]

    This function will be called when the inputs and outputs are
    normalized.

    Args:
        name: The name to check.
        kind: The kind of the name. Either "action" or "variable".

    Raises:
        ValueError: If the name is reserved.
    """
    if name in PYTHON_BUILTIN_NAMES:
        msg = (
            f"The name of this {kind} ('{name}') overrides a Python "
            "built-in name. Please choose a different name."
        )
        raise ValueError(msg)

    if name in CONATUS_RESERVED_NAMES:
        msg = (
            f"The name of this {kind} ('{name}') overrides a Conatus "
            "reserved name. Please choose a different name."
        )
        raise ValueError(msg)

generate_import_statement

generate_import_statement(
    t: type, *, skip_if_builtin: Literal[False]
) -> tuple[str, str]
generate_import_statement(
    t: type, *, skip_if_builtin: Literal[True] = True
) -> tuple[str, str] | None
generate_import_statement(
    t: type, *, skip_if_builtin: bool = True
) -> tuple[str, str] | None

Generate an import statement for a given type.

Example

from conatus.utils.common_processing import generate_import_statement
from conatus.runtime.variable import RuntimeVariable

variable = RuntimeVariable("var", 0)
import_statement = generate_import_statement(type(variable))
assert (
    import_statement
    == ("conatus.runtime.variable", "RuntimeVariable")
)
PARAMETER DESCRIPTION
t

The type object to generate the import for.

TYPE: type

skip_if_builtin

Whether to skip if the type is a built-in type. Defaults to True.

TYPE: bool DEFAULT: True

RETURNS DESCRIPTION
str

The formatted import statement.

TYPE: tuple[str, str] | None

Source code in conatus/utils/common_processing.py
def generate_import_statement(
    t: type, *, skip_if_builtin: bool = True
) -> tuple[str, str] | None:
    """Generate an import statement for a given type.

    !!! example

        ```python
        from conatus.utils.common_processing import generate_import_statement
        from conatus.runtime.variable import RuntimeVariable

        variable = RuntimeVariable("var", 0)
        import_statement = generate_import_statement(type(variable))
        assert (
            import_statement
            == ("conatus.runtime.variable", "RuntimeVariable")
        )
        ```

    Args:
        t (type): The type object to generate the import for.
        skip_if_builtin (bool): Whether to skip if the type is a built-in type.
            Defaults to `True`.

    Returns:
        str: The formatted import statement.
    """
    module = t.__module__
    qualname = t.__qualname__
    if skip_if_builtin and module == "builtins":
        return None
    return (module, qualname)

extract_code_blocks

extract_code_blocks(
    markdown_text: str,
) -> list[tuple[str, str]]

Extracts all fenced code blocks from a Markdown-formatted LLM response.

PARAMETER DESCRIPTION
markdown_text

The Markdown content.

TYPE: str

RETURNS DESCRIPTION
list[tuple[str, str]]

A list of tuples where each tuple contains: (1) The language (empty string if unspecified) (2) The code block content

Source code in conatus/utils/common_processing.py
def extract_code_blocks(markdown_text: str) -> list[tuple[str, str]]:
    """Extracts all fenced code blocks from a Markdown-formatted LLM response.

    Args:
        markdown_text (str): The Markdown content.

    Returns:
        A list of tuples where each tuple contains:
            (1) The language (empty string if unspecified)
            (2) The code block content
    """
    code_blocks: list[tuple[str, str]] = []

    # Regex for fenced code blocks
    fenced_pattern = re.compile(r"```(\w*)\n(.*?)```", re.DOTALL)

    for match in fenced_pattern.finditer(markdown_text):
        language, code = match.groups()
        code_blocks.append((language, code.strip()))

    return code_blocks