# Quickstart chat app

Build a terminal chat that remembers the conversation, streams each answer and adds up its charge.

1. [Start from the Quickstart](#1-start-from-the-quickstart): the key in your environment, the library installed.
2. [Keep the conversation](#2-keep-the-conversation).
3. [Stream each answer](#3-stream-each-answer).
4. [Write the app](#4-write-the-app).
5. [Run it and read what it cost](#5-run-it-and-read-what-it-cost).

## 1. Start from the Quickstart

The app picks up where the [Quickstart](/docs/quickstart) ends: an API key in `OPENDUNES_API_KEY`, the OpenAI library installed, one request sent. Do those five steps first, then come back.

| Value | Set to |
|---|---|
| Base URL | `https://opendunes.com/v1` |
| API key | `OPENDUNES_API_KEY`, in the terminal you run the app from |
| Model | `anthropic/claude-sonnet-4.5` |

## 2. Keep the conversation

The model remembers nothing between two requests. The app keeps the conversation in a list and sends all of it on every turn.

| Role | Holds | Added |
|---|---|---|
| `system` | how the model should behave | once, at the top |
| `user` | the question typed | before each request |
| `assistant` | the model's answer | after each answer |

<div class="dont">
<p>Don't send only the new question. The model loses the thread, and "And on Friday?" means nothing to it.</p>
</div>
<div class="do">
<p>Do add each answer to the list as an <code>assistant</code> turn before the next question.</p>
</div>

Every turn sends the whole conversation again, so each turn reads more tokens than the one before, and costs more. For a long chat, drop the oldest turns and keep the `system` line.

## 3. Stream each answer

With `"stream": true`, the answer arrives in pieces and the app prints each piece as it comes. The last piece carries no words: it carries `usage.cost`, the charge for that turn in DA. [Streaming](/docs/streaming) shows every event.

<div class="good-to-know">
<p>A streamed answer carries no <code>X-Balance-Available</code> header. The turn's charge is in the closing event, and the app adds it to the chat's total.</p>
</div>

## 4. Write the app

An empty line or `exit` ends the chat. The cURL tab sends one turn from inside a conversation: the history the app would send on its second question.

```python
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 a shop in Oran answer its customers. Be brief."

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)
history = [{"role": "system", "content": SYSTEM}]
spent = 0.0

while True:
    question = input("You: ").strip()
    if question in ("", "exit"):
        break
    history.append({"role": "user", "content": question})

    stream = client.chat.completions.create(
        model=MODEL,
        messages=history,
        stream=True,
    )
    answer = ""
    print("Answer: ", end="", flush=True)
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            words = chunk.choices[0].delta.content
            answer += words
            print(words, end="", flush=True)
        if chunk.usage:
            spent += chunk.usage.cost
    print()
    history.append({"role": "assistant", "content": answer})

print(f"This chat cost {round(spent, 6)} DA")
```

```javascript
import OpenAI from "openai";
import * as readline from "node:readline/promises";

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 a shop in Oran answer its customers. Be brief.";

const client = new OpenAI({ baseURL: BASE_URL, apiKey: API_KEY });
const terminal = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
const history = [{ role: "system", content: SYSTEM }];
let spent = 0;

while (true) {
  const question = (await terminal.question("You: ")).trim();
  if (question === "" || question === "exit") break;
  history.push({ role: "user", content: question });

  const stream = await client.chat.completions.create({
    model: MODEL,
    messages: history,
    stream: true,
  });
  let answer = "";
  process.stdout.write("Answer: ");
  for await (const chunk of stream) {
    const words = chunk.choices[0]?.delta?.content;
    if (words) {
      answer += words;
      process.stdout.write(words);
    }
    if (chunk.usage) spent += chunk.usage.cost;
  }
  process.stdout.write("\n");
  history.push({ role: "assistant", content: answer });
}

terminal.close();
console.log(`This chat cost ${spent.toFixed(6)} DA`);
```

```go
package main

import (
	"bufio"
	"context"
	"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 a shop in Oran answer its customers. Be brief."
)

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

	client := openai.NewClient(
		option.WithBaseURL(baseURL),
		option.WithAPIKey(apiKey),
	)
	history := []openai.ChatCompletionMessageParamUnion{
		openai.SystemMessage(system),
	}
	spent := 0.0
	terminal := bufio.NewScanner(os.Stdin)

	for {
		fmt.Print("You: ")
		if !terminal.Scan() {
			break
		}
		question := strings.TrimSpace(terminal.Text())
		if question == "" || question == "exit" {
			break
		}
		history = append(history, openai.UserMessage(question))

		params := openai.ChatCompletionNewParams{
			Model:    model,
			Messages: history,
		}
		stream := client.Chat.Completions.NewStreaming(
			context.TODO(), params,
		)
		answer := ""
		fmt.Print("Answer: ")
		for stream.Next() {
			chunk := stream.Current()
			if len(chunk.Choices) > 0 {
				words := chunk.Choices[0].Delta.Content
				answer += words
				fmt.Print(words)
			}
			if cost, ok := chunk.Usage.JSON.ExtraFields["cost"]; ok {
				charge, _ := strconv.ParseFloat(cost.Raw(), 64)
				spent += charge
			}
		}
		if err := stream.Err(); err != nil {
			panic(err)
		}
		fmt.Println()
		history = append(history, openai.AssistantMessage(answer))
	}

	fmt.Printf("This chat cost %.6f DA\n", spent)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
SYSTEM="You help a shop in Oran answer its customers. Be brief."

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": "Do you deliver to Bir El Djir?" },
      { "role": "assistant", "content": "Yes, within the day." },
      { "role": "user", "content": "And on Friday?" }
    ]
  }'
```

## 5. Run it and read what it cost

Save the Python tab as `chat.py` and run it. Each tab runs the same way in its own language: `node chat.mjs`, `go run chat.go`.

Illustrative: the answers and the charge are an example.

```text
$ python chat.py
You: Do you deliver to Bir El Djir?
Answer: Yes, within the day. Order before 16:00 for an evening drop.
You: And on Friday?
Answer: On Friday we deliver after the midday prayer, until 20:00.
You: exit
This chat cost 0.412776 DA
```

The total is the sum of each turn's `usage.cost`. Each turn is also a line in *Activity*, in the app, with its tokens and its charge. How a request is charged: [Balance and charges](/docs/balance-and-charges).

<div class="watch-out">
<p>At zero or below, or when the balance cannot pay the request's hold, the next turn gets a 402 and the app stops with an error. New requests are refused until a deposit covers what the balance owes: see <a href="/docs/errors-and-retries">Errors and retries</a>.</p>
</div>

Next: [Move to OpenDunes](/docs/cookbook/move-to-opendunes) · [Text](/docs/text) · [Tools](/docs/tools)
