Server Integration
This guide shows how to integrate LoreMind with popular backend platforms. Choose the pattern that matches your stack.
Prerequisites
- A Server Key (
sk_server_*): see Authentication. It lives on your backend, never in game builds - An authenticated source of
playerId, required for rate limiting, memory, and conversation tracking - Your backend platform's tooling (Nakama, PlayFab, Node.js, or a custom C# service)
Why Use a Backend?
Your backend:
- Keeps API keys secure - Never expose keys in game builds
- Identifies players - Provide
playerId(required) for rate limiting, memory, and conversation tracking - Adds your own logic - Custom rate limiting, validation, logging, analytics
Important: The LoreMind API key must never be in your game client. Only your backend should have it.
See Backend Integration for a simpler getting-started guide.
Timeouts
The first request after a period of inactivity can take much longer than usual, sometimes minutes. LoreMind allows up to 600 seconds per request.
Every timeout between the player's game and LoreMind must be at least 600 seconds, or a slow first reply turns into an error:
- The game's request to your backend
- Your backend's HTTP client, calling LoreMind
- Your function's or server's own request timeout
- Any load balancer, API gateway, CDN, or reverse proxy in front of your backend
Defaults that are shorter than 600 seconds:
| Where | Setting | Default | What to do |
|---|---|---|---|
Node.js fetch | headersTimeout and bodyTimeout (undici) | 300 s | Pass an undici Agent set to 600 s (see the Node.js example) |
.NET HttpClient | Timeout | 100 s | Set to 600 s |
Unity UnityWebRequest | timeout | 0 (no timeout) | Leave at 0, or set 600 or more |
| Nakama server runtime | nk.httpRequest timeout argument | 5,000 ms | Pass 600,000 ms |
| Nakama server | socket.write_timeout_ms | 10,000 ms | Set to 600,000 ms so RPCs called over HTTP can answer |
| Nakama Unity client | client.Timeout | 10 s | Set to 600 s, with UnityWebRequestAdapter (see the Nakama example) |
| Google Cloud Run | Request timeout | 300 s | Set to 600 s or more (maximum 3,600 s) |
| Cloud Run functions, Firebase Functions | Function timeout | 60 s | Set to 600 s or more on the current generation (HTTP maximum 60 minutes). 1st gen stops at 540 s, so it can't wait long enough |
| AWS Lambda | Function timeout | 3 s | Set to 600 s or more |
| Amazon API Gateway, REST API | Integration timeout | 29 s | Regional and private APIs: request a quota increase above 29 s. Edge-optimized APIs can't be raised |
| Amazon API Gateway, HTTP API | Integration timeout | 30 s maximum | Can't wait long enough; put a different front end on this route |
| AWS Application Load Balancer | Connection idle timeout | 60 s | Set to 600 s or more |
| Google Cloud Application Load Balancer | Backend service timeout | 30 s | Set to 600 s or more |
| nginx | proxy_read_timeout | 60 s | Set to 600s or more |
| Cloudflare proxy | Proxy Read Timeout | 125 s | Only Enterprise zones can raise it |
| Azure Functions, HTTP trigger | Response limit | 230 s maximum | Can't wait long enough; host the LoreMind call elsewhere |
| PlayFab CloudScript | Execution limits | 10 s (4 s for classic CloudScript) | Can't wait long enough; see the PlayFab example |
Pass LoreMind's Response Through
Return LoreMind's response to your game unchanged: the same status code, the same JSON body, and the Retry-After header when there is one. Your game needs all three to tell a reply from a 503 Lore unavailable, a 402 Insufficient credits, or a 429 Rate limit exceeded, and to know when to try again. The full list is in the POST /npc/interact reference.
- Never substitute canned NPC lines. LoreMind never answers an NPC without its lore, so a failed request has no reply to show. Your backend shouldn't invent one either: show the player that the NPC can't answer right now.
- If LoreMind doesn't answer at all (your timeout fired or the connection dropped), return your own error status, such as
502, not NPC dialogue.
Retries
If your backend retries, retry only a 503 that carries a Retry-After header. Wait at least that many seconds, then send the same request again, a limited number of times.
Never retry a timeout or a dropped connection. LoreMind may have finished the first request, charging for it and storing any memories it made. Retry in one place, your backend or your game, not both, or the attempts multiply.
Serving the Unity SDK? Don't retry in your backend. The SDK already retries a 503 that carries Retry-After: it waits exactly that delay and tries again, up to 3 attempts in all, then reports LORE_UNAVAILABLE to the game. Pass the 503 and its Retry-After header through unchanged and let the SDK do it. See Timeouts and Retries.
The examples below don't retry: they pass every LoreMind response, including a 503, through to the game.
Integration Patterns
With the Unity SDK, the simplest game client is the SDK's own CustomBackendTransport: it sends the NPC's full context, conversation history and Active Knowledge Tags, plus your player's session token as Authorization: Bearer <token> once you set its token provider. Your backend verifies the token, derives playerId from it (never from the request body), adds the Server Key, and forwards the body. See Backend Setup.
The Unity clients below build their own requests from npc.Context instead. npc.Context holds only what your code set: global time of day, world events and auto-sensed nearby characters and objects are merged into a separate copy for each request, so add them yourself if you send npc.Context directly.
Nakama is an open-source game server supporting realtime multiplayer, matchmaking, and server-side logic. LoreMind integrates via Nakama's TypeScript runtime.
Register the RPC
// main.ts
const InitModule: nkruntime.InitModule = function(
ctx: nkruntime.Context,
logger: nkruntime.Logger,
nk: nkruntime.Nakama,
initializer: nkruntime.Initializer
) {
initializer.registerRpc('npc_interact', rpcNpcInteract);
logger.info('LoreMind NPC module loaded');
};
const LOREMIND_URL = 'https://loremind.peekgames.dev/api/loremind/v1/npc/interact';
const LOREMIND_API_KEY = 'sk_server_your_key_here'; // Placeholder: load from your server's env/config, never hardcode
const LOREMIND_TIMEOUT_MS = 600000; // LoreMind allows up to 600 s per requestNPC Interaction RPC
const rpcNpcInteract: nkruntime.RpcFunction = function(
ctx: nkruntime.Context,
logger: nkruntime.Logger,
nk: nkruntime.Nakama,
payload: string
): string {
const request = JSON.parse(payload);
const playerId = ctx.userId; // Nakama user ID from authenticated session
// Client sends context from Unity scene; the server just forwards it
const body = JSON.stringify({
text: request.message,
entityMindId: request.entityMindId,
playerId: playerId, // Server provides authenticated player ID
memory: { retrieve: true },
context: request.context // Context comes from client (LocationZone, ContextTag, etc.)
});
// Call LoreMind. A timeout or dropped connection throws and fails the RPC:
// don't retry it (LoreMind may have finished it).
const response = nk.httpRequest(LOREMIND_URL, 'post', {
'Content-Type': 'application/json',
'Authorization': `Bearer ${LOREMIND_API_KEY}`
}, body, LOREMIND_TIMEOUT_MS);
if (response.code !== 200) {
logger.error(`LoreMind error: ${response.code} ${response.body}`);
}
// An RPC can't set its own HTTP status or headers, so return LoreMind's
// status, Retry-After header and JSON body to the client unchanged.
// Nakama gives each response header as a list of values.
const headers = response.headers as unknown as { [name: string]: string[] };
const retryAfter = headers['Retry-After'] ? headers['Retry-After'][0] : null;
return JSON.stringify({
status: response.code,
retryAfter: retryAfter,
body: response.body
});
};Nakama server configuration
The Unity client calls the RPC over HTTP, and Nakama cuts an HTTP response off after socket.write_timeout_ms (10 seconds by default). Raise it to 600 seconds:
# Nakama config file
socket:
write_timeout_ms: 600000Unity Client (with Nakama)
The client gathers context from the scene using SDK components (LocationZone, ContextTag, etc.) and sends it to the server. It waits up to 600 seconds for the RPC and makes one attempt only, so a slow LoreMind request is never sent twice:
using Nakama;
using Peek.LoreMind;
public class NpcClient : MonoBehaviour
{
private IClient _client;
private ISession _session;
[SerializeField] private LoreMindNPC npc;
private void Awake()
{
// UnityWebRequestAdapter applies client.Timeout to each request
_client = new Client("https", "nakama.yourgame.com", 7350, "defaultkey",
UnityWebRequestAdapter.Instance);
_client.Timeout = 600; // Seconds: LoreMind can take this long after a quiet period
}
public async Task<NpcRpcResult> TalkToNpc(string message)
{
// Client builds context from scene state
var payload = new
{
entityMindId = npc.EntityMindId,
message = message,
context = new
{
location = npc.Context.location,
locationDetails = npc.Context.locationDetails,
timeOfDay = npc.Context.timeOfDay,
weather = npc.Context.weather,
nearbyCharacters = npc.Context.nearbyCharacters,
playerAppearance = npc.Context.playerAppearance,
recentEvents = npc.Context.recentEvents
}
};
// One attempt: don't repeat a LoreMind request blindly
var noRetries = new RetryConfiguration(500, 0); // 500 ms base delay, no retries
var response = await _client.RpcAsync(_session, "npc_interact",
JsonConvert.SerializeObject(payload), noRetries);
// LoreMind's own status, Retry-After and body. On 200, body holds the reply;
// on an error such as 503 Lore unavailable, show that the NPC can't answer right now.
return JsonConvert.DeserializeObject<NpcRpcResult>(response.Payload);
}
}
public class NpcRpcResult
{
public int status; // LoreMind's HTTP status code
public string retryAfter; // LoreMind's Retry-After header, if any (seconds)
public string body; // LoreMind's JSON body, unchanged
}Resources:
PlayFab is Microsoft's game backend.
Don't call LoreMind from CloudScript. PlayFab stops waiting for a CloudScript function after 10 seconds when the game calls it through ExecuteFunction (CloudScript using Azure Functions), and after 4 seconds for classic CloudScript. A LoreMind reply after a quiet period takes far longer, so CloudScript turns it into an error.
Instead, keep PlayFab for player login, and call LoreMind from a server you run that can wait 600 seconds, such as the Custom Node.js example. That server checks the player's PlayFab session ticket with Server/AuthenticateSessionTicket and uses their PlayFab ID as playerId. (An HTTP-triggered Azure Function can't host it either: it must respond within 230 seconds.)
Verify the PlayFab player (Express middleware)
Use this as the authenticatePlayer middleware in the Custom Node.js example:
// playfab-auth.ts
import type { Request, Response, NextFunction } from 'express';
const PLAYFAB_TITLE_ID = process.env.PLAYFAB_TITLE_ID;
const PLAYFAB_SECRET_KEY = process.env.PLAYFAB_SECRET_KEY; // Title secret key, server only
export async function authenticatePlayer(req: Request, res: Response, next: NextFunction) {
const sessionTicket = req.get('X-PlayFab-SessionTicket');
if (!sessionTicket) {
return res.status(401).json({ error: 'Missing session ticket' });
}
const response = await fetch(
`https://${PLAYFAB_TITLE_ID}.playfabapi.com/Server/AuthenticateSessionTicket`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-SecretKey': PLAYFAB_SECRET_KEY
},
body: JSON.stringify({ SessionTicket: sessionTicket })
}
);
const result = await response.json();
if (!response.ok || result.data.IsSessionTicketExpired) {
return res.status(401).json({ error: 'Invalid session ticket' });
}
req.player = { id: result.data.UserInfo.PlayFabId };
next();
}Unity Client (with PlayFab)
The game logs in with PlayFab as usual, then sends its session ticket to your server with each NPC request:
using System.Text;
using UnityEngine.Networking;
using Peek.LoreMind;
public class NpcClient : MonoBehaviour
{
[SerializeField] private LoreMindNPC npc;
// From your PlayFab login result (LoginResult.SessionTicket)
public string SessionTicket { get; set; }
public async Task<UnityWebRequest> TalkToNpc(string message)
{
// Client builds context from scene state
var payload = new
{
entityMindId = npc.EntityMindId,
message = message,
context = new
{
location = npc.Context.location,
locationDetails = npc.Context.locationDetails,
timeOfDay = npc.Context.timeOfDay,
nearbyCharacters = npc.Context.nearbyCharacters,
playerAppearance = npc.Context.playerAppearance
}
};
var request = new UnityWebRequest("https://api.yourgame.com/api/npc/interact", "POST");
request.uploadHandler = new UploadHandlerRaw(
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload)));
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("X-PlayFab-SessionTicket", SessionTicket);
request.timeout = 600; // Seconds: LoreMind can take this long after a quiet period
var operation = request.SendWebRequest();
while (!operation.isDone)
{
await Task.Yield();
}
// LoreMind's own status code, JSON body and Retry-After header, passed through by your server.
// On an error such as 503 Lore unavailable, show that the NPC can't answer right now.
return request;
}
}Resources:
For studios with custom backends using Express, Fastify, or similar frameworks.
Express Server
// server.ts
import express from 'express';
import { createClient } from 'redis';
import { fetch, Agent } from 'undici';
const app = express();
const redis = createClient();
const LOREMIND_API_KEY = process.env.LOREMIND_API_KEY;
// LoreMind allows up to 600 s per request.
// Node's fetch stops waiting after 300 s by default, so wait longer.
const loremindAgent = new Agent({ headersTimeout: 600_000, bodyTimeout: 600_000 });
app.use(express.json());
// Your auth middleware (Steam, Epic, PlayFab, custom JWT)
app.use('/api/npc', authenticatePlayer);
app.post('/api/npc/interact', async (req, res) => {
const playerId = req.player.id; // From your auth middleware
const { entityMindId, message, context } = req.body; // Context comes from client
// Rate limiting
const rateKey = `npc:rate:${playerId}`;
const count = await redis.incr(rateKey);
if (count === 1) await redis.expire(rateKey, 60);
if (count > 10) {
return res.status(429).json({ error: 'RATE_LIMITED' });
}
// Client sends context from Unity scene; the server adds playerId and forwards it
let response;
try {
response = await fetch(
'https://loremind.peekgames.dev/api/loremind/v1/npc/interact',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${LOREMIND_API_KEY}`
},
body: JSON.stringify({
text: message,
entityMindId: entityMindId,
playerId: playerId, // Server provides authenticated player ID
memory: { retrieve: true },
context: context // Context comes from client
}),
dispatcher: loremindAgent
}
);
} catch (error) {
// No answer from LoreMind (timeout or dropped connection). Don't retry:
// LoreMind may have finished it. Return an error, never NPC lines.
console.error('LoreMind request failed:', error);
return res.status(502).json({ error: 'LoreMind did not respond' });
}
const body = await response.text();
if (response.ok) {
// Analytics
analytics.track('npc_interaction', {
playerId,
entityMindId
});
} else {
console.error('LoreMind error:', response.status, body);
}
// Pass LoreMind's status, Retry-After header and JSON body through unchanged
const retryAfter = response.headers.get('Retry-After');
if (retryAfter) res.set('Retry-After', retryAfter);
res.status(response.status).type('application/json').send(body);
});undici is the HTTP client behind Node's built-in fetch; install it with npm install undici to pass it an Agent. If this server sits behind a load balancer, reverse proxy, or serverless platform, raise those timeouts to 600 seconds too (see Timeouts).
For games using Mirror networking with a backend that calls external APIs.
Backend Service (C#)
// NpcService.cs - runs on your backend
public class LoreMindResult
{
public int Status; // LoreMind's HTTP status code
public string Body; // LoreMind's JSON body, unchanged
public string RetryAfter; // LoreMind's Retry-After header, if any (seconds)
}
public class NpcService
{
private readonly HttpClient _http;
public NpcService(string apiKey)
{
_http = new HttpClient
{
BaseAddress = new Uri("https://loremind.peekgames.dev/api/loremind/v1/"),
// LoreMind allows up to 600 s per request
Timeout = TimeSpan.FromSeconds(600)
};
_http.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
}
public async Task<LoreMindResult> GetResponse(NpcRequest request)
{
// Client sends context; the server adds playerId and forwards it
var payload = new
{
text = request.Message,
entityMindId = request.EntityMindId,
playerId = request.PlayerId, // Server provides authenticated player ID
memory = new { retrieve = true },
context = request.Context // Context comes from client
};
var json = JsonSerializer.Serialize(payload);
var content = new StringContent(json, Encoding.UTF8, "application/json");
// A timeout or dropped connection throws. Don't retry it:
// LoreMind may have finished it.
var response = await _http.PostAsync("npc/interact", content);
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
Debug.LogError($"LoreMind error: {response.StatusCode} {body}");
}
return new LoreMindResult
{
Status = (int)response.StatusCode,
Body = body,
RetryAfter = response.Headers.RetryAfter?.ToString()
};
}
}Mirror NetworkBehaviour
// NpcInteraction.cs
using Peek.LoreMind;
public class NpcInteraction : NetworkBehaviour
{
[SerializeField] private LoreMindNPC npc;
private static NpcService _npcService;
[Server]
public static void InitializeService(string apiKey)
{
_npcService = new NpcService(apiKey);
}
// Client calls this Command, sending context from their scene
[Command]
public void CmdTalkToNpc(string message, RuntimeContext context)
{
var player = connectionToClient.identity.GetComponent<Player>();
StartCoroutine(HandleNpcRequest(player, message, context));
}
[Server]
private IEnumerator HandleNpcRequest(Player player, string message, RuntimeContext context)
{
var request = new NpcRequest
{
PlayerId = player.PlayerId,
EntityMindId = npc.EntityMindId,
Message = message,
Context = context // Context came from client
};
var task = _npcService.GetResponse(request);
yield return new WaitUntil(() => task.IsCompleted);
if (task.IsFaulted)
{
// No answer from LoreMind: report an error, never a made-up line
TargetReceiveResult(connectionToClient, 502, "{\"error\":\"LoreMind did not respond\"}", null);
yield break;
}
// Pass LoreMind's status, body and Retry-After to the client unchanged
var result = task.Result;
TargetReceiveResult(connectionToClient, result.Status, result.Body, result.RetryAfter);
}
[TargetRpc]
private void TargetReceiveResult(NetworkConnection conn, int status, string body, string retryAfter)
{
if (status == 200)
{
var reply = JsonUtility.FromJson<NpcReply>(body);
DialogueUI.Instance.ShowResponse(reply.response);
}
else
{
// For example 503 Lore unavailable: show that the NPC can't answer right now,
// and let the player try again after retryAfter seconds
DialogueUI.Instance.ShowUnavailable(status, retryAfter);
}
}
}
[Serializable]
public class NpcReply
{
public string response;
public string character;
}
// Client-side: gather context and send to server
public class NpcInteractionClient : MonoBehaviour
{
[SerializeField] private LoreMindNPC npc;
[SerializeField] private NpcInteraction networkNpc;
public void TalkToNpc(string message)
{
// Client builds context from scene state and sends to server
networkNpc.CmdTalkToNpc(message, npc.Context);
}
}Resources:
Request & Response Format
Whatever the platform, the call to LoreMind is the same: POST /npc/interact with text, entityMindId, and your authenticated playerId, plus optional context, memory.retrieve, conversationHistory and activeKnowledgeTags. Full request and response schemas, every context field, and the complete error table live in the POST /npc/interact reference.
Troubleshooting
- The first request after a quiet period fails, later ones work: a timeout shorter than 600 seconds sits somewhere between your game and LoreMind. Check every layer in Timeouts.
401 Invalid API keyor403 Invalid authentication: you're using an Editor Key or an incomplete key; this endpoint needs the full Server Key (sk_server_*)400 Unknown knowledge tags: none of the request'sactiveKnowledgeTagsexist on the Entity Mind, so LoreMind made no reply and charged nothing. Retrying won't help: fix the tags, see Unknown Knowledge Tags429 Rate limit exceeded: wait per theRetry-Afterheader; defaults and configuration are in Errors & Rate Limits503 Lore unavailable: the NPC's lore couldn't be searched, so LoreMind made no reply and charged nothing. WaitRetry-Afterseconds and try again; see Lore Unavailable503 Generation failed: the language model failed to reply, and nothing was charged. Show the player that the NPC can't answer right now and let them try again; never substitute a canned line
The full error reference is Errors & Rate Limits.
Next Steps
- Authentication - Set up API keys
- Long-Term Memory - Player memory across sessions
- Entity Minds - Configure NPC personalities