API Documentation
Contents
Quick Start
Get an NPC talking in under 60 seconds:
Or use MCP for Claude Code native integration: ainpc mcp-serve | View on npm
Authentication
CLI (recommended): Headers are automatic after login.
ainpc login --key YOUR_KEY --game my-rpg # All subsequent commands auto-include credentials
REST API (direct): Two headers required on every request:
| Header | Description |
|---|---|
x-api-key | Your API key |
x-game-id | Your game identifier (tenant isolation) |
Create NPC
POST /api/npcs
{
"name": "Grok the Blacksmith",
"role": "merchant",
"faction": "village_guard",
"location": "blacksmith_shop",
"personality": {
"traits": ["gruff", "honest", "protective"],
"speechStyle": "gruff",
"backstory": "Former soldier who retired to smithing",
"values": ["honor", "craft", "family"],
"quirks": ["always mentions the weather"]
},
"inventory": [
{ "item": "iron_sword", "price": 50, "quantity": 2 },
{ "item": "shield", "price": 30, "quantity": 1 }
]
}
The response carries the NPC's id. To keep an id your game already uses, send it as "id" (a UUID): the NPC is created under that id, and a second create with the same id in the same game answers 409 with code npc_exists and changes nothing, so a re-seed is safe to retry.
Send Event
POST /api/npcs/:npcId/event
{
"type": "player_dialogue",
"playerId": "player_joe",
"message": "Do you have any swords for sale?",
"context": {
"location": "blacksmith_shop",
"timeOfDay": "morning",
"weather": "sunny",
"playerReputation": 75,
"playerLevel": 12
}
}
Response:
{
"response": {
"dialogue": "Aye lad, got a fine iron blade. Fifty gold.",
"emotion": "cheerful",
"action": { "type": "gesture", "target": "display_rack" },
"tradeOffer": { "item": "iron_sword", "price": 45 },
"memoryUpdated": true
},
"tokenUsage": { "input": 1200, "output": 85, "calls": 1 }
}
Errors: an unknown npcId returns 404 { "error": "NPC not found" }. If the NPC could not answer this turn, the status is 503 and the result carries an error object ({ "code": "no_experts" | "experts_failed", "message": "..." }) — safe to retry, and not counted as an interaction. Plan and billing errors are listed under Errors & Limits.
WebSocket
Connect to wss://ainpcengine.com/ws?apiKey=YOUR_KEY&gameId=YOUR_GAME. The WebSocket takes the same API key as REST and counts against the same plan limits: every event it serves is one interaction.
Send:
{ "action": "event", "data": { "type": "player_dialogue", "npcId": "...", "playerId": "...", "message": "...", "context": {...} } }
{ "action": "subscribe", "npcIds": ["npc1", "npc2"] }
{ "action": "unsubscribe", "npcIds": ["npc1"] }
Receive:
{ "type": "connected", "gameId": "my-game" }
{ "type": "typing", "npcId": "...", "playerId": "..." }
{ "type": "response", "data": { "response": { "dialogue": "...", "emotion": "..." }, ... } }
{ "type": "subscribed", "npcIds": ["npc1", "npc2"] }
{ "type": "error", "message": "...", "code": "event_rate", "retryAfter": 12 }
typing arrives as soon as an event is accepted, so you can show the NPC thinking; response follows with the same result as Send Event. A turn the NPC could not answer arrives as a response whose data.error is set. An error message means the event was refused; its code is one of event_rate (wait retryAfter seconds), interaction_cap or payment_required, as under Errors & Limits.
If the server closes the connection, the close code says why:
| Close code | Meaning |
|---|---|
4001 | The API key was not accepted |
4002 | No gameId was given |
4003 | No active subscription (an error message with payment_required and a paymentUrl comes first) |
Update NPC
PATCH /api/npcs/:npcId — Update any NPC properties (partial update).
curl -X PATCH https://ainpcengine.com/api/npcs/{npcId} \
-H "x-api-key: your-key" \
-H "x-game-id: my-game" \
-H "Content-Type: application/json" \
-d '{"location": "town_square", "mood": {"emotion": "angry", "intensity": 0.8, "cause": "theft"}}'
NPC Mind
GET /api/npcs/:npcId/mind — the NPC's schedule, psychology, beliefs and knowledge.
{
"schedule": { "slots": [ { "activity": "working the forge", "location": "forge", "startHour": 8, "endHour": 18 } ] },
"psychology": { "stress": 0.2, "goals": [...], "emotions": [...], "trauma": [...] },
"beliefs": [ { "subject": "the mayor", "proposition": "is hiding something", "confidence": 0.6 } ],
"knowledge": [ { "topic": "the old mine", "content": "The east shaft collapsed last winter." } ]
}
PUT /api/npcs/:npcId/mind/:section — replace one section (schedule, psychology, beliefs or knowledge). The body is the section itself: an object for schedule and psychology, an array for beliefs and knowledge. A save replaces the whole section, so read it, change it, and send it back.
curl -X PUT https://ainpcengine.com/api/npcs/{npcId}/mind/knowledge \
-H "x-api-key: your-key" \
-H "x-game-id: my-game" \
-H "Content-Type: application/json" \
-d '[{"topic": "the old mine", "content": "The east shaft collapsed last winter."}]'
Which sections you can edit depends on your plan: GET /api/npcs-editable returns one true/false per section, and a section outside your plan returns 402 with code: "feature_not_in_plan". GET /api/npc-roles lists the roles an NPC can have.
Reset Memory
Make NPCs forget, and keep who they are. A reset removes what an NPC has built up by being played: what it knows and feels about each player, its conversation history, and its current mood. Its name, persona, schedule, psychology, beliefs and knowledge stay exactly as you wrote them. Use it to wipe test play before launch or to start a new season. It cannot be undone.
DELETE /api/npcs/:npcId/memory — reset one NPC.
POST /api/npcs/memory/purge — reset a set of NPCs ({"npcIds": [...]}, up to 2,000 per request) or every NPC of the game ({"all": true}).
curl -X POST https://ainpcengine.com/api/npcs/memory/purge \
-H "x-api-key: your-key" \
-H "x-game-id: my-game" \
-H "Content-Type: application/json" \
-d '{"npcIds": ["npc_abc123", "npc_def456"]}'
{
"forgottenAt": "2026-11-30T16:20:05.113Z",
"npcs": 2,
"erased": { "relationships": 14, "states": 2, "moods": 1 },
"remaining": [],
"unknown": [],
"done": true
}
From forgottenAt on, the NPCs recall nothing from before that moment; turns played after it are remembered as usual. unknown lists ids that are not NPCs of this game.
A large reset is done in steps. While done is false, send the request again with the ids in remaining (or "all": true again) and the forgottenAt you were given, until done is true. Passing forgottenAt keeps the reset at the same moment, so nothing played in between is lost:
{"npcIds": ["npc_def456"], "forgottenAt": "2026-11-30T16:20:05.113Z"}
A reset is not an interaction and is not counted against your plan. An NPC that has been reset carries the moment as memorySince when you read it.
In the Studio
On the NPCs page: open an NPC and choose Reset memory; tick several NPCs and choose Reset memory in the bar that appears; or choose Reset all memory for every NPC of the game. Each one asks for a second click before it runs.
From the SDKs
Each SDK has the three resets and sends the repeat requests for you, so one call covers any number of NPCs:
// Unity (C#)
MemoryResetResult r = await client.ResetNPCMemory(npcId);
await client.ResetMemory(new[] { "npc_abc123", "npc_def456" });
await client.ResetAllMemory();
// Unreal (C++): the answer arrives on OnMemoryReset
Client->ResetNPCMemory(NpcId);
Client->ResetMemory(NpcIds, TEXT(""));
Client->ResetAllMemory(TEXT(""));
# Godot (GDScript)
var r = await client.reset_npc_memory(npc_id)
await client.reset_memory(["npc_abc123", "npc_def456"])
await client.reset_all_memory()
// Node.js
await client.resetNPCMemory(npcId);
await client.resetMemory(['npc_abc123', 'npc_def456']);
await client.resetMemory('all');
// Rust
client.reset_npc_memory(npc_id).await?;
client.reset_memory(MemoryResetTarget::Npcs(ids), None).await?;
client.reset_memory(MemoryResetTarget::All, None).await?;
Each returns the same result as the API. Requires Unity, Unreal and Godot SDK 1.4.0, Node.js SDK 1.2.0, Rust SDK 0.3.0.
Generate NPC
POST /api/npcs/generate — AI-generate an NPC with full persona, psychology, and schedule.
curl -X POST https://ainpcengine.com/api/npcs/generate \
-H "x-api-key: your-key" \
-H "x-game-id: my-game" \
-H "Content-Type: application/json" \
-d '{"role": "merchant", "name": "Grok"}'
Returns a full NPC with cognitive extensions: persona (OCEAN personality, backstory, fears, ambitions), schedule (daily routines), and psychology (stress, trauma, goals, emotions).
Batch Generate
POST /api/npcs/generate-batch — Generate multiple NPCs with social relationships.
curl -X POST https://ainpcengine.com/api/npcs/generate-batch \
-H "x-api-key: your-key" \
-H "x-game-id: my-game" \
-H "Content-Type: application/json" \
-d '{"count": 5, "role": "guard"}'
Returns { npcs: [...], socialLinks: [...] } — NPCs plus auto-generated relationships between them.
Batch Events
POST /api/events — Send multiple events in one request.
{
"events": [
{ "type": "player_dialogue", "npcId": "npc1", "playerId": "p1", "message": "Hello!", "context": {...} },
{ "type": "player_approached", "npcId": "npc2", "playerId": "p1", "context": {...} }
]
}
Returns { results: [EventResult, ...] } — one result per event, in order. The status is 200 when at least one event was served; per-event failures are flagged via that result's error field ({ "code": "npc_not_found", ... }). If no NPC in the batch could answer, the status is 503. Only the events that were served count as interactions.
Errors & Limits
Every error is JSON with a readable error message; plan and billing errors add a code your game can branch on. Requests that fail are not counted as interactions.
| Status | Code | Meaning | Also in the body |
|---|---|---|---|
401 | — | Missing or invalid API key | |
402 | payment_required | No active subscription | paymentUrl |
402 | npc_limit | Your plan's NPC count is reached | plan, limit, current, upgradeUrl |
402 | feature_not_in_plan | The feature is not part of your plan | plan, upgradeUrl |
429 | interaction_cap | This month's interactions are used up | plan, limit, used, upgradeUrl |
429 | event_rate | Too many events this minute | retryAfter (seconds, also the Retry-After header), limit |
400 | invalid_field | An NPC edit was rejected | field |
503 | experts_failed, no_experts | The NPC could not answer this turn; safe to retry | the code sits in error.code of the result |
Every account is on a paid plan; there is no free tier or trial. Until the subscription is active, API calls return 402 payment_required with the link to finish signing up. Plans and limits: pricing.
Unity SDK
Copy Assets/Plugins/AINPCEngine/ from the Unity demo repo into your project's Assets/Plugins/ folder. SDK version 1.3.0.
var client = new NPCEngineClient("https://ainpcengine.com", "key", "my-game");
// Talk to an NPC
var result = await client.Say(npcId, "player1", "Hello!", context);
Debug.Log(result.response.dialogue);
// AI-generate an NPC with full persona
var npc = await client.GenerateNPC(new GenerateNPCRequest { role = "merchant" });
// Batch-generate NPCs with relationships
var batch = await client.GenerateBatch(new GenerateBatchRequest { count = 5, role = "guard" });
// Send batch events
var results = await client.SendBatchEvents(new BatchEventItem[] { ... });
// Read and edit what the NPC knows
NPCMind mind = await client.GetMind(npcId);
await client.SaveKnowledge(npcId, new[] {
new KnowledgeFact { topic = "the old mine", content = "The east shaft collapsed last winter." }
});
// Errors are typed
try { await client.Say(npcId, "player1", "Hello!", context); }
catch (AINPCError ex) {
if (ex.IsPaymentRequired) Debug.LogWarning(ex.PaymentUrl); // no active subscription
else if (ex.IsRateLimited) Debug.LogWarning(ex.RetryAfterSeconds); // too many events this minute
else if (ex.IsQuotaExceeded) Debug.LogWarning(ex.UpgradeUrl); // month's interactions used up
}
// Real-time, with the same key
var ws = new NPCWebSocketClient("wss://ainpcengine.com/ws", "key", "my-game");
ws.OnTyping += t => ShowThinking(t.npcId);
ws.OnResponse += r => Debug.Log(r.response.dialogue);
ws.OnServerError += e => Debug.LogWarning(e.code);
await ws.Connect();
git clone https://github.com/jyswee/ainpc-unity-demo.git
View on GitHub
Unreal SDK
Copy Plugins/AINPCEngine/ from the Unreal demo repo into your project's Plugins/ folder and enable it in the Plugin Manager. Plugin version 1.3.0.
// Create client
UNPCEngineClient* Client = NewObject<UNPCEngineClient>();
Client->Init("https://ainpcengine.com", "key", "my-game");
// Bind response delegate
Client->OnEventResult.AddDynamic(this, &AMyActor::OnNPCResponse);
// Talk to an NPC
FGameContext Context;
Context.Location = "blacksmith_shop";
Context.TimeOfDay = "morning";
Client->Say(NpcId, "player1", "Got any swords?", Context);
// AI-generate an NPC
FGenerateNPCRequest GenReq;
GenReq.Role = "merchant";
Client->GenerateNPC(GenReq);
// Read and edit what the NPC knows
Client->OnMindReceived.AddDynamic(this, &AMyActor::OnMind);
Client->GetMind(NpcId);
Client->SaveMindSection(NpcId, "knowledge",
TEXT("[{\"topic\":\"the old mine\",\"content\":\"The east shaft collapsed last winter.\"}]"));
// Errors are typed: Error.Code, Error.IsPaymentRequired, Error.IsRateLimited,
// Error.RetryAfterSeconds, Error.PaymentUrl, Error.UpgradeUrl
Client->OnApiError.AddDynamic(this, &AMyActor::OnNPCApiError);
// Real-time, with the same key
UNPCWebSocketClient* Socket = NewObject<UNPCWebSocketClient>();
Socket->OnTyping.AddDynamic(this, &AMyActor::OnNPCTyping);
Socket->OnResponse.AddDynamic(this, &AMyActor::OnNPCResponse);
Socket->OnApiError.AddDynamic(this, &AMyActor::OnNPCApiError);
Socket->Connect("wss://ainpcengine.com/ws", "key", "my-game");
Full Blueprint support — all methods are BlueprintCallable and responses fire BlueprintAssignable delegates.
git clone https://github.com/jyswee/ainpc-unreal-demo.git
View on GitHub
Godot SDK
Copy addons/ainpcengine/ from the Godot demo repo into your project's addons/ folder. Enable in Project → Project Settings → Plugins. Addon version 1.3.0, for Godot 4.
var client = AINPCEngineClient.new()
client.setup("https://ainpcengine.com", "key", "my-game")
add_child(client)
# Talk to an NPC
var context = AINPCModels.game_context("blacksmith", "morning", "sunny")
var result = await client.say(npc_id, "player1", "Got any swords?", context)
if AINPCEngineClient.is_error(result):
# result.code: payment_required, event_rate (wait result.retry_after),
# interaction_cap, npc_limit, feature_not_in_plan, experts_failed, network_error
push_warning(result.error)
else:
print(result.response.dialogue)
# AI-generate an NPC
var npc = await client.generate_npc("merchant", "Grok")
# Read and edit what the NPC knows
var mind = await client.get_mind(npc.id)
await client.save_knowledge(npc.id, mind.knowledge + [
{"topic": "the old mine", "content": "The east shaft collapsed last winter."}])
# Real-time, with the same key
var ws = AINPCWebSocket.new()
add_child(ws)
ws.typing.connect(func(npc_id, _player_id): show_thinking(npc_id))
ws.response_received.connect(func(r): print(r.response.dialogue))
ws.server_error.connect(func(e): push_warning(e.get("code", "")))
ws.connect_to_server("wss://ainpcengine.com/ws", "key", "my-game")
Every call uses Godot 4 await and returns a Dictionary (or an Array for lists); a failed call returns an error Dictionary instead of raising.
git clone https://github.com/jyswee/ainpc-godot-demo.git
View on GitHub
Rust SDK
Add to your Cargo.toml:
[dependencies]
ainpc-sdk = { git = "https://github.com/jyswee/ainpc-rust-sdk.git" }
use ainpc_sdk::{AINPCClient, GameContext};
#[tokio::main]
async fn main() {
let client = AINPCClient::new("https://ainpcengine.com", "key", "my-game");
// Talk to an NPC
let result = client.say("npc_1", "player_1", "Hello!", GameContext {
location: Some("village".into()),
time_of_day: Some("morning".into()),
weather: Some("sunny".into()),
player_reputation: 75,
player_level: 5,
..Default::default()
}).await.unwrap();
println!("NPC: {}", result.response.dialogue.unwrap_or_default());
}
Full REST client + WebSocket support. WASM-compatible (gate WebSocket behind native feature).
git clone https://github.com/jyswee/ainpc-rust-sdk.git
View on GitHub
Node.js / REST API
Node.js SDK: npm i ainpcengine — or use any HTTP client. All endpoints accept JSON with x-api-key and x-game-id headers.
const API = "https://ainpcengine.com/api";
const HEADERS = {
"Content-Type": "application/json",
"x-api-key": "your-api-key",
"x-game-id": "my-game"
};
// Create an NPC
const npc = await fetch(`${API}/npcs`, {
method: "POST",
headers: HEADERS,
body: JSON.stringify({
name: "Grok", role: "blacksmith",
personality: {
traits: ["gruff", "loyal"],
speechStyle: "blunt, short sentences",
backstory: "Third-gen smith",
values: ["craftsmanship", "honor"],
quirks: []
}
})
}).then(r => r.json());
// Talk to the NPC
const result = await fetch(`${API}/npcs/${npc.id}/event`, {
method: "POST",
headers: HEADERS,
body: JSON.stringify({
type: "player_dialogue",
playerId: "player_1",
message: "Got any swords?",
context: { location: "forge", timeOfDay: "morning" }
})
}).then(r => r.json());
console.log(result.response.dialogue);
Works with Node.js, Python, Go, or any language with HTTP support. See Agent Quickstarts for AI coding agent integration.
CLI (npm)
Command-line interface for coding agents and quick testing. Zero dependencies.
npm install -g ainpc-cli # Setup ainpc login --key YOUR_KEY --game my-rpg # Create NPC ainpc create "Grok" --role merchant --traits gruff,loyal # Talk to NPC ainpc say NPC_ID "Got any swords?" # AI-generate full NPC (NPC Persona) ainpc generate --role guard # List all NPCs ainpc list # Full reference ainpc --help
Config stored in .ainpc/config.json (project-local) or ~/.ainpc/config.json (global). Supports --json flag for machine-readable output.
Use the ainpc CLI for NPC management. Config auto-loaded from .ainpc/config.json or AINPC_API_KEY env.
View on npm
Event Types
| Event | Experts | Use When |
|---|---|---|
player_approached | Dialogue + Social | Player enters NPC range |
player_dialogue | Dialogue | Player speaks to NPC |
combat_started | Combat + Dialogue | Fight begins |
trade_requested | Trade + Dialogue | Player wants to buy/sell |
quest_accepted | Quest + Dialogue | Player takes a quest |
quest_completed | Quest + Social + Dialogue | Player finishes quest |
ambient_trigger | Ambient | Idle/background behavior |
world_event | Ambient + Social | Weather change, explosion, etc. |
npc_interaction | Social + Dialogue | NPC-to-NPC interaction |
<custom> | Dialogue | Any custom type string (e.g. bigHand, blunder) — routes to the Dialogue expert and stays in-character |
context to make the NPC react in-character to a specific beat on any event type:
context.situation— what is happening right now, in plain text (e.g."The player just slew the dragon — react big"). This anchors the scene.context.style— a per-event voice/style directive that reinforces the seeded personality (e.g."gruff, short sentences; never breaks the fourth wall").context.playerName— display name to address the player by (playerIdstays the stable memory key).context.language— per-event output language as a BCP-47 tag (e.g."en","vi","pt-BR"). Omit and the NPC infers its own language from the persona; set it and the NPC is hard-pinned to that language for this event. The same NPC can speak its native language on one surface and English on another without forking its memory.
DELETE your pilot NPCs and re-create them, rather than promoting the ones you tested with.