> ## Documentation Index
> Fetch the complete documentation index at: https://www.agent37.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Temporal

> Run sandbox agents in Agent37 sandboxes from Temporal workflows, where a retried activity never runs a command twice.

Give an agent in a [Temporal](https://temporal.io) workflow an Agent37 sandbox to work in. Temporal's [OpenAI Agents integration](https://docs.temporal.io/develop/python/integrations/openai-agents) runs every sandbox operation (creating it, each command, each file read and write, deleting it) as its own activity, so a worker that crashes part-way through a run picks it up where it stopped, against the same sandbox.

The sandbox client is the one file from the [OpenAI Agents SDK guide](https://www.agent37.com/docs/agents-api/openai-agents-sdk.md#install), with no package to install.

## Install

Use Python 3.11 or newer, an [Agent37 API key](https://www.agent37.com/dashboard/cloud/api-keys), a funded [workspace wallet](https://www.agent37.com/docs/agents-api/billing.md), and a Temporal server. The [Temporal CLI](https://docs.temporal.io/cli) runs one locally.

```bash theme={null}
pip install temporalio-openai-agents httpx
export AGENT37_API_KEY=sk_live_...
export OPENAI_API_KEY=...
temporal server start-dev
```

Save [`agent37_sandbox.py`](https://www.agent37.com/docs/agents-api/openai-agents-sdk#install) next to the three files below.

## Write the workflow

The workflow names a sandbox provider, `agent37`, and the worker decides what that name means.

```python coding_workflow.py theme={null}
from agents import Runner
from agents.run import RunConfig
from agents.sandbox import SandboxAgent, SandboxRunConfig
from temporalio import workflow
from temporalio.openai_agents.workflow import temporal_sandbox_client

with workflow.unsafe.imports_passed_through():
    from agent37_sandbox import Agent37SandboxClientOptions


@workflow.defn
class CodingWorkflow:
    @workflow.run
    async def run(self, prompt: str) -> str:
        agent = SandboxAgent(
            name="Coder",
            model="gpt-5.5",
            instructions="Use the sandbox to do the work, then report what the commands returned.",
        )
        result = await Runner.run(
            agent,
            prompt,
            run_config=RunConfig(
                sandbox=SandboxRunConfig(
                    client=temporal_sandbox_client("agent37"),
                    options=Agent37SandboxClientOptions(),
                ),
            ),
        )
        return str(result.final_output)
```

Import the options inside `imports_passed_through()`, because Temporal's workflow sandbox blocks the HTTP library the client file imports.

## Run the worker

Register the Agent37 client under the same name. The worker process is the only place that needs `AGENT37_API_KEY` and `OPENAI_API_KEY`.

```python worker.py theme={null}
import asyncio

from temporalio.client import Client
from temporalio.openai_agents import OpenAIAgentsPlugin, SandboxClientProvider
from temporalio.worker import Worker

from agent37_sandbox import Agent37SandboxClient
from coding_workflow import CodingWorkflow


async def main():
    client = await Client.connect(
        "localhost:7233",
        plugins=[
            OpenAIAgentsPlugin(
                sandbox_clients=[SandboxClientProvider("agent37", Agent37SandboxClient())],
            ),
        ],
    )
    await Worker(client, task_queue="agent37-sandbox", workflows=[CodingWorkflow]).run()


asyncio.run(main())
```

## Start a run

```python start.py theme={null}
import asyncio
import uuid

from temporalio.client import Client
from temporalio.openai_agents import OpenAIAgentsPlugin

from coding_workflow import CodingWorkflow


async def main():
    client = await Client.connect("localhost:7233", plugins=[OpenAIAgentsPlugin()])
    result = await client.execute_workflow(
        CodingWorkflow.run,
        "Write fib.py that prints the first 10 Fibonacci numbers, run it, and show the output.",
        id=f"coding-{uuid.uuid4().hex[:8]}",
        task_queue="agent37-sandbox",
    )
    print(result)


asyncio.run(main())
```

```bash theme={null}
python worker.py   # one terminal
python start.py    # another
```

The run creates an instance, and the Temporal Web UI at `http://localhost:8233` shows each step as an `agent37-sandbox_*` activity between the model calls. The instance is deleted when the run ends, including when it fails. Instances bill your workspace while they exist; OpenAI bills model calls separately.

## Retries do not run a command twice

Temporal retries an activity whose connection dropped, whose worker died, or that passed its timeout. Inside an activity, the client sends each command under a [name](https://www.agent37.com/docs/agents-api/exec.md) taken from the workflow run, the activity, and the command. Agent37 runs a named command once: a retry gets that run's result, waiting for it if it is still running, and the command does not start a second time. A name is remembered while its command runs and for 5 minutes after it finishes.

Sandbox activities get 5 minutes by default, and a command can run for up to 15. Give long commands the time they need:

```python theme={null}
from datetime import timedelta

from temporalio.workflow import ActivityConfig

client = temporal_sandbox_client(
    "agent37", ActivityConfig(start_to_close_timeout=timedelta(minutes=16))
)
```

A call Agent37 refuses (a revoked key, a deleted instance, an empty wallet) fails the activity without retries. A dropped connection or a `5xx` is retried.

## Sleep while a workflow waits

A workflow can wait hours for a person or a timer. Turn on [auto-sleep](https://www.agent37.com/docs/agents-api/instance-auto-sleep.md) and the instance sleeps while nothing runs in it, paying for disk alone, and the next command wakes it with its files and running processes as they were:

```python theme={null}
options = Agent37SandboxClientOptions(
    create_options={"auto_sleep": True, "idle_timeout_seconds": 300},
)
```

`create_options` accepts the JSON fields from [Create an instance](https://www.agent37.com/docs/agents-api/instances/create.md), such as `resources`, `env`, `region`, and `type`. The rest of the client (keeping files between runs, attaching to an existing instance, choosing a template) is in the [OpenAI Agents SDK guide](https://www.agent37.com/docs/agents-api/openai-agents-sdk.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.