Skip to Content
Loremind Unity SDKAPI Reference

API Reference

Complete reference for the LoreMind Unity SDK. Each API includes practical usage examples.

Last verified against LoreMind v1.0.67 (August 2026).

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)

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 tavern

SetCustomContext / 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

PropertyTypeDescription
EntityMindIdstringEntity Mind to use (required, set in Inspector)
ContextRuntimeContextCurrent situational context
IsProcessingboolTrue while waiting for response
LastResponsestringMost recent response text
LastResponseDataNPCResponseMost recent full response data
ActiveKnowledgeTagsstring[]Restrict which lore tags the NPC can reference
AutoSenseNearbyboolAuto-detect nearby ContextTags
SyncGlobalContextboolSync with GlobalContextManager
EnableMemoryRetrievalboolEnable long-term memory retrieval (storage is automatic server-side)

Events

EventTypeWhen
OnResponseReceivedUnityEvent<string>Response text received
OnResponseCompleteUnityEvent<NPCResponse>Full response with metadata
OnErrorUnityEvent<string>Error occurred

RuntimeContext

Namespace: Peek.LoreMind.Cloud.Data

Holds situational context for NPC responses.

RuntimeContext Fields

FieldTypeDescription
locationstringCurrent location name
locationDetailsstringLocation description
timeOfDaystringdawn/morning/midday/afternoon/dusk/evening/night/midnight
weatherstringclear/rainy/stormy/foggy/snowing
atmospherestringpeaceful/tense/festive/eerie/somber
nearbyCharactersstring[]Visible character names
nearbyObjectsstring[]Notable objects
situationstringshopping/combat/exploring/trading
recentEventsstring[]Recent game events
npcMoodstringcheerful/suspicious/nervous/tired/angry
npcActivitystringWhat NPC is doing
playerAppearancestringPlayer description
playerReputationstringHow NPC views player
playerVisibleItemsstring[]Notable player items
customstringFreeform custom context (max 500 chars)

RuntimeContext Properties

PropertyTypeDescription
CustomEntriesIReadOnlyList<RuntimeContext.ContextKeyValue>Read-only list of custom key-value pairs

RuntimeContext Methods

MethodReturnsDescription
Clone()RuntimeContextCreate a deep copy of this context
HasAnyContext()boolTrue if any context field is set
ClearCustomEntries()voidRemove 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

FieldTypeDescription
successboolTrue if response generated
responsestringNPC’s dialogue text
characterstringCharacter name
metadataResponseMetadataUsage stats
errorstringError code if failed
messagestringError message if failed
retryAfterintSeconds to wait (rate limit)

Example: Handling responses

var response = await npc.RespondAsync("Hello!"); if (response.success) { dialogueUI.ShowText(response.response); if (response.metadata.memoryCheckpoint) Debug.Log("Memories auto-saved — conversation hit max length"); } else if (response.error == "INSUFFICIENT_CREDITS") { ShowBuyCreditsPrompt(); } else if (response.error == "RATE_LIMITED") { await Task.Delay(response.retryAfter * 1000); // Retry... }

ResponseMetadata

Namespace: Peek.LoreMind.Cloud.Data

Metadata included with each response.

ResponseMetadata Fields

FieldTypeDescription
memoryCheckpointboolTrue when the server auto-saved memories because the conversation exceeded the project’s max session length

Example: Memory checkpoint handling

npc.OnResponseComplete.AddListener(response => { if (response.metadata.memoryCheckpoint) { // Conversation was long — memories were auto-saved. // Clear history and start fresh. npc.ClearConversationHistory(); Debug.Log("Memories saved. Starting fresh conversation."); } });

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

PropertyTypeDescription
LocationNamestringLocation name
LocationDetailsstringLocation description
WeatherstringWeather override
AtmospherestringAtmosphere override
PriorityintFor overlapping zones
CustomContextIReadOnlyList<ContextEntry>Custom key-value pairs

Example: Zone setup via code

var zone = gameObject.AddComponent<LocationZone>(); // Configure via inspector fields or serialized properties

NPCs 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

PropertyTypeDescription
DisplayNamestringHow NPCs see this
CategoryContextCategoryCharacter/Object/Item/Landmark
DetailsstringAdditional info when close
DetailsRadiusfloatDistance 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

MethodDescription
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.

LoreMindVoiceInput Methods

MethodDescription
StartCapture()Begin recording
StopCapture()Stop and transcribe
CaptureAndTranscribeAsync(float)Record for duration, return text
CancelCapture()Stop an in-progress capture (currently behaves like StopCapture())

LoreMindVoiceInput Properties

PropertyTypeDescription
IsCapturingboolCurrently recording
IsTranscribingboolCurrently processing
CaptureDurationfloatCurrent recording length
LastTranscriptionstringMost recent text
PushToTalkboolUse push-to-talk mode
PushToTalkKeyKeyCodeKey to hold for recording
TargetNPCLoreMindNPCAuto-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, // Direct API calls in Editor (testing) CustomBackend // Route through your backend (production) }

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; }

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.

// Editor-only: The SDK creates this automatically from Control Panel settings. // Direct construction requires baseUrl, serverApiKey, and playerId: var transport = new DirectApiTransport(baseUrl, serverApiKey, playerId); npc.SetTransport(transport);

Note: This transport is for Editor testing only. The SDK automatically creates it when you configure your Server API Key in the Control Panel. In builds, use CustomBackendTransport.

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
  • timeoutSeconds - Request timeout in seconds (default: 60)

Error Codes

Codes set on NPCResponse.error when success is false.

Editor-direct transport:

CodeMeaningAction
CONFIG_ERRORSDK not configuredCheck Control Panel settings (API key, Entity Mind)
VALIDATION_ERRORServer rejected the request (HTTP 400)Check Entity Mind ID and request fields
AUTH_FAILEDInvalid API key (HTTP 401)Check your Server Key in the Control Panel
INSUFFICIENT_CREDITSOut of credits (HTTP 402)Top up at loremind.peekgames.dev 
RATE_LIMITEDToo many requests (HTTP 429)Wait retryAfter seconds
SERVICE_UNAVAILABLEAI service unavailable (HTTP 503)Retry
REQUEST_FAILEDOther HTTP errorCheck the message field
TRANSPORT_ERRORRequest failed to sendCheck network connection

Custom-backend transport: CONFIG_ERROR, TRANSPORT_ERROR, CONNECTION_ERROR, HTTP_ERROR, PARSE_ERROR - plus whatever error body your backend passes through from LoreMind.

These codes map to the platform API’s HTTP errors (AUTH_FAILED401 Invalid API key, INSUFFICIENT_CREDITS402 Insufficient credits, and so on) — the HTTP-level reference lives at Errors & Rate Limits.


Next Steps

Last updated on