Skip to content

The platform for continuously improving AI agents.

2.1 KB
Raw Blame
from contextlib import suppress
from datetime import timedelta

from temporalio import workflow
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError

TASK_QUEUE = "overmind-research"


def workflow_id(agent):
    return f"research-agent:{agent}"


@workflow.defn
class ResearchAgentWorkflow:
    """One research agent: a burst of turns is an activity, a wake is a signal, a wait is a timer."""

    def __init__(self):
        self.woken = False

    @workflow.signal
    def wake(self):
        self.woken = True

    @workflow.run
    async def run(self, agent: str) -> dict:
        while True:
            # Cleared before the burst, so a wake that lands while it runs is not lost.
            self.woken = False
            try:
                result = await workflow.execute_activity(
                    "research_advance",
                    agent,
                    start_to_close_timeout=timedelta(hours=2),
                    heartbeat_timeout=timedelta(seconds=90),
                    retry_policy=RetryPolicy(
                        initial_interval=timedelta(seconds=5),
                        maximum_interval=timedelta(seconds=60),
                        maximum_attempts=4,
                    ),
                )
            except ActivityError as error:
                cause = error.cause
                result = await workflow.execute_activity(
                    "research_fence",
                    args=[
                        agent,
                        getattr(cause, "type", None) or type(cause).__name__,
                        next(iter(getattr(cause, "details", ())), None),
                    ],
                    start_to_close_timeout=timedelta(seconds=60),
                )
            if result["state"] == "end":
                return result
            if result["state"] == "wait":
                with suppress(TimeoutError):
                    await workflow.wait_condition(
                        lambda: self.woken, timeout=timedelta(seconds=result["seconds"])
                    )
            if workflow.info().is_continue_as_new_suggested():
                workflow.continue_as_new(agent)