# 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](#1-take-the-goal-from-the-command-line).
2. [Run the loop to a result](#2-run-the-loop-to-a-result).
3. [Write events for another program](#3-write-events-for-another-program).
4. [End with an exit code](#4-end-with-an-exit-code).
5. [Run it on a schedule](#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 run | The goal is |
|---|---|
| `python agent.py "Read sales/today.csv and write report.md"` | the arguments |
| `cat task.txt \| python agent.py` | what 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](/docs/tools), 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.

```python
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)
```

```javascript
import fs from "node:fs";
import path from "node:path";
import OpenAI from "openai";

const API_KEY = process.env.OPENDUNES_API_KEY;
const BASE_URL = "https://opendunes.com/v1";
const MODEL = "anthropic/claude-sonnet-4.5";
const SYSTEM =
  "You work alone: nobody will answer a question. Use the tools, " +
  "make reasonable choices, and end with a two-line summary.";
const MAX_STEPS = 30;

const client = new OpenAI({
  baseURL: BASE_URL,
  apiKey: API_KEY,
  maxRetries: 5,
});
const asJson = process.argv.includes("--json");
const words = process.argv.slice(2).filter((word) => word !== "--json");
const piped = process.stdin.isTTY ? "" : fs.readFileSync(0, "utf8");
const goal = words.join(" ") || piped.trim();

function emit(event) {
  if (asJson) console.log(JSON.stringify(event));
}

const functions = {
  read_file({ path: file }) {
    if (!fs.existsSync(file)) return { error: `no file at ${file}` };
    return { text: fs.readFileSync(file, "utf8").slice(0, 20000) };
  },
  write_file({ path: file, content }) {
    fs.mkdirSync("out", { recursive: true });
    const target = path.join("out", path.basename(file));
    fs.writeFileSync(target, content);
    return { written: target };
  },
};

const functionTool = (name, description, properties) => ({
  type: "function",
  function: {
    name,
    description,
    parameters: {
      type: "object",
      properties,
      required: Object.keys(properties),
    },
  },
});

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

async function run(goal) {
  const messages = [
    { role: "system", content: SYSTEM },
    { role: "user", content: goal },
  ];
  let spent = 0;
  for (let step = 0; step < MAX_STEPS; step++) {
    const reply = await client.chat.completions.create({
      model: MODEL,
      messages,
      tools,
    });
    spent += reply.usage.cost;
    const message = reply.choices[0].message;
    if (!message.tool_calls?.length) return { answer: message.content, spent };
    messages.push(message);
    for (const call of message.tool_calls) {
      const name = call.function.name;
      const args = JSON.parse(call.function.arguments);
      emit({ type: "tool", name, args });
      messages.push({
        role: "tool",
        tool_call_id: call.id,
        content: JSON.stringify(functions[name](args)),
      });
    }
  }
  return { answer: null, spent };
}

if (!goal) {
  console.error("usage: agent.mjs [--json] <goal>");
  process.exit(1);
}
try {
  const { answer, spent } = await run(goal);
  if (answer === null) {
    emit({ type: "stopped", reason: "max_steps", spent });
    process.exit(2);
  }
  emit({ type: "done", text: answer, spent });
  if (!asJson) console.log(answer);
} catch (error) {
  emit({ type: "error", message: String(error) });
  console.error(String(error));
  process.exit(1);
}
```

```go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"slices"
	"strconv"
	"strings"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
)

const (
	baseURL = "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."
	maxSteps = 30
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	client := openai.NewClient(
		option.WithBaseURL(baseURL),
		option.WithAPIKey(apiKey),
		option.WithMaxRetries(5),
	)

	words := slices.DeleteFunc(slices.Clone(os.Args[1:]), func(w string) bool {
		return w == "--json"
	})
	goal := strings.Join(words, " ")
	if stat, _ := os.Stdin.Stat(); goal == "" &&
		stat.Mode()&os.ModeCharDevice == 0 {
		piped, _ := io.ReadAll(os.Stdin)
		goal = strings.TrimSpace(string(piped))
	}
	if goal == "" {
		fmt.Fprintln(os.Stderr, "usage: agent [--json] <goal>")
		os.Exit(1)
	}

	answer, spent, err := run(client, goal)
	if err != nil {
		emit(map[string]any{"type": "error", "message": err.Error()})
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if answer == nil {
		emit(map[string]any{
			"type": "stopped", "reason": "max_steps", "spent": spent,
		})
		os.Exit(2)
	}
	emit(map[string]any{"type": "done", "text": *answer, "spent": spent})
	if !asJSON {
		fmt.Println(*answer)
	}
}

var asJSON = slices.Contains(os.Args[1:], "--json")

func run(client openai.Client, goal string) (*string, float64, error) {
	text := map[string]any{"type": "string"}
	params := openai.ChatCompletionNewParams{
		Model: model,
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.SystemMessage(system),
			openai.UserMessage(goal),
		},
		Tools: []openai.ChatCompletionToolUnionParam{
			functionTool("read_file", "Read a text file.",
				map[string]any{"path": text}),
			functionTool("write_file", "Write a text file.",
				map[string]any{"path": text, "content": text}),
		},
	}
	spent := 0.0
	for step := 0; step < maxSteps; step++ {
		reply, err := client.Chat.Completions.New(context.TODO(), params)
		if err != nil {
			return nil, spent, err
		}
		cost := reply.Usage.JSON.ExtraFields["cost"].Raw()
		charge, _ := strconv.ParseFloat(cost, 64)
		spent += charge
		message := reply.Choices[0].Message
		if len(message.ToolCalls) == 0 {
			return &message.Content, spent, nil
		}
		params.Messages = append(params.Messages, message.ToParam())
		for _, call := range message.ToolCalls {
			var args struct{ Path, Content string }
			json.Unmarshal([]byte(call.Function.Arguments), &args)
			emit(map[string]any{"type": "tool", "name": call.Function.Name,
				"args": json.RawMessage(call.Function.Arguments)})
			result := runTool(call.Function.Name, args.Path, args.Content)
			toolMessage := openai.ToolMessage(result, call.ID)
			params.Messages = append(params.Messages, toolMessage)
		}
	}
	return nil, spent, nil
}

func runTool(name, path, content string) string {
	var result map[string]string
	if name == "read_file" {
		raw, err := os.ReadFile(path)
		result = map[string]string{"text": string(raw)}
		if err != nil {
			result = map[string]string{"error": "no file at " + path}
		}
	} else {
		os.MkdirAll("out", 0o755)
		target := filepath.Join("out", filepath.Base(path))
		os.WriteFile(target, []byte(content), 0o644)
		result = map[string]string{"written": target}
	}
	out, _ := json.Marshal(result)
	return string(out)
}

func emit(event map[string]any) {
	if asJSON {
		line, _ := json.Marshal(event)
		fmt.Println(string(line))
	}
}

func functionTool(
	name, description string,
	properties map[string]any,
) openai.ChatCompletionToolUnionParam {
	required := []string{}
	for key := range properties {
		required = append(required, key)
	}
	return openai.ChatCompletionFunctionTool(openai.FunctionDefinitionParam{
		Name:        name,
		Description: openai.String(description),
		Parameters: openai.FunctionParameters{
			"type":       "object",
			"properties": properties,
			"required":   required,
		},
	})
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
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."
GOAL="Read sales/today.csv and write report.md"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "system",
        "content": "'"$SYSTEM"'"
      },
      {
        "role": "user",
        "content": "'"$GOAL"'"
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "read_file",
          "description": "Read a text file.",
          "parameters": {
            "type": "object",
            "properties": {
              "path": {
                "type": "string"
              }
            },
            "required": ["path"]
          }
        }
      }
    ]
  }'
```

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](/docs/errors-and-retries).

<div class="watch-out">
<p>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: <a href="/docs/cookbook/long-horizon-agents">Long-horizon agents</a>.</p>
</div>

## 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
}
```

| `type` | Written when | Carries |
|---|---|---|
| `tool` | a tool is about to run | `name`, `args` |
| `done` | the model answered in words | `text`, `spent` in DA |
| `stopped` | the run reached `MAX_STEPS` | `reason`, `spent` in DA |
| `error` | a request failed after its retries | `message` |

## 4. End with an exit code

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

| Code | Means | The script |
|---|---|---|
| `0` | the agent finished | moves on |
| `1` | a request failed: a 401, a 402, a model not on sale, or no goal given | stops, and tells someone |
| `2` | the run reached `MAX_STEPS` before the model finished | raises `MAX_STEPS`, or splits the goal |

A 402 means the balance 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](/docs/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.

```bash
#!/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
```

<div class="do">
<p>Give the agent an API key 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.</p>
</div>

## 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](/docs/cookbook/a-terminal-agent-app).
