API Reference
Complete reference for the LoreMind Unity SDK. Each API includes practical usage examples.
LoreMindNPC
Namespace: Peek.LoreMind
Main component for NPC intelligence. Attach to any GameObject to enable AI conversations.
RespondAsync
Generate an NPC response to player text.
Task<NPCResponse> RespondAsync(string playerText)
Task<NPCResponse> RespondAsync(string playerText, CancellationToken cancellationToken)Never returns null and never throws for a failed request: a failure comes back as a response with success = false and an error code. See What Happens on Every Request. Player text is limited to 2,000 characters by the server.
Example: Basic conversation
var npc = GetComponent<LoreMindNPC>();
var response = await npc.RespondAsync("What do you know about the dragon?");
if (response.success)
{
dialogueUI.ShowText(response.response);
}
else
{
Debug.LogError($"Error: {response.error} - {response.message}");
}Respond
Fire-and-forget version. Use with events instead of await.
void Respond(string playerText)Example: Event-based dialogue
void Start()
{
npc.OnResponseReceived.AddListener(text => dialogueUI.ShowText(text));
npc.OnError.AddListener(error => Debug.LogError(error));
}
void OnPlayerSpeak(string text)
{
npc.Respond(text);
}SetLocation
Set the NPC's current location context.
void SetLocation(string location, string details = null)Example: Location-aware responses
// Before conversation
npc.SetLocation("The Rusty Anvil Tavern", "Crowded, smell of ale");
var response = await npc.RespondAsync("Is it always this busy?");
// NPC responds knowing they're in a busy tavernSetCustomContext / GetCustomContext / RemoveCustomContext
Manage custom key-value context pairs.
void SetCustomContext(string key, string value)
string GetCustomContext(string key)
void RemoveCustomContext(string key)Example: Quest-aware NPC
// Set quest context
npc.SetCustomContext("active_quest", "Find the missing merchant");
npc.SetCustomContext("player_reputation", "trusted_ally");
var response = await npc.RespondAsync("Any news about missing people?");
// NPC knows about the quest and trusts the player
// Clear when quest completes
npc.RemoveCustomContext("active_quest");ClearConversationHistory
Clear the current conversation. Call when player walks away.
void ClearConversationHistory()Example: Ending a conversation
void OnPlayerLeaveNPC()
{
npc.ClearConversationHistory();
// Next conversation starts fresh
}Key Properties
| Property | Type | Description |
|---|---|---|
EntityMindId | string | Entity Mind to use (required, set in Inspector) |
Context | RuntimeContext | Current situational context |
IsProcessing | bool | True while waiting for response |
LastResponse | string | Most recent reply text (successful replies only) |
LastResponseData | NPCResponse | Most recent response, success or failure |
EnableMemoryRetrieval | bool | Recall what this player said before (needs playerId, added by your backend, and Long-Term Memory on for the project) |
ActiveKnowledgeTags | string[] | Restrict the NPC's lore to these tags (see Active Knowledge Tags) |
AutoSenseNearby | bool | Auto-detect nearby ContextTags |
SyncGlobalContext | bool | Sync with GlobalContextManager |
Events
| Event | Type | When |
|---|---|---|
OnResponseReceived | UnityEvent<string> | A reply arrived (success only) |
OnResponseComplete | UnityEvent<NPCResponse> | A reply arrived, with the full response (success only, after the event above) |
OnError | UnityEvent<string> | The request failed |
OnRequestFinished | UnityEvent<NPCResponse> | Every request, exactly once, last; success or failure (not fired for BUSY) |
OnRequestFinished fires on failures too: check response.success before showing response.response. See What Happens on Every Request.
RuntimeContext
Namespace: Peek.LoreMind.Cloud.Data
Holds situational context for NPC responses.
RuntimeContext Fields
| Field | Type | Description |
|---|---|---|
location | string | Current location name |
locationDetails | string | Location description |
timeOfDay | string | dawn/morning/midday/afternoon/dusk/evening/night/midnight |
weather | string | clear/rainy/stormy/foggy/snowing |
atmosphere | string | peaceful/tense/festive/eerie/somber |
nearbyCharacters | string[] | Visible character names |
nearbyObjects | string[] | Notable objects |
situation | string | shopping/combat/exploring/trading |
recentEvents | string[] | Recent game events |
npcMood | string | cheerful/suspicious/nervous/tired/angry |
npcActivity | string | What NPC is doing |
playerAppearance | string | Player description |
playerReputation | string | How NPC views player |
playerVisibleItems | string[] | Notable player items |
custom | string | Freeform custom context (max 500 chars) |
RuntimeContext Properties
| Property | Type | Description |
|---|---|---|
CustomEntries | IReadOnlyList<RuntimeContext.ContextKeyValue> | Read-only list of custom key-value pairs |
RuntimeContext Methods
| Method | Returns | Description |
|---|---|---|
Clone() | RuntimeContext | Create a deep copy of this context |
HasAnyContext() | bool | True if any context field is set |
ClearCustomEntries() | void | Remove all custom key-value pairs |
Example: Full context setup
var context = npc.Context;
context.location = "Blacksmith Shop";
context.locationDetails = "Hot forge, smell of metal";
context.timeOfDay = "afternoon";
context.npcActivity = "hammering at the anvil";
context.npcMood = "focused";
context.playerAppearance = "carrying a broken sword";
context.recentEvents = new[] { "Dragon spotted near the village" };SetCustom / GetCustom / RemoveCustom
Manage custom context key-value pairs.
context.SetCustom("faction", "Silver Hawks");
string faction = context.GetCustom("faction");
context.RemoveCustom("faction");NPCResponse
Namespace: Peek.LoreMind.Cloud.Data
Response returned from RespondAsync().
NPCResponse Fields
| Field | Type | Description |
|---|---|---|
success | bool | True if response generated |
response | string | NPC's dialogue text |
character | string | Character name |
metadata | ResponseMetadata | Internal protocol metadata |
error | string | Error code if failed |
message | string | Error message if failed |
retryAfter | int | Seconds to wait before trying again (rate limit, or lore unavailable) |
An error response never carries dialogue: response is empty, and the SDK never substitutes a canned or fallback line. Compare error against the constants in Peek.LoreMind.Cloud.LoreMindErrorCodes (see Error Codes).
Example: Handling responses
using Peek.LoreMind.Cloud;
var response = await npc.RespondAsync("Hello!");
if (response.success)
{
dialogueUI.ShowText(response.response);
}
else if (response.error == LoreMindErrorCodes.InsufficientCredits)
{
ShowBuyCreditsPrompt();
}
else if (response.error == LoreMindErrorCodes.RateLimited
|| response.error == LoreMindErrorCodes.LoreUnavailable)
{
// The SDK has already retried a 503 Lore unavailable as the server asked.
// Show a "try again" state; the player can retry after response.retryAfter seconds.
ShowTryAgainLater(response.retryAfter);
}
else
{
Debug.LogError($"NPC error {response.error}: {response.message}");
}ResponseMetadata
Namespace: Peek.LoreMind.Cloud.Data
Internal protocol metadata included with each response.
ResponseMetadata Fields
| Field | Type | Description |
|---|---|---|
memoryCheckpoint | bool | True when the server auto-saved memories because the conversation was long. The SDK uses this internally to trim conversation history |
warnings | string[] | Server notes about the request, for example activeKnowledgeTags the Entity Mind doesn't have. Null when there is nothing to report. For developers, not players |
The built-in transports show each warning as a Console warning in the Editor and Development Builds, whatever the Log Level.
Usage details like token counts, credits, and latency are available in the LoreMind dashboard.
LocationZone
Namespace: Peek.LoreMind.Context
Trigger-based zone that auto-updates NPC location context.
LocationZone Properties
| Property | Type | Description |
|---|---|---|
LocationName | string | Location name |
LocationDetails | string | Location description |
Weather | string | Weather override |
Atmosphere | string | Atmosphere override |
Priority | int | For overlapping zones |
CustomContext | IReadOnlyList<ContextEntry> | Custom key-value pairs |
Example: Zone setup via code
var zone = gameObject.AddComponent<LocationZone>();
// Configure via inspector fields or serialized propertiesNPCs implement ILocationZoneReceiver automatically and update their context when entering/exiting zones.
ContextTag
Namespace: Peek.LoreMind.Context
Marker for entities that NPCs can perceive.
ContextTag Properties
| Property | Type | Description |
|---|---|---|
DisplayName | string | How NPCs see this |
Category | ContextCategory | Character/Object/Item/Landmark |
Details | string | Additional info when close |
DetailsRadius | float | Distance for details (0 = always) |
Example: Suspicious NPC tag
// In inspector:
// Display Name: "Hooded stranger"
// Category: Character
// Details: "Covered in dried blood, watching the door"
// Details Radius: 5.0
// When player asks NPC about surroundings:
// "There's a hooded stranger over there. Be careful - I saw blood on his cloak."GlobalContextManager
Namespace: Peek.LoreMind.Context
Singleton for shared world state.
GlobalContextManager Methods
| Method | Description |
|---|---|
SetTimeOfDay(string) | Update global time |
AddWorldEvent(string) | Add event NPCs know about |
ClearWorldEvents() | Remove all world events |
SetCustom(key, value) | Set global custom context |
GetCustom(key) | Get global custom context |
RemoveCustom(key) | Remove global custom context |
Example: Day/night cycle
public class DayNightManager : MonoBehaviour
{
void OnTimeChanged(float gameHours)
{
var global = GlobalContextManager.Instance;
if (gameHours < 6) global.SetTimeOfDay("night");
else if (gameHours < 12) global.SetTimeOfDay("morning");
else if (gameHours < 18) global.SetTimeOfDay("afternoon");
else global.SetTimeOfDay("evening");
}
void OnMajorEvent(string eventDescription)
{
GlobalContextManager.Instance.AddWorldEvent(eventDescription);
// All NPCs with SyncGlobalContext=true now know about this event
}
}LoreMindVoiceInput
Namespace: Peek.LoreMind.Voice
Optional voice input component. Requires whisper.unity (or the LOREMIND_MICROPHONE scripting define with your own speech-to-text; see Voice Input).
LoreMindVoiceInput Methods
| Method | Description |
|---|---|
StartCapture() | Begin recording. Raises OnError instead when speech-to-text is off, microphone permission was denied, or the microphone isn't running yet |
StopCapture() | Stop and transcribe |
CaptureAndTranscribeAsync(float) | Record for duration (0 = until push-to-talk release or max duration), return this capture's text or null |
CancelCapture() | Stop and discard the audio (nothing is transcribed; a waiting CaptureAndTranscribeAsync returns null) |
Captures stop at the maximum recording duration with or without push-to-talk. After the component is disabled or destroyed, a transcription still in progress delivers nothing.
LoreMindVoiceInput Properties
| Property | Type | Description |
|---|---|---|
IsCapturing | bool | Currently recording |
IsTranscribing | bool | Currently processing |
CaptureDuration | float | Current recording length |
LastTranscription | string | Most recent text |
PushToTalk | bool | Use push-to-talk mode |
PushToTalkKey | KeyCode | Key to hold for recording |
TargetNPC | LoreMindNPC | Auto-send transcriptions here |
Example: Manual voice capture
async void OnVoiceButtonPressed()
{
// Duration depends on expected speech length - adjust for your game
string text = await voiceInput.CaptureAndTranscribeAsync(maxDuration);
if (!string.IsNullOrEmpty(text))
{
npc.Respond(text);
}
}STTProviderType
Namespace: Peek.LoreMind
enum STTProviderType
{
None,
Whisper
}ISpeechToTextProvider
Namespace: Peek.LoreMind.Services
Interface for speech-to-text providers. Implement this to use your own STT solution.
public interface ISpeechToTextProvider
{
Task<string> TranscribeAsync(float[] audioData, int sampleRate, int channels);
Task<bool> InitializeAsync();
void Dispose();
bool IsReady { get; }
string ProviderName { get; }
}The SDK includes a Whisper implementation. See Voice Input for custom provider examples.
INpcContextProvider
Namespace: Peek.LoreMind.Context
Interface for custom context providers. Implement this to inject context from your game systems.
public interface INpcContextProvider
{
NpcContextData GetCurrentContext();
}Example: Quest system integration
public class QuestContextProvider : MonoBehaviour, INpcContextProvider
{
public NpcContextData GetCurrentContext()
{
return new NpcContextData
{
situation = QuestManager.ActiveQuest?.Type ?? "exploring",
npcMood = HostilitySystem.IsHostile(gameObject) ? "hostile" : "neutral",
playerReputation = FactionSystem.GetReputation("Innkeepers") > 50 ? "trusted" : "stranger",
recentEvents = QuestManager.GetRecentEventSummaries(3)
};
}
}Attach to the same GameObject as LoreMindNPC. Context is fetched automatically before each API request.
Enums
ContextCategory
enum ContextCategory
{
Character, // NPCs, creatures, enemies
Object, // Furniture, decorations
Item, // Weapons, tools, consumables
Landmark // Buildings, monuments
}TransportMode
enum TransportMode
{
EditorDirect = 0, // Direct API calls in Editor (testing); client builds fail
CustomBackend = 1, // Route through the backend URL in the settings (production)
SetInCode = 2 // Your code calls npc.SetTransport(...); the settings create no transport
}Transport System
The transport system handles how NPC requests are sent. Most developers configure this through the Control Panel, but you can use these APIs for advanced scenarios.
ILoreMindTransport
Interface for custom transport implementations.
public interface ILoreMindTransport
{
Task<NPCResponse> SendRequestAsync(NPCRespondRequest request);
bool IsReady { get; }
event Action<NPCRespondRequest> OnRequestSending;
event Action<NPCResponse> OnResponseReceived;
event Action<Exception> OnTransportError; // only when sending throws; HTTP and network failures are responses
}A transport must never invent dialogue: on failure, return an NPCResponse with success = false and an error code.
Cancellation (optional). To support cancellation, also implement ICancellableLoreMindTransport, which adds Task<NPCResponse> SendRequestAsync(NPCRespondRequest request, CancellationToken cancellationToken). The built-in transports do. A custom transport that implements only ILoreMindTransport still works: when its request is cancelled, LoreMindNPC lets the request finish and then reports CANCELLED.
Example: Custom logging transport
public class LoggingTransport : ILoreMindTransport
{
private readonly ILoreMindTransport _inner;
public LoggingTransport(ILoreMindTransport inner)
{
_inner = inner;
}
public bool IsReady => _inner.IsReady;
public event Action<NPCRespondRequest> OnRequestSending;
public event Action<NPCResponse> OnResponseReceived;
public event Action<Exception> OnTransportError;
public async Task<NPCResponse> SendRequestAsync(NPCRespondRequest request)
{
Debug.Log($"Sending: {request.text}");
OnRequestSending?.Invoke(request);
var response = await _inner.SendRequestAsync(request);
Debug.Log($"Received: {response.response}");
OnResponseReceived?.Invoke(response);
return response;
}
}DirectApiTransport
Sends requests directly to LoreMind API. Used for Editor testing. The SDK creates it automatically in the Editor from Control Panel settings.
Available only in the Editor and in Dedicated Server builds (UNITY_SERVER). It doesn't exist in game client builds, because it sends a Server API Key. In client builds, use CustomBackendTransport. On a Dedicated Server, see Dedicated Server Builds.
#if UNITY_EDITOR || UNITY_SERVER
var transport = new DirectApiTransport(baseUrl, serverApiKey, playerId);
npc.SetTransport(transport);
#endifThe constructor throws ArgumentException unless the base URL is https (plain http only to localhost in the Editor and Development Builds). The constructor's playerId is a default: a request that already carries playerId keeps it.
LoreService and EntityMind (the 1.0 API) are obsolete: use LoreMindNPC. LoreService.SetServerMediatedAuth also exists only in the Editor and Dedicated Server builds.
CustomBackendTransport
Routes requests through your game server. Used for production.
var transport = new CustomBackendTransport(
backendUrl: "https://api.yourgame.com/api/npc/interact"
);
npc.SetTransport(transport);Parameters:
backendUrl: your server endpoint that forwards to LoreMind. It receives the player's session token, so it must behttpswithout a user name or password (plainhttponly tolocalhostin the Editor and Development Builds). Otherwise the transport is not ready (IsReadyis false) and every request fails withCONFIG_ERRORwithout sending anything.timeoutSeconds: request timeout in seconds (default: 600,LoreMindRequestPolicy.RequestTimeoutSeconds). Don't lower it: the first request after a period of inactivity can take minutes. Your backend's own timeout must be at least as long; see Timeouts.
Properties:
AuthTokenProvider(Func<Task<string>>): returns the player's session token, sent asAuthorization: Bearer <token>.CustomBackendTransport.DefaultAuthTokenProviderapplies to every instance that has none. See Sending the Player's Session Token.ConfigureRequest(Action<UnityWebRequest>): adds your own headers.CustomBackendTransport.DefaultConfigureRequestapplies to every instance that has none.
Responses larger than 1 MiB are refused (RESPONSE_TOO_LARGE). Redirects are not followed. activeKnowledgeTags with a null, empty or whitespace-only entry, or beyond the server's limits, are refused with VALIDATION_ERROR before sending, and so is a conversationHistory message whose role is not user or assistant or that has no content.
Timeouts and Retries
The first NPC request after a period of inactivity can take much longer than usual, sometimes minutes. LoreMind never answers without the NPC's lore: if the lore can't be searched, it answers 503 Lore unavailable with a Retry-After header and charges nothing.
The SDK's policy (Peek.LoreMind.Cloud.LoreMindRequestPolicy):
| Setting | Value | Description |
|---|---|---|
RequestTimeoutSeconds | 600 | Matches LoreMind's 600-second request limit. Used for NPC requests and every Editor API call |
MaxAttempts | 3 | A 503 that carries Retry-After is retried after exactly that delay: one request plus up to two retries |
MaxRetryAfterSeconds | 25 | A longer requested wait isn't slept through; the error goes to your game with retryAfter set |
Nothing else is retried automatically, including a timeout or a dropped connection. Every failure reaches your game through OnError and the returned NPCResponse. Show a "thinking" indicator while IsProcessing is true, and a "try again" state on LORE_UNAVAILABLE, never a made-up line. Because the SDK retries, your backend shouldn't retry as well.
Error Codes
Every failure returns an NPCResponse with success = false, a code in error (constants in Peek.LoreMind.Cloud.LoreMindErrorCodes) and a readable message (the server's own explanation when it gives one). response is always empty: show a "try again" state, never made-up dialogue. The same codes are used with DirectApiTransport (Editor) and CustomBackendTransport (production), as long as your backend forwards LoreMind's status code and body unchanged.
| Code | Meaning | Action |
|---|---|---|
CONFIG_ERROR | Not set up: no transport (e.g. EditorDirect in a client build, or no backend URL), no Entity Mind ID, or in the Editor no Server key or test player | Check the Control Panel |
EMPTY_TEXT | RespondAsync was called with empty text | Send the player's text |
BUSY | The NPC is still answering the previous request (no event fires) | Wait for OnRequestFinished |
CANCELLED | Cancelled: NPC destroyed, Play mode ended, or your token | Nothing to show |
VALIDATION_ERROR | Request rejected as invalid (HTTP 400), e.g. text over 2,000 characters, more than 50 knowledge tags, or an empty knowledge tag | Check message |
UNKNOWN_KNOWLEDGE_TAGS | None of the request's activeKnowledgeTags exist on the Entity Mind (HTTP 400). No reply, no credits used. message names the tags | Fix the NPC's Active Knowledge Tags (a tag renamed or removed in the dashboard); retrying doesn't help |
AUTH_FAILED | Key or player token rejected (HTTP 401), or your AuthTokenProvider returned no token | Check the key (sk_server_) or the player's login |
INSUFFICIENT_CREDITS | Out of credits (HTTP 402) | Top up at loremind.peekgames.dev |
FORBIDDEN | Key not allowed for this call (HTTP 403), e.g. an Editor key (sk_editor_) used for NPC requests | Use a Server key |
TERMS_NOT_ACCEPTED | A team owner or admin must accept the updated Terms of Service (HTTP 403) | Sign in to the dashboard and accept them |
ENTITY_MIND_NOT_FOUND | The Entity Mind ID doesn't exist in this project (HTTP 404) | Pick the NPC again in the Inspector |
NOT_FOUND | Something else wasn't found (HTTP 404), e.g. the backend path | Check URLs |
RATE_LIMITED | Too many requests (HTTP 429) | Wait retryAfter seconds (from the Retry-After header) |
LORE_UNAVAILABLE | The NPC's lore couldn't be searched (HTTP 503), even after the SDK's automatic retries. No credits used | Let the player try again after retryAfter seconds |
SERVICE_UNAVAILABLE | Generation failed (HTTP 503). No credits used | Retry later |
SERVER_ERROR | Unexpected server error (HTTP 5xx) | Retry later |
REQUEST_FAILED | No usable response from LoreMind: no connection, or no reply within 600 s (message is Request timeout) | Check the connection, then retry |
CONNECTION_ERROR | CustomBackendTransport couldn't reach your backend, or got no reply within timeoutSeconds | Check the backend is up and its timeouts |
RESPONSE_TOO_LARGE | The response was larger than 1 MiB | Check what your backend returns |
PARSE_ERROR | The response wasn't valid NPCResponse JSON | Return LoreMind's body unchanged |
TRANSPORT_ERROR | The transport threw an exception, or a custom transport returned nothing | Check the Console |
HTTP_ERROR (in LoreMindErrorCodes) is never returned: HTTP errors from a custom backend are mapped by status like LoreMind's own. A custom backend may also return its own JSON error body ({"success": false, "error": "...", "message": "..."}). If error is one of the codes above it is kept as is; otherwise the SDK maps the HTTP status as in the table and keeps your message.
The HTTP-level reference lives at Errors & Rate Limits.
Next Steps
- Your First NPC - Build your first NPC
- LoreMindNPC Component - Complete component guide
- Context System - Situational awareness
- Platform Documentation - Dashboard and API setup