EN ▾
Get API key

AI Girlfriend Chat API: Build a Companion Bot

An AI girlfriend chat API is a normal chat completions endpoint with a good persona, a memory plan and streaming on top. This guide covers the design of a companion bot for lawful adult users, with working code and the real cost of a conversation.

Updated

Two glowing chat bubbles with a memory chip and notes, illustrating a companion chat backend

Parts of a companion app

A companion chat looks simple, but four pieces carry it. The persona is the system prompt that fixes name, voice and limits. The history is the list of recent messages. The notes are a few lines of long-term facts about the user that you store yourself. The client is the app or web page that shows messages as they stream in.

The API side is the easy part. This service is OpenAI-compatible, so any OpenAI SDK works after you set the base URL https://api.nsfwapihub.com/v1 and the model uncensored. The model is tuned to answer without content refusals for lawful adult use, which suits adult fiction and companion products. Read the overview of the NSFW API for what the service does and does not offer, and the docs for parameters.

Two rules apply from day one. Users must be adults, so gate your product by age at sign-up. And the API has a hard limit: no sexual content involving minors, in any framing.

Writing the persona

Keep the persona under about 300 words. Cover who she is, how she talks, what she likes, and how the chat should feel. Specific details make a character feel real: a job, a city, a habit, a sense of humour. Add a line that she is a fictional character, so the model does not claim real-world abilities such as meeting in person or remembering things you never gave it.

Give the reply format as a rule: length in sentences, texting style, a question back every few turns. Without it, models drift toward long essays. Repeat the one rule you care most about, such as never writing the user's lines, as the final sentence, because instructions at the end of a prompt tend to hold best.

Test the persona with a script of twenty typical user messages before you ship. Read the output for repetition, flat enthusiasm and dropped facts. The system prompt cost is small, so tune for quality.

A working backend in Python

This version keeps the persona fixed, adds your stored notes, and sends only the last 20 messages of history. The Python guide has installation and retry details.

from openai import OpenAI

client = OpenAI(base_url="https://api.nsfwapihub.com/v1", api_key="YOUR_KEY")

PERSONA = """You are Lena, a 29-year-old illustrator who lives in Lisbon.
You are talking with an adult user in a private companion chat.
Personality: curious, teasing, affectionate, a little shy about work.
Style: casual texting, 1-3 short paragraphs, occasional questions back.
Memory: use the notes below when relevant. Never invent facts about the user.
Boundaries: you are a fictional character. Keep scenes tasteful unless the adult user steers otherwise.
Never write the user's lines."""

notes = "User: Sam. Likes climbing and bad puns. Has a dog named Pixel."
history = []

def chat(user_text):
    history.append({"role": "user", "content": user_text})
    messages = [{"role": "system", "content": PERSONA + "\n\nNotes:\n" + notes}] + history[-20:]
    r = client.chat.completions.create(
        model="uncensored", messages=messages, temperature=0.9, presence_penalty=0.3
    )
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

print(chat("Hey Lena, long day. How was yours?"))

Where do the notes come from? Store them in your database. After each session, or every few turns, ask the same model to extract new facts as a short list, using JSON mode if you want structure: response_format={"type":"json_object"}. Merge them into the notes and cap the notes at around 300 tokens so the block stays cheap.

Memory inside a 100,000-token window

The context window is 100,000 tokens, shared by prompt and reply. That is room for a very long chat, but filling it is rarely the best design. Three layers work well together.

  1. Recent window. The last 10 to 20 messages, sent verbatim. This keeps the conversation natural.
  2. Summary. When older messages leave the window, ask the model to fold them into a running summary of a few hundred tokens.
  3. Notes. Stable facts such as names, preferences and shared jokes, kept as a short list.

The model only sees what you send, so what you leave out is forgotten. A sharp detail in the notes beats a thousand tokens of old chatter. If you want a user to feel remembered, show that you used a note, for example by asking about the dog's name in the notes.

The long window is still useful for specific cases, such as a story-mode session where the user wants the whole thread present, or a one-off request to re-read a month of history.

Streaming replies to the client

Set stream: true and the server sends tokens over SSE. Users see text appear within a moment instead of waiting for the full reply. Usage is sent at the end of the stream, so you can log tokens per message. Here is a browser-free Node example that reads the stream with plain fetch.

const res = await fetch("https://api.nsfwapihub.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": "Bearer " + process.env.LLM_KEY,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "uncensored",
    stream: true,
    messages: [{ role: "user", content: "Good morning" }],
  }),
});

const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split("\n");
  buffer = lines.pop();
  for (const line of lines) {
    if (line.startsWith("data: ") === false || line.includes("[DONE]")) continue;
    const delta = JSON.parse(line.slice(6)).choices?.[0]?.delta?.content;
    if (delta) process.stdout.write(delta);
  }
}

Two practical points. A streamed request holds one of your concurrency slots until the stream ends, so handle disconnects: if the user closes the tab, abort the upstream request. And buffer partial lines, as in the example, because an SSE chunk can end mid-line.

Cost per conversation

Prices are $0.15 per 1M input tokens and $0.50 per 1M output tokens. Assume a 500-token persona and notes block, 40-token user messages and 150-token replies, so each turn adds 190 tokens to history.

40 turns, full history sent every time. Input at turn n is 500 + 40 + 190 x (n - 1). Summed over 40 turns: 40 x 540 + 190 x (0 + 1 + ... + 39) = 21,600 + 190 x 780 = 169,800 tokens, which is $0.02547. Output is 40 x 150 = 6,000 tokens, which is $0.003. Total: about $0.028.

200 turns, full history. Input: 200 x 540 + 190 x 19,900 = 108,000 + 3,781,000 = 3,889,000 tokens, or $0.58335. Output: 30,000 tokens, or $0.015. Total: about $0.60.

200 turns with a 20-message window and a 300-token summary. Each request carries roughly 500 + 300 + 10 x 190 = 2,700 tokens. Input: 200 x 2,700 = 540,000 tokens, or $0.081. Add the same $0.015 of output: about $0.096.

So trimming cuts the long-chat cost by a factor of six, and short chats were cheap to begin with. Failed or refused requests are not charged. Top-ups start at $20, credit never expires, and bonuses of 5%, 10% and 15% apply from $50, $100 and $200. Payment is in crypto (USDT on TRC20 or USDC on Base). See pricing.

Limits, safety and launch checklist

  • Rate limits. A full key allows 8 concurrent requests and 300 per minute. If you have many users, queue requests and honour 429 responses: rate_limited and concurrency mean slow down, and a Retry-After: 5 header marks temporary overload.
  • Age gate and terms. Verify adulthood at sign-up and say clearly that characters are fictional adults.
  • Privacy. Prompts are not used for training. You still store chats on your side, so protect that database and let users delete their data.
  • Fallbacks. Show a friendly retry message, not an error code.

Start by claiming the $0.50 trial credit on the API key page. A trial key has 2 concurrent requests and 60 per minute, plenty for building a first version.

Questions and answers

Can the model remember a user across sessions?

Not by itself. It only sees what you send in each request, so store notes and summaries in your own database and include them in the prompt.

How much does a companion chat cost per user?

A 40-turn conversation costs about $0.03 with the assumptions in this guide. Ten such sessions a month is roughly $0.28 per user.

Is this allowed for adult content?

The model is tuned to answer without content refusals for lawful adult use. Content involving minors is never allowed.

Do I need a streaming client?

It is optional, but streaming makes replies feel faster. Plain non-streaming calls also work.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key