Skip to content

Instruction

conatus.runtime.instruction.RuntimeInstruction

Bases: ABC

Instruction for the Runtime.

There are two types of instructions that are executable by the Runtime :

Each of these classes has a code method, which returns the code of the instruction. This will be essentially for replaying the run.

No execution capabilities

This class, and its subclasses, do not have any execution capabilities. The actual execution is done by the Runtime class. Treat this class as a piece of code.

We're doing this in large part to avoid circular imports. See the documentation of RuntimeState for more information.

code abstractmethod

code() -> str

Get the code of the instruction.

Source code in conatus/runtime/instruction.py
@abstractmethod
def code(self) -> str:
    """Get the code of the instruction."""

import_statements abstractmethod

import_statements() -> list[tuple[str, str]]

Get the import statements for the instruction.

The import statements are returned as a list of tuples, where the first element is the module name and the second element is the name of the object.

RETURNS DESCRIPTION
list[tuple[str, str]]

list[tuple[str, str]]: The import statements for the instruction.

Source code in conatus/runtime/instruction.py
@abstractmethod
def import_statements(self) -> list[tuple[str, str]]:
    """Get the import statements for the instruction.

    The import statements are returned as a list of tuples, where the
    first element is the module name and the second element is the name of
    the object.

    Returns:
        list[tuple[str, str]]: The import statements for the instruction.
    """

conatus.runtime.instruction.RuntimeJSONInstruction dataclass

RuntimeJSONInstruction(
    action_name: str,
    arguments: dict[str, JSONType | RuntimeVariable],
    returns: list[tuple[str, TypeOfType]],
    stdout_output: str | None = None,
    stderr_output: str | None = None,
    modified_variables: list[str] = list(),
    execution_successful: bool = False,
)

Bases: RuntimeInstruction

An instruction for the agent that is a JSON call.

from conatus.runtime.state import RuntimeJSONInstruction

instruction = RuntimeJSONInstruction(
    action_name="search_google",
    arguments={"query": "What happens if you eat soap?"},
    returns=[("result", str)],
)
assert instruction.code() == (
    "result: str = search_google(query='What happens if you eat soap?')"
)

action_name instance-attribute

action_name: str

The name of the action to perform.

arguments instance-attribute

The arguments for the action.

The arguments can be either a JSONType or a RuntimeVariable.

returns instance-attribute

returns: list[tuple[str, TypeOfType]]

The return variables of the action, in the format (name, type_hint).

stdout_output class-attribute instance-attribute

stdout_output: str | None = None

The output of the code snippet to stdout, if any.

stderr_output class-attribute instance-attribute

stderr_output: str | None = None

The output of the code snippet to stderr, if any.

modified_variables class-attribute instance-attribute

modified_variables: list[str] = field(default_factory=list)

The variables that were modified by the code snippet.

execution_successful class-attribute instance-attribute

execution_successful: bool = False

Whether the execution of the instruction was successful.

argument_to_str staticmethod

argument_to_str(
    argument: JSONType | RuntimeVariable,
) -> str

Convert an argument to a string.

This is necessary to print instructions as if it was Python code.

If the argument is a RuntimeVariable , we return the name of the variable.

If the argument is a string, we return the string itself, in quotes.

Otherwise, we return the string representation of the argument.

Example

from conatus.runtime.state import RuntimeJSONInstruction
from conatus.runtime.variable import RuntimeVariable

variable = RuntimeVariable(name="variable", value="value")
assert RuntimeJSONInstruction.argument_to_str(variable) == "variable"
assert RuntimeJSONInstruction.argument_to_str("string") == "'string'"
assert RuntimeJSONInstruction.argument_to_str(1) == "1"
RETURNS DESCRIPTION
str

The string representation of the argument.

TYPE: str

Source code in conatus/runtime/instruction.py
@staticmethod
def argument_to_str(argument: JSONType | RuntimeVariable) -> str:
    """Convert an argument to a string.

    This is necessary to print instructions as if it was Python code.

    If the argument is a [`RuntimeVariable`
    ][conatus.runtime.variable.RuntimeVariable], we return the name of the
    variable.

    If the argument is a string, we return the string itself, in quotes.

    Otherwise, we return the string representation of the argument.

    # Example

    ```python
    from conatus.runtime.state import RuntimeJSONInstruction
    from conatus.runtime.variable import RuntimeVariable

    variable = RuntimeVariable(name="variable", value="value")
    assert RuntimeJSONInstruction.argument_to_str(variable) == "variable"
    assert RuntimeJSONInstruction.argument_to_str("string") == "'string'"
    assert RuntimeJSONInstruction.argument_to_str(1) == "1"
    ```

    Returns:
        str: The string representation of the argument.
    """
    if isinstance(argument, RuntimeVariable):
        return argument.name
    if isinstance(argument, str):
        return repr(argument)
    return str(argument)

code

code() -> str

Get the Python code of the instruction.

A few rules:

  • If the action has no return value, the code will be:

    _ = fn(arg0=variable_0, arg1="value_1")
    
  • If the action has one return value, the code will be:

    result: type = fn(arg0=variable_0, arg1="value_1")
    
  • If the action has multiple return values, the code will be:

    result1: type1
    result2: type2
    result1, result2 = fn(arg0=variable_0, arg1="value_1")
    
RETURNS DESCRIPTION
str

The Python code of the instruction.

TYPE: str

Source code in conatus/runtime/instruction.py
@override
def code(self) -> str:
    """Get the Python code of the instruction.

    A few rules:

    - If the action has no return value, the code will be:

      ```text
      _ = fn(arg0=variable_0, arg1="value_1")
      ```

    - If the action has one return value, the code will be:

      ```text
      result: type = fn(arg0=variable_0, arg1="value_1")
      ```

    - If the action has multiple return values, the code will be:

      ```text
      result1: type1
      result2: type2
      result1, result2 = fn(arg0=variable_0, arg1="value_1")
      ```

    Returns:
        str: The Python code of the instruction.
    """
    results_part: str
    type_hint_str: str
    if not self.returns:
        results_part = "_"
    elif len(self.returns) == 1:
        type_hint_str = process_typehint(
            self.returns[0][1],
            return_type="str",
            allow_qualified_names=False,
        )
        results_part = f"{self.returns[0][0]}: {type_hint_str}"
    else:
        results_part = ""
        for name, type_hint in self.returns:
            type_hint_str = process_typehint(
                type_hint, return_type="str", allow_qualified_names=False
            )
            results_part += f"{name}: {type_hint_str}\n"
        results_part = results_part.rstrip("\n")
        results_part += "\n"
        results_part += ", ".join(f"{name}" for name, _ in self.returns)

    arguments_part = ", ".join(
        self.argument_to_str(value)
        if name == "_"
        else f"{name}={self.argument_to_str(value)}"
        for name, value in self.arguments.items()
        if name != "return"
    )
    return f"{results_part} = {self.action_name}({arguments_part})"

import_statements

import_statements() -> list[tuple[str, str]]

Get the import statements for the instruction.

RETURNS DESCRIPTION
list[tuple[str, str]]

list[tuple[str, str]]: The import statements for the instruction.

Source code in conatus/runtime/instruction.py
@override
def import_statements(self) -> list[tuple[str, str]]:
    """Get the import statements for the instruction.

    Returns:
        list[tuple[str, str]]: The import statements for the instruction.
    """
    all_types: set[type] = set()
    for _, type_hint in self.returns:
        type_hint_set: set[type | str] = process_typehint(
            type_hint, return_type="set"
        )
        for type_or_str in type_hint_set:
            if isinstance(type_or_str, type):
                all_types.add(type_or_str)
    import_statements_type_hints: list[tuple[str, str] | None] = [
        generate_import_statement(type_hint) for type_hint in all_types
    ]
    return [
        import_statement
        for import_statement in import_statements_type_hints
        if import_statement is not None
    ]

conatus.runtime.instruction.RuntimePythonInstruction dataclass

RuntimePythonInstruction(
    snippet: str,
    stdout_output: str | None = None,
    stderr_output: str | None = None,
    modified_variables: list[str] = list(),
    execution_successful: bool = False,
)

Bases: RuntimeInstruction

An instruction for the agent that is a Python code snippet.

from conatus.runtime.state import RuntimePythonInstruction

code_snippet = "result = 10093/100"
instruction = RuntimePythonInstruction(code_snippet)
assert instruction.code() == code_snippet

snippet instance-attribute

snippet: str

The Python code of the instruction.

stdout_output class-attribute instance-attribute

stdout_output: str | None = None

The output of the code snippet to stdout, if any.

stderr_output class-attribute instance-attribute

stderr_output: str | None = None

The output of the code snippet to stderr, if any.

modified_variables class-attribute instance-attribute

modified_variables: list[str] = field(default_factory=list)

The variables that were modified by the code snippet.

execution_successful class-attribute instance-attribute

execution_successful: bool = False

Whether the execution of the instruction was successful.

code

code() -> str

Get the Python code of the instruction.

It's just the snippet.

RETURNS DESCRIPTION
str

The instruction as Python code.

TYPE: str

Source code in conatus/runtime/instruction.py
@override
def code(self) -> str:
    """Get the Python code of the instruction.

    It's just the snippet.

    Returns:
        str: The instruction as Python code.
    """
    return self.snippet

import_statements

import_statements() -> list[tuple[str, str]]

Get the import statements for the instruction.

RETURNS DESCRIPTION
list[tuple[str, str]]

list[tuple[str, str]]: The import statements for the instruction.

Source code in conatus/runtime/instruction.py
@override
def import_statements(self) -> list[tuple[str, str]]:
    """Get the import statements for the instruction.

    Returns:
        list[tuple[str, str]]: The import statements for the instruction.
    """
    # NOTE: For now, we don't have a way to extract import statements from
    # a Python snippet. This might be added in the future.
    return []