opendunes
Building agents
Copy page ▾

A headless agent

Run an agent with no one at the keyboard: a goal in, the result out, and an exit code a script can read.

  1. Take the goal from the command line.
  2. Run the loop to a result.
  3. Write events for another program.
  4. End with an exit code.
  5. Run it on a schedule.

1. Take the goal from the command line

A headless agent has no screen and no one to answer its questions. It reads its goal once, at start: from its arguments, or piped in on standard input.

You runThe goal is
python agent.py "Read sales/today.csv and write report.md"the arguments
cat task.txt | python agent.pywhat came in on standard input
python agent.py --json "…"the arguments, with events written as JSON lines

Lamia runs a bookshop in Tizi Ouzou. Every morning at 6, her agent reads the day's sales file and writes the report she reads with her coffee.

2. Run the loop to a result

The loop is the tool loop of Tools and function calling, with two changes. Its brief tells the model that nobody will answer, so it decides for itself. And the file it writes lands in out/, whatever path the model names: an agent nobody watches gets the smallest reach that does the job.

import json
import os
import sys
from openai import OpenAI

API_KEY = os.environ["OPENDUNES_API_KEY"]
BASE_URL = "https://opendunes.com/v1"
MODEL = "anthropic/claude-sonnet-4.5"
SYSTEM = (
    "You work alone: nobody will answer a question. Use the tools, "
    "make reasonable choices, and end with a two-line summary."
)
MAX_STEPS = 30

client = OpenAI(base_url=BASE_URL, api_key=API_KEY, max_retries=5)
as_json = "--json" in sys.argv
words = [word for word in sys.argv[1:] if word != "--json"]
piped = "" if sys.stdin.isatty() else sys.stdin.read()
goal = " ".join(words) or piped.strip()


def emit(event):
    if as_json:
        print(json.dumps(event), flush=True)


def read_file(path):
    if not os.path.isfile(path):
        return {"error": f"no file at {path}"}
    with open(path) as file:
        return {"text": file.read()[:20000]}


def write_file(path, content):
    os.makedirs("out", exist_ok=True)
    target = os.path.join("out", os.path.basename(path))
    with open(target, "w") as file:
        file.write(content)
    return {"written": target}


def function_tool(name, description, properties):
    return {
        "type": "function",
        "function": {
            "name": name,
            "description": description,
            "parameters": {
                "type": "object",
                "properties": properties,
                "required": list(properties),
            },
        },
    }


text = {"type": "string"}
tools = [
    function_tool("read_file", "Read a text file.", {"path": text}),
    function_tool(
        "write_file",
        "Write a text file.",
        {"path": text, "content": text},
    ),
]
FUNCTIONS = {"read_file": read_file, "write_file": write_file}


def run(goal):
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": goal},
    ]
    spent = 0.0
    for step in range(MAX_STEPS):
        reply = client.chat.completions.create(
            model=MODEL,
            messages=messages,
            tools=tools,
        )
        spent += reply.usage.cost
        message = reply.choices[0].message
        if not message.tool_calls:
            return message.content, spent
        messages.append(message)
        for call in message.tool_calls:
            name = call.function.name
            args = json.loads(call.function.arguments)
            emit({"type": "tool", "name": name, "args": args})
            messages.append(
                {
                    "role": "tool",
                    "tool_call_id": call.id,
                    "content": json.dumps(FUNCTIONS[name](**args)),
                }
            )
    return None, spent


if not goal:
    print("usage: agent.py [--json] <goal>", file=sys.stderr)
    sys.exit(1)
try:
    answer, spent = run(goal)
except Exception as error:
    emit({"type": "error", "message": str(error)})
    print(error, file=sys.stderr)
    sys.exit(1)
if answer is None:
    emit({"type": "stopped", "reason": "max_steps", "spent": spent})
    sys.exit(2)
emit({"type": "done", "text": answer, "spent": spent})
if not as_json:
    print(answer)

The cURL sample is the first turn: its answer carries the read_file call your code runs.

The library sends a request again, after a wait, when it gets a 408, a 429 or a 5xx: the samples raise it to five tries. A retry sends one turn again, never the run: the tools that already ran stay in the conversation and do not run twice. What each status means: Errors and retries.

Watch out

A process that dies halfway and starts again from the goal runs every tool again, the writes included. For runs longer than a few minutes, save the conversation after every turn and go on from it: Long-horizon agents.

3. Write events for another program

Without --json, the agent prints its final answer and nothing else. With --json, it writes one JSON object per line, as things happen, for a log, a queue, or a dashboard to read.

Illustrative: the charge is an example.

JSON
{
  "type": "done",
  "text": "report.md is written: 41 sales, 3 back orders.",
  "spent": 0.184233
}
typeWritten whenCarries
toola tool is about to runname, args
donethe model answered in wordstext, spent in DADAThe Algerian dinar, the one currency the docs show.More on Balance and charges →
stoppedthe run reached MAX_STEPSreason, spent in DA
errora request failed after its retriesmessage

4. End with an exit code

The exit code tells the calling script how the run ended, without reading a word of the output.

CodeMeansThe script
0the agent finishedmoves on
1a request failed: a 401, a 402, a model not on sale, or no goal givenstops, and tells someone
2the run reached MAX_STEPS before the model finishedraises MAX_STEPS, or splits the goal

A 402 means the balanceBalanceWhat you can spend, in DA.More on Balance and charges → is at zero or below, cannot pay the request's hold, or the key's cap is spent: metadata.limit_source in the error names which (Limits).

5. Run it on a schedule

A scheduler runs the agent like any other command. Keep the key out of the schedule itself: put the export OPENDUNES_API_KEY= line in a file only the agent's user can read, and load it first.

Shell
#!/bin/sh
# nightly.sh, run by cron at 06:00: 0 6 * * * /srv/bookshop/nightly.sh
cd /srv/bookshop || exit 1
. ./agent.env
python3 agent.py --json "Read sales/today.csv and write report.md" \
  >> runs.jsonl
Do

Give the agent an API keyAPI keyThe key you create and send with every request that calls a model.More on API keys → of its own, with a cap. An agent nobody watches stops at the cap with a 402 and exit code 1, and your other keys run on.

What it costs

Each turn is a request of its own, charged as one: usage.cost on its answer, in DA, from your balance. The agent adds the turns up and reports the sum in spent, and Activity, in the app, lists every turn.

The same agent with someone at the keyboard: A terminal agent app.

Last modified on