Skip to Content
DocsLoremind SdkAPI Reference

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)

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); Debug.Log($"Credits used: {response.metadata.creditsUsed}"); } 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 (set in Inspector)
ContextRuntimeContextCurrent situational context
TopKintNumber of lore chunks to retrieve (configurable in Inspector)
VerbosityVerbosityPresetResponse length (Terse/Balanced/Verbose)
TemperaturefloatCreativity level (configurable in Inspector)
IsProcessingboolTrue while waiting for response
LastResponsestringMost recent response text
AutoSenseNearbyboolAuto-detect nearby ContextTags
SyncGlobalContextboolSync with GlobalContextManager

Events

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

RuntimeContext

Namespace: Peek.LoreMind.Cloud.Data

Holds situational context for NPC responses.

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

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().

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); Debug.Log($"Credits: {response.metadata.creditsUsed}"); } 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

Usage and performance data included with each response.

Fields

FieldTypeDescription
modelstringLLM model used
promptTokensintInput tokens
completionTokensintOutput tokens
creditsUsedfloatCredits charged
creditsRemainingfloatCredits left
usedFallbackboolTrue if fallback model was used
loreChunksUsedintLore chunks retrieved
memoriesUsedintMemories retrieved
memoryCheckpointboolAuto-saved memories
finishReasonstringstop/length/content_filter
costBreakdownCostBreakdownDetailed costs
latencyLatencyInfoTiming info

Example: Cost monitoring

npc.OnResponseWithMetadata.AddListener(response => { var meta = response.metadata; Debug.Log($"Model: {meta.model}"); Debug.Log($"Tokens: {meta.promptTokens} in, {meta.completionTokens} out"); Debug.Log($"Cost: {meta.creditsUsed} credits"); Debug.Log($"Remaining: {meta.creditsRemaining} credits"); // Set your own threshold based on your game's usage patterns if (meta.creditsRemaining < YOUR_LOW_CREDITS_THRESHOLD) ShowLowCreditsWarning(); });

LocationZone

Namespace: Peek.LoreMind.Context

Trigger-based zone that auto-updates NPC location context.

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.

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.

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
ResetAll()Clear everything

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.

Methods

MethodDescription
StartCapture()Begin recording
StopCapture()Stop and transcribe
CaptureAndTranscribeAsync(float)Record for duration, return text
CancelCapture()Cancel without transcribing

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

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

VerbosityPreset

enum VerbosityPreset { Terse, // 1-2 sentences Balanced, // 2-4 sentences (default) Verbose // Detailed responses }

ContextCategory

enum ContextCategory { Character, // NPCs, creatures, enemies Object, // Furniture, decorations Item, // Weapons, tools, consumables Landmark // Buildings, monuments }

AuthMode

enum AuthMode { DirectClient, // Device-based JWT sessions ServerMediated // API key authentication }

Error Codes

CodeMeaningAction
INSUFFICIENT_CREDITSOut of creditsPurchase more at loremind.peekgames.dev 
RATE_LIMITEDToo many requestsWait retryAfter seconds
INVALID_SESSIONSession expiredSDK auto-refreshes
INVALID_ENTITY_MINDEntity Mind not foundCheck Entity Mind ID
PROJECT_SUSPENDEDProject disabledCheck billing/policy
CONTENT_FILTEREDResponse blockedAdjust prompts/restrictions

Next Steps

Last updated on