# A terminal agent app

Build a chat agent that runs in your terminal: it streams its answer, runs your tools, and shows what each turn cost.

1. [Install the library](#1-install-the-library).
2. [Read a line, stream the answer](#2-read-a-line-stream-the-answer).
3. [Run the tools the model calls](#3-run-the-tools-the-model-calls).
4. [Show what each turn cost](#4-show-what-each-turn-cost).
5. [Add what your app needs](#5-add-what-your-app-needs).

## 1. Install the library

The app is one file on the OpenAI library, with no terminal framework: it reads a line, prints the answer as it arrives, and loops.

| Tab | Install line | Run |
|---|---|---|
| Python | `pip install openai` | `python agent.py` |
| JavaScript | `npm install openai` | `node agent.mjs` |
| Go | `go get github.com/openai/openai-go/v3` | `go run .` |

Put your key in `OPENDUNES_API_KEY` first, in the terminal the app runs in ([API keys](/docs/api-keys)).

## 2. Read a line, stream the answer

Each line you type becomes a `user` message. The app sends the whole conversation with `stream` set to `true`, and prints each piece of the answer as it arrives ([Streaming](/docs/streaming)). Two commands never reach the model: `/cost` prints the session's charge so far, `/exit` quits.

Sofiane keeps his shop's price lists in text files. His terminal agent reads them and answers his questions about them.

```python
import json
import os
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 help in a terminal. Use read_file to read files."
MAX_STEPS = 10

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)


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]}


tools = [
    {
        "type": "function",
        "function": {
            "name": "read_file",
            "description": "Read a text file.",
            "parameters": {
                "type": "object",
                "properties": {"path": {"type": "string"}},
                "required": ["path"],
            },
        },
    }
]


def stream_turn(messages):
    stream = client.chat.completions.create(
        model=MODEL,
        messages=messages,
        tools=tools,
        stream=True,
    )
    text, calls, cost = "", {}, 0.0
    for chunk in stream:
        if chunk.usage:
            cost = chunk.usage.cost
        if not chunk.choices:
            continue
        delta = chunk.choices[0].delta
        if delta.content:
            print(delta.content, end="", flush=True)
            text += delta.content
        for part in delta.tool_calls or []:
            empty = {"id": "", "name": "", "args": ""}
            call = calls.setdefault(part.index, empty)
            call["id"] = part.id or call["id"]
            if part.function:
                call["name"] = part.function.name or call["name"]
                call["args"] += part.function.arguments or ""
    message = {"role": "assistant", "content": text or None}
    if calls:
        message["tool_calls"] = [
            {
                "id": call["id"],
                "type": "function",
                "function": {"name": call["name"], "arguments": call["args"]},
            }
            for call in calls.values()
        ]
    return message, cost


messages = [{"role": "system", "content": SYSTEM}]
session = 0.0

while True:
    line = input("\n> ").strip()
    if line == "/exit":
        break
    if line == "/cost":
        print(f"{session} DA this session")
        continue
    if not line:
        continue
    messages.append({"role": "user", "content": line})
    turn = 0.0
    for step in range(MAX_STEPS):
        message, cost = stream_turn(messages)
        turn += cost
        messages.append(message)
        for call in message.get("tool_calls", []):
            args = json.loads(call["function"]["arguments"] or "{}")
            print(f"\n  -> {call['function']['name']} {args}")
            messages.append(
                {
                    "role": "tool",
                    "tool_call_id": call["id"],
                    "content": json.dumps(read_file(**args)),
                }
            )
        if "tool_calls" not in message:
            break
    session += turn
    print(f"\n  {turn} DA")
```

```javascript
import fs from "node:fs";
import * as readline from "node:readline/promises";
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 help in a terminal. Use read_file to read files.";
const MAX_STEPS = 10;

const client = new OpenAI({ baseURL: BASE_URL, apiKey: API_KEY });
const terminal = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

function readFile({ path }) {
  if (!fs.existsSync(path)) return { error: `no file at ${path}` };
  return { text: fs.readFileSync(path, "utf8").slice(0, 20000) };
}

const tools = [
  {
    type: "function",
    function: {
      name: "read_file",
      description: "Read a text file.",
      parameters: {
        type: "object",
        properties: { path: { type: "string" } },
        required: ["path"],
      },
    },
  },
];

async function streamTurn(messages) {
  const stream = await client.chat.completions.create({
    model: MODEL,
    messages,
    tools,
    stream: true,
  });
  let text = "";
  let cost = 0;
  const calls = [];
  for await (const chunk of stream) {
    if (chunk.usage) cost = chunk.usage.cost;
    const delta = chunk.choices[0]?.delta;
    if (delta?.content) {
      process.stdout.write(delta.content);
      text += delta.content;
    }
    for (const part of delta?.tool_calls ?? []) {
      calls[part.index] ??= { id: "", name: "", args: "" };
      const call = calls[part.index];
      call.id = part.id ?? call.id;
      call.name = part.function?.name ?? call.name;
      call.args += part.function?.arguments ?? "";
    }
  }
  const message = { role: "assistant", content: text || null };
  if (calls.length) {
    message.tool_calls = calls.map((call) => ({
      id: call.id,
      type: "function",
      function: { name: call.name, arguments: call.args },
    }));
  }
  return { message, cost };
}

const messages = [{ role: "system", content: SYSTEM }];
let session = 0;

while (true) {
  const line = (await terminal.question("\n> ")).trim();
  if (line === "/exit") break;
  if (line === "/cost") {
    console.log(`${session} DA this session`);
    continue;
  }
  if (!line) continue;
  messages.push({ role: "user", content: line });
  let turn = 0;
  for (let step = 0; step < MAX_STEPS; step++) {
    const { message, cost } = await streamTurn(messages);
    turn += cost;
    messages.push(message);
    for (const call of message.tool_calls ?? []) {
      const args = JSON.parse(call.function.arguments || "{}");
      console.log(`\n  -> ${call.function.name} ${JSON.stringify(args)}`);
      messages.push({
        role: "tool",
        tool_call_id: call.id,
        content: JSON.stringify(readFile(args)),
      });
    }
    if (!message.tool_calls) break;
  }
  session += turn;
  console.log(`\n  ${turn} DA`);
}

terminal.close();
```

```go
package main

import (
	"bufio"
	"context"
	"encoding/json"
	"fmt"
	"os"
	"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 help in a terminal. Use read_file to read files."
	maxSteps = 10
)

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

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

	path := map[string]any{"type": "string"}
	params := openai.ChatCompletionNewParams{
		Model: model,
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.SystemMessage(system),
		},
		Tools: []openai.ChatCompletionToolUnionParam{
			openai.ChatCompletionFunctionTool(openai.FunctionDefinitionParam{
				Name:        "read_file",
				Description: openai.String("Read a text file."),
				Parameters: openai.FunctionParameters{
					"type":       "object",
					"properties": map[string]any{"path": path},
					"required":   []string{"path"},
				},
			}),
		},
	}

	terminal := bufio.NewScanner(os.Stdin)
	session := 0.0
	for {
		fmt.Print("\n> ")
		if !terminal.Scan() {
			break
		}
		line := strings.TrimSpace(terminal.Text())
		if line == "/exit" {
			break
		}
		if line == "/cost" {
			fmt.Println(session, "DA this session")
			continue
		}
		if line == "" {
			continue
		}
		params.Messages = append(params.Messages, openai.UserMessage(line))
		turn := 0.0
		for step := 0; step < maxSteps; step++ {
			message, cost := streamTurn(client, params)
			turn += cost
			params.Messages = append(params.Messages, message.ToParam())
			for _, call := range message.ToolCalls {
				name, arguments := call.Function.Name, call.Function.Arguments
				fmt.Println("\n  ->", name, arguments)
				var args struct{ Path string }
				json.Unmarshal([]byte(arguments), &args)
				result := openai.ToolMessage(readFile(args.Path), call.ID)
				params.Messages = append(params.Messages, result)
			}
			if len(message.ToolCalls) == 0 {
				break
			}
		}
		session += turn
		fmt.Println("\n ", turn, "DA")
	}
}

func streamTurn(
	client openai.Client,
	params openai.ChatCompletionNewParams,
) (openai.ChatCompletionMessage, float64) {
	stream := client.Chat.Completions.NewStreaming(context.TODO(), params)
	all := openai.ChatCompletionAccumulator{}
	cost := 0.0
	for stream.Next() {
		chunk := stream.Current()
		all.AddChunk(chunk)
		if len(chunk.Choices) > 0 {
			fmt.Print(chunk.Choices[0].Delta.Content)
		}
		if raw, ok := chunk.Usage.JSON.ExtraFields["cost"]; ok {
			cost, _ = strconv.ParseFloat(raw.Raw(), 64)
		}
	}
	if err := stream.Err(); err != nil {
		panic(err)
	}
	return all.Choices[0].Message, cost
}

func readFile(path string) string {
	raw, err := os.ReadFile(path)
	if err != nil {
		return `{"error": "no such file"}`
	}
	text := string(raw)
	if len(text) > 20000 {
		text = text[:20000]
	}
	out, _ := json.Marshal(map[string]string{"text": text})
	return string(out)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
SYSTEM="You help in a terminal. Use read_file to read files."
LINE="What does prices.txt say about the Galaxy A16?"

curl -N "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "stream": true,
    "messages": [
      {
        "role": "system",
        "content": "'"$SYSTEM"'"
      },
      {
        "role": "user",
        "content": "'"$LINE"'"
      }
    ],
    "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 one streamed turn: its pieces carry the words, or the `read_file` call your code runs.

## 3. Run the tools the model calls

A streamed call arrives in pieces too: the call's `id` and name first, then its arguments a few characters at a time, all under the same `index`. The app joins the pieces, and once the stream ends, runs each call and sends the results back ([Tools and function calling](/docs/tools)). The model then streams its answer, or calls again, up to `MAX_STEPS` times for one line.

| A piece's `delta` carries | The app |
|---|---|
| `content` | prints it, and keeps it for the conversation |
| `tool_calls[].id`, `function.name` | starts the call at that `index` |
| `tool_calls[].function.arguments` | adds the characters to that call's arguments |

Go's `ChatCompletionAccumulator` joins the pieces for you.

<div class="watch-out">
<p>Parse a call's arguments only once the stream has ended. Midway, they are half a JSON object.</p>
</div>

## 4. Show what each turn cost

The last piece of each stream carries `usage`, with `usage.cost`: that request's charge in DA. One line can take several requests when the model calls tools, so the app adds them up in `turn` and prints the sum under the answer. `session` holds the total since the app started, and `/cost` prints it.

Illustrative: the question and the charge are an example.

```text
> What does prices.txt say about the Galaxy A16?

  -> read_file {"path": "prices.txt"}
The Galaxy A16 is listed at two prices: the 128 GB model and the 256 GB…

  0.041288 DA
```

## 5. Add what your app needs

| Add | How |
|---|---|
| a tool that writes, deletes or pays | ask before it runs: [Human approval on tool calls](/docs/cookbook/human-approval-on-tool-calls) |
| a session that survives a restart | save the conversation after each turn: [Long-horizon agents](/docs/cookbook/long-horizon-agents) |
| a stronger model to consult | [Review by a stronger model](/docs/cookbook/review-by-a-stronger-model) |
| the same agent with no one at the keyboard | [A headless agent](/docs/cookbook/a-headless-agent) |

<div class="watch-out">
<p>An error after the first piece arrives under a 200: the last piece carries <code>error</code>, and <code>finish_reason</code> reads <code>error</code>. Check for it before you keep the text. What to do on each status: <a href="/docs/errors-and-retries">Errors and retries</a>.</p>
</div>
