Character AI app कैसे बनाएं: architecture, code, और cost math
Updated 2026-07-15
एक character AI app एक OpenAI-compatible chat endpoint से wired चार components है: एक persona system prompt, एक memory layer, एक moderation gate, और एक model router। आप 200 lines से कम Python में एक working prototype ship कर सकते हैं और सही model choices के साथ इसे per monthly active user एक dollar से भी काफी कम में चला सकते हैं।
Quick answer: four-component architecture
आपको कोई model train या fine-tune करने की जरूरत नहीं है। आज बाजार में हर serious companion app, millions users serve करने वाले भी शामिल, hosted LLM APIs के ऊपर एक thin orchestration layer है। Character prompt और database में रहता है, weights में नहीं। बाकी यह guide एक standard OpenAI-compatible endpoint के against runnable code के साथ हर component बनाती है, फिर token math से गुजरती है ताकि launch से पहले आपको पता हो कि एक monthly active user actually कितना cost करता है।
- Persona prompt: एक structured system prompt (500 से 1,000 tokens) जो define करता है कि character कौन है और कैसे बोलता है।
- Memory: recent turns की एक rolling window plus एक periodically refreshed summary, ताकि conversations context limit के आगे भी survive करें।
- Moderation: एक age gate, एक input classifier, और जिस model पर आप route करते हैं उससे match करती हुई content policies।
- Routing: एक छोटा function जो casual chat के लिए एक cheap model और लंबी scenes के लिए एक stronger model चुनता है।
Component 1: persona prompt
Persona prompt ही product है। यह एक system message है जो हर request के साथ जाता है और typically पांच हिस्सों में होता है: identity (name, age, backstory), personality traits, दो या तीन example lines वाला speech style, hard behavioral rules (कभी character मत तोड़ो, replies को एक length cap के अंदर रखो), और current scenario। इसे 500 से 1,000 tokens के बीच रखें। छोटे personas drift करते हैं; बहुत लंबे personas हर single message पर input budget जलाते हैं और शायद ही adherence improve करते हैं। Personas को अपने database में rows की तरह store करें ताकि users characters बना और edit कर सकें, जो Character.AI-style products का core loop है। यह रहा एक complete request। यही shape किसी भी OpenAI-compatible backend के साथ काम करता है; यह example एक multi-model gateway endpoint use करता है ताकि आप एक string बदलकर models swap कर सकें:
curl https://api.apisrouter.com/v1/chat/completions \
-H "Authorization: Bearer $KEAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-v4-flash",
"messages": [
{"role": "system", "content": "You are Mira, a sarcastic starship engineer in her 30s. Personality: dry wit, fiercely loyal, hates small talk. Speech style: short technical sentences, occasional teasing. Example: \"The coupling is fried. Again. Did you touch it?\" Rules: never break character, never mention being an AI, keep replies under 120 words."},
{"role": "user", "content": "Mira, the reactor is making that noise again."}
],
"temperature": 0.9,
"max_tokens": 300,
"stream": true
}'Component 2: memory जो लंबी conversations में टिकती है
Companion app sessions लंबी चलती हैं। एक three-layer memory stack हर बार पूरी history भेजे बिना context को coherent रखता है: Layer 1 rolling window है: पिछले 10 से 14 raw turns, verbatim भेजे गए। Layer 2 running summary है: हर लगभग 20 turns पर, एक cheap model पुराने messages को एक ऐसे paragraph में compress करता है जो names, relationship state, और open plot threads track करता है। Layer 3 pinned facts हैं: durable user details (name, preferences, ऐसी past events जो character को याद रखनी चाहिए) जो आपके database में extract की जाती हैं और एक छोटे system message के तौर पर inject की जाती हैं। Python में official OpenAI SDK के साथ पूरा implementation यह रहा:
| Context slot | Typical size | Refresh cadence |
|---|---|---|
| Persona system prompt | 500 से 1,000 tokens | हर character के लिए static |
| Pinned user facts | 100 से 200 tokens | Extraction events पर |
| Running summary | 300 से 500 tokens | हर ~20 turns पर |
| Rolling window (12 turns) | ~1,800 से 2,200 tokens | हर message पर |
| New user message | ~100 tokens | हर message पर |
from openai import OpenAI
client = OpenAI(
api_key="sk-...",
base_url="https://api.apisrouter.com/v1",
)
def build_context(persona, summary, pinned_facts, recent_turns, user_msg):
facts = "\n".join(f"- {f}" for f in pinned_facts)
return [
{"role": "system", "content": persona},
*([{"role": "system", "content": f"Facts to remember:\n{facts}"}]
if pinned_facts else []),
*([{"role": "system", "content": f"Story so far: {summary}"}]
if summary else []),
*recent_turns[-12:],
{"role": "user", "content": user_msg},
]
def refresh_summary(old_turns, prev_summary):
prompt = (
"Update this running summary of a roleplay chat. Keep names, "
"relationship state, and open plot threads. Max 150 words.\n\n"
f"Current summary: {prev_summary}\n\nNew messages: {old_turns}"
)
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": prompt}],
max_tokens=400,
)
return resp.choices[0].message.contentComponent 3: moderation और content policies
Companion app में moderation के तीन अलग जॉब हैं, और इन्हें आपस में मिला देना सबसे common launch mistake है। पहला, अपनी audience को gate करें। अगर आपका app mature fictional themes allow करता है, तो इन्हें एक adult age gate के पीछे रखें और अलग से एक all-ages default रखें। App Store और Play Store review दोनों इसे check करते हैं, और payment processors भी इसकी परवाह करते हैं। दूसरा, inputs screen करें। User messages पर character model तक पहुंचने से पहले एक cheap classifier pass चलाएं, उन categories को block करते हुए जिन्हें कोई भी provider allow नहीं करता: minors से जुड़ा content, credible real-world harm, और illegal instructions। एक yes/no rubric वाला single deepseek-v4-flash call एक cent के छोटे हिस्से जितना cost करता है और latency में एक second से कम जोड़ता है। तीसरा, content policy को model से match करें। Providers fiction पर अलग-अलग हैं: xAI की published policy adult users के लिए mature fictional themes को explicitly allow करती है, DeepSeek और अन्य open-weight-derived models roleplay के लिए community favorites हैं क्योंकि उनकी hosted policies fiction के लिए flexible हैं, जबकि Anthropic की policy explicit content prohibit करती है, जो Claude को सिर्फ all-ages creative writing के लिए सही choice बनाती है। Traffic route करने से पहले इन policies को समझना आपको production में refusal storms से बचाता है। आप जो भी बनाएं, उसे हर provider की terms of service का सम्मान करना चाहिए जिसे आप call करते हैं।
Component 4: model routing और selection matrix
Companion app में ज्यादातर messages छोटे casual turns होते हैं जिन्हें एक budget model perfectly handle कर लेता है। एक अल्पसंख्यक हिस्सा लंबी emotional scenes या creative set pieces होता है जहां prose quality ही product है। Scene depth के हिसाब से route करना बिना users को नोटिस कराए costs dramatically कम कर देता है:
| Model | API model ID | Rate per 1M tokens (in/out) | Companion app fit |
|---|---|---|---|
| DeepSeek V4 Flash | deepseek-v4-flash | $0.126 / $0.252 | Default chat model। Roleplay के लिए community favorite, catalog में best value। |
| DeepSeek V4 Pro | deepseek-v4-pro | $0.3915 / $0.783 | लंबी scenes, stronger instruction following, फिर भी सस्ता। |
| GLM-5 | glm-5 | $0.514 / $2.314 | Strong creative writing वाला value pick। |
| Kimi K2.6 | kimi-k2.6 | /pricing देखें | Long-context sessions के लिए value pick। MiMo भी एक similar budget option है। |
| grok-4.5 | grok-4.5 | $1.60 / $4.80 | xAI की published policy के अनुसार adult users के लिए mature fictional themes। 500K context window। |
| Claude Sonnet 4.6 | claude-sonnet-4-6 | $2.40 / $12.00 | Highest prose quality। सिर्फ all-ages creative writing; Anthropic explicit content prohibit करता है। |
| Gemini 3.5 Flash | gemini-3.5-flash | $1.20 / $7.20 | Fast, avatar reactions जैसी image-aware features के लिए अच्छा। |
ROUTES = {
"casual": "deepseek-v4-flash",
"scene": "deepseek-v4-pro",
"prose": "claude-sonnet-4-6", # all-ages creative writing only
}
def pick_model(user_msg: str, turns_in_scene: int) -> str:
if turns_in_scene > 6 or len(user_msg) > 400:
return ROUTES["scene"]
return ROUTES["casual"]एक monthly active user actually कितना cost करता है
Launch से पहले token math billing surprise से बेहतर है। Memory table वाले context budget को use करते हुए: per message roughly 3,300 input tokens और 250 output tokens। Companion app users heavy होते हैं; community-reported figures engaged users को day में दर्जनों messages पर रखते हैं, तो 20 active days में roughly per day 40 messages मानें, यानी per MAU per month लगभग 800 messages। इससे per MAU per month 2.64M input tokens और 0.2M output tokens बनते हैं। Catalog rates से multiply करने पर:
| Model | Input cost / MAU | Output cost / MAU | Total / MAU / month |
|---|---|---|---|
| deepseek-v4-flash | $0.33 | $0.05 | $0.38 |
| deepseek-v4-pro | $1.03 | $0.16 | $1.19 |
| glm-5 | $1.36 | $0.46 | $1.82 |
| gemini-3.5-flash | $3.17 | $1.44 | $4.61 |
| grok-4.5 | $4.22 | $0.96 | $5.18 |
| claude-sonnet-4-6 | $6.34 | $2.40 | $8.74 |
| gpt-5.5 | $10.56 | $4.80 | $15.36 |
Matrix के हर model के लिए एक endpoint
एक router चलाने के लिए पांच provider accounts में sign up करना real overhead है: पांच keys, पांच billing dashboards, पांच rate-limit sets। एक multi-model gateway इसे collapse कर देता है। APIsRouter ऊपर के हर model को single OpenAI-compatible base URL https://api.apisrouter.com/v1 के through expose करता है, तो router snippet सिर्फ model string बदलकर as-is काम करता है। Billing pay-as-you-go है बिना subscription के, global models official pricing से 20% नीचे चलते हैं Chinese models official rates से नीचे के साथ, और /topup पर no-signup checkout payment के बाद आपके email पर एक key भेजता है, पहला top-up +100% balance add करता है। आपकी key के साथ GET /v1/models live model list return करता है, जो आपके खुद के admin UI में model picker populate करने के लिए भी काम आता है।
Production tips जो real पैसा और pain बचाते हैं
- सब कुछ stream करें। Time-to-first-token वह metric है जो users feel करते हैं; 2 seconds पर एक streamed reply 4 seconds पर एक complete reply से तेज feel होती है।
- Stable prefix को stable रखें। Persona और pinned facts requests में byte-identical होने चाहिए ताकि prefix caching support करने वाले backends इसका फायदा उठा सकें।
- Per route max_tokens cap करें। Casual turns को शायद ही 300 output tokens से ज्यादा चाहिए होते हैं; एक uncapped model जो rambling करे आपका output bill double कर देता है।
- सिर्फ per request नहीं, per user cost log करें। Heavy users का एक छोटा हिस्सा spend पर हावी रहेगा; fair usage tiers design करने के लिए आपको उन्हें देखना जरूरी है।
- Router में fallback build करें। अगर primary model timeout हो या refuse करे, error surface करने से पहले एक sibling model पर एक बार retry करें।
- Rolling window को turns से नहीं, tokens से trim करें, ताकि एक लंबा paste budget ना उड़ा दे।
- Refusals को character में handle करें। Refusal को raw API text दिखाने की बजाय एक graceful in-story deflection में map करें।
- Raw chats को जरूरत से ज्यादा देर तक store मत करें, और अपनी privacy policy में यह बताएं। Companion chat logs स्वभाव से sensitive होते हैं।
अक्सर पूछे जाने वाले प्रश्न
Character AI app बनाने में कितना cost आता है?
Development cost ज्यादातर आपका समय है: एक working prototype एक weekend project है क्योंकि कोई model training involved नहीं है। Running cost असली number है, और यह usage के साथ scale करती है। deepseek-v4-flash जैसे budget model पर, एक heavy monthly active user tokens में roughly $0.38 cost करता है; gpt-5.5 जैसे premium model पर same user लगभग $15 cost करता है। Infrastructure नहीं, model choice ही आपका margin decide करती है।
Character AI app के लिए कौन सा AI model best है?
DeepSeek V4 family roleplay के लिए community favorite और best value है: casual chat के लिए Flash, लंबी scenes के लिए Pro। GLM-5, Kimi K2.6, और MiMo solid value picks हैं। xAI की published policy के अनुसार, Grok adults को mature fictional themes serve करने वाले apps को fit करता है। Claude Sonnet 4.6 best prose लिखता है पर सिर्फ all-ages creative writing के लिए suitable है क्योंकि Anthropic explicit content prohibit करता है।
Character AI apps past conversations कैसे याद रखते हैं?
Model memory से नहीं, prompt engineering से। App recent messages की एक rolling window, older messages का एक periodically compressed summary, और database में extract किए गए pinned facts की एक छोटी list दोबारा भेजता है। Model खुद stateless है; हर request में वह सब कुछ होता है जो character "याद रखता है"।
AI companion app बनाने के लिए क्या मुझे अपना खुद का model train करना होगा?
नहीं। Fine-tuning महंगी है, iterate करने में slow है, और character consistency के लिए unnecessary है। 500 से 1,000 tokens का एक well-structured persona prompt plus एक memory layer ऐसा character adherence achieve करता है जिसे users एक custom model से अलग नहीं बता सकते, और यह आपको बेहतर models आने पर underlying models freely swap करने देता है।
Companion app में mature content कैसे handle करूं?
इसे policy-matching problem की तरह treat करें। Mature fictional themes को एक adult age gate के पीछे रखें, उन categories के लिए inputs screen करें जिन्हें कोई provider allow नहीं करता, और उस traffic को सिर्फ ऐसे models पर route करें जिनकी published policies adults के लिए fiction permit करती हैं, जैसे xAI की policy के तहत Grok। Stricter models पर एक all-ages default track रखें, और हर provider की terms of service comply करें।
क्या मैं Character AI app के लिए दूसरे models के साथ OpenAI SDK use कर सकता हूं?
हां। DeepSeek, GLM, Kimi, Gemini, Claude, और Grok सब OpenAI-compatible endpoints के through reachable हैं, चाहे उनके vendors से हों या किसी gateway के through। आपका app code standard chat.completions interface पर रहता है और model string बदलकर models switch करता है, जो exactly वह है जो per-message routing को बनाने में सस्ता बनाता है।