---
name: eternal-ai-character-api
description: Use when the user wants to chat with Eternal AI characters or story scenes from code, build a bot, game or app around Eternal characters, or subscribe to a character with diamonds. Covers the Eternal AI Character API (Developer API v1).
---

# Eternal AI - Character API

Chat with Eternal AI characters and story scenes over REST. Replies are asynchronous: send, then poll.

## Before you start

You need an API key (format: `2am_sk_live_...`).

1. Look for it in this order:
   - environment variable `ETERNAL_API_KEY`
   - a `.env` or `.env.local` file in the project
2. If there is none, ask the user to create one at https://eternalai.org/api/keys. Do **not** invent a key.
3. Keep the key server-side. Never put it in browser or mobile code.
4. Subscriptions spend the user’s diamonds. Ask before calling POST /subscriptions.

## Key facts

- Base URL: https://agent.api.eternalai.org/api/dev/v1. It is not the docs host.
- Auth: `Authorization: Bearer 2am_sk_live_...`. Create keys in the API keys dashboard; a key is shown once. Keys are server-side secrets.
- Personal keys act as your own Eternal AI account: same chats, free messages, subscriptions and diamonds as on Eternal (web and mobile). Partner keys act as end users you create, selected with `end_user_id` in the JSON body (POST) or query string (GET); their subscriptions are bought and auto-renewed from your diamonds, and end users get no free messages. The only header is `Authorization`.
- Replies are asynchronous: POST /agents/{username}/messages returns your message; poll GET /agents/{username}/messages?after_id={id} every 2-5s for messages with `role: "assistant"` and `bubbles[]`. Characters may also message first.
- Each character has free messages (shared with Eternal web and mobile). After that the API returns `402 subscription_required`; subscribe with diamonds (POST /subscriptions). Scenes use their host character’s subscription.
- Photos and videos are asynchronous: `media.status` is `locked` (needs a subscription), `processing`, `ready` (has `url`) or `failed`. Unlock a locked one with POST /messages/{id}/unlock (uses the subscription quota, never diamonds; 402 `media_quota_exhausted` when used up), then poll GET /messages/{id} until `ready`. Voice messages are not available.
- Language: no per-request language. PUT /language {language, end_user_id?} saves it (codes from the public GET /api/languages) and sets the reply language. Partner keys must send `end_user_id`.
- POST /subscriptions body: `reference_id` (required, your order id, 8-128 chars of A-Z a-z 0-9 . _ : -), exactly one of `agent_username` or `scene_slug`, `plan` (slug from GET /plans), and `end_user_id` (required with a Partner key, never with a Personal key). Same id + same body returns the stored result and never charges twice; same id + different body is 422 `reference_id_reused`. Look one up with GET /subscription_purchases/{reference_id}.
- Errors: `{"error":{"type","code","message","request_id","details"}}`. Branch on `type` (invalid_request, authentication_error, forbidden, not_found, conflict, payment_required, rate_limited, api_error), show `message`, quote `request_id` (also the X-Request-Id header) to support. `details.retryable` marks safe retries. Every response has X-RateLimit-Limit / -Remaining / -Reset (epoch seconds); 429 and 503 add Retry-After (seconds).
- Rate limit: 120 requests per minute per account. No API fee: you only spend diamonds, at Eternal prices.

## Workflow

1. `GET /agents` (or `GET /scenes`, `GET /flings`) and pick a `username` (or scene / fling `slug`). A fling’s `cta` opens chat via `POST /scenes/{cta.scene_slug}/enter` with `fling_slug`.
2. `POST /agents/{username}/messages` with `{ "text": "..." }`.
3. Poll `GET /agents/{username}/messages?after_id={id}` every 2-5s until a message has `role: "assistant"`; print its `bubbles`.
4. On `402 subscription_required`, tell the user and, with their OK, subscribe (`POST /subscriptions`).
5. For a `locked` photo, once subscribed call `POST /messages/{id}/unlock` (no diamonds), then poll `GET /messages/{id}` until `ready`.
6. Give every purchase your own `reference_id`; after a timeout, retry with the same one or look it up with `GET /subscription_purchases/{reference_id}`.

## Reference cURL

```bash
BASE=https://agent.api.eternalai.org/api/dev/v1
AUTH="Authorization: Bearer $ETERNAL_API_KEY"

# 1. List characters
curl "$BASE/agents?limit=5" -H "$AUTH"

# 2. Send a message (keep its id; needs jq)
ID=$(curl -s -X POST "$BASE/agents/mio_kaneshiro/messages" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d '{"text": "Hey, how was your day?"}' | jq -r .message.id)

# 3. Get the reply (if it's empty, run again in a few seconds)
curl "$BASE/agents/mio_kaneshiro/messages?after_id=$ID" -H "$AUTH"
# -> { "data": [ { "role": "assistant",
#                  "bubbles": ["It was long...", "better now that you're here"] } ] }
```

## Reference Python (send, poll, handle 402)

```python
import os, time, requests

BASE = "https://agent.api.eternalai.org/api/dev/v1"
H = {"Authorization": f"Bearer {os.environ['ETERNAL_API_KEY']}"}

def chat(username, text):
    res = requests.post(f"{BASE}/agents/{username}/messages", headers=H,
                        json={"text": text})
    if res.status_code == 402:
        # Free messages for this character are used up.
        # Subscribe with diamonds (POST /subscriptions) or pick another one.
        raise RuntimeError("subscription_required")
    res.raise_for_status()
    last_id = res.json()["message"]["id"]

    for _ in range(40):
        time.sleep(3)
        data = requests.get(f"{BASE}/agents/{username}/messages", headers=H,
                            params={"after_id": last_id}).json()["data"]
        replies = [m for m in data if m["role"] == "assistant"]
        if replies:
            return replies
    raise TimeoutError("no reply yet")

for reply in chat("mio_kaneshiro", "Hey, how was your day?"):
    print("\n".join(reply["bubbles"]))
    # A locked photo: once subscribed, POST /messages/{id}/unlock (uses
    # the plan's photo quota, no diamonds), then check GET /messages/{id}.
```

## Reference JavaScript (Node 18+)

```javascript
const BASE = "https://agent.api.eternalai.org/api/dev/v1";
const headers = {
  Authorization: `Bearer ${process.env.ETERNAL_API_KEY}`,
  "Content-Type": "application/json",
};
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function chat(username, text) {
  const res = await fetch(`${BASE}/agents/${username}/messages`, {
    method: "POST",
    headers,
    body: JSON.stringify({ text }),
  });
  if (res.status === 402) {
    // Free messages for this character are used up.
    // Subscribe with diamonds (POST /subscriptions) or pick another one.
    throw new Error("subscription_required");
  }
  const { message } = await res.json();

  for (let i = 0; i < 40; i++) {
    await sleep(3000);
    const { data } = await (await fetch(
      `${BASE}/agents/${username}/messages?after_id=${message.id}`,
      { headers },
    )).json();
    const replies = data.filter((m) => m.role === "assistant");
    if (replies.length) return replies;
  }
  throw new Error("no reply yet");
}

for (const reply of await chat("mio_kaneshiro", "Hey, how was your day?")) {
  console.log(reply.bubbles.join("\n"));
  // A locked photo: once subscribed, POST /messages/{id}/unlock (uses
  // the plan's photo quota, no diamonds), then check GET /messages/{id}.
}
```

## Error handling

- 401: missing, invalid or revoked key. Ask the user for a valid key.
- 402 subscription_required: free messages for that character are used up.
- 429 rate_limited: more than 120 requests per minute per account. Wait the Retry-After seconds (X-RateLimit-Remaining / X-RateLimit-Reset show the budget), then retry.
- 400 invalid_reference_id / invalid_target: fix the subscription body (reference_id 8-128 chars; exactly one of agent_username or scene_slug).
- 403 partner_only: the call needs a Partner key.
- No reply after ~2 minutes: stop polling and report it; do not resend in a loop.

## Rules

- 18+ only. Characters are fictional adults.
- No content with minors or real people. We block it.
- Keep keys on your server. Never put one in a mobile or web app.
- Scraping, reselling access or spam gets your key revoked.

## Resources

- Docs: https://eternalai.org/api/docs
- API keys: https://eternalai.org/api/keys
- llms.txt: https://eternalai.org/api/llms.txt
- OpenAPI: https://eternalai.org/api/openapi.json
