Skip to Content
Loremind Unity 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 (required, 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
customstringFreeform custom context (max 500 chars)

Properties

PropertyTypeDescription
CustomEntriesIReadOnlyList<ContextEntry>Read-only list of custom key-value pairs

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

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 (maps from API’s memoriesRetrieved)
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

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

LoreMindVoiceOutput

Namespace: Peek.LoreMind.Voice

Optional text-to-speech component for NPC voices. Uses Kokoro for fully local, offline speech synthesis.

Methods

MethodDescription
Speak(string)Fire-and-forget speech synthesis
SpeakAsync(string)Await-able speech synthesis
Stop()Stop current playback
GetAvailableVoices()Get voice list from provider
GetProviderName()Current provider name
ReinitializeProviderAsync()Reinitialize after settings change

Properties

PropertyTypeDescription
IsSpeakingboolCurrently synthesizing or playing
IsSynthesizingboolCurrently generating audio
LastSpokenTextstringMost recent spoken text
AudioSourceAudioSourceAudioSource for playback
VoiceIdstringVoice identifier (provider-specific)
OverrideProviderboolUse custom provider instead of project settings
ProviderOverrideITextToSpeechProviderCustom TTS provider instance
AudioSourceOverrideAudioSourceCustom AudioSource for this component

Events

EventTypeWhen
OnSpeechStartedUnityEventSpeech begins
OnSpeechCompletedUnityEventSpeech finishes
OnErrorUnityEvent<string>Error occurred

Example: NPC speaks responses

void Start() { // Auto-speak NPC responses npc.OnResponseReceived.AddListener(text => { voiceOutput.Speak(text); }); // Track speech state voiceOutput.OnSpeechStarted.AddListener(() => speakingIcon.SetActive(true)); voiceOutput.OnSpeechCompleted.AddListener(() => speakingIcon.SetActive(false)); }

Example: Different voices per NPC

// Assign unique voices blacksmithVoice.VoiceId = "bm_george"; // British male apprenticeVoice.VoiceId = "af_sky"; // American female

TTSVoiceInfo

Namespace: Peek.LoreMind.Services

Voice metadata returned by TTS providers.

Fields

FieldTypeDescription
idstringProvider-specific voice ID
namestringDisplay name
languagestringLanguage code (e.g., “en-US”)
genderstring”male” or “female”
descriptionstringVoice description
tagsstring[]Voice attributes
isDefaultboolProvider’s default voice
isLocalboolRuns locally (no API calls)

Example: List available voices

foreach (var voice in voiceOutput.GetAvailableVoices()) { Debug.Log($"{voice.name} ({voice.gender}): {voice.id}"); }

TTSProviderType

Namespace: Peek.LoreMind.Services

enum TTSProviderType { None, Kokoro }

STTProviderType

Namespace: Peek.LoreMind.Services

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.


ITextToSpeechProvider

Namespace: Peek.LoreMind.Services

Interface for text-to-speech providers. Implement this to use your own TTS solution.

public interface ITextToSpeechProvider : IDisposable { Task<AudioClip> SynthesizeAsync(string text, string voiceId = null, TTSSynthesisOptions options = null); Task SynthesizeStreamingAsync(string text, AudioSource audioSource, string voiceId = null, TTSSynthesisOptions options = null); Task<bool> InitializeAsync(); bool IsReady { get; } string ProviderName { get; } bool SupportsStreaming { get; } TTSVoiceInfo[] GetAvailableVoices(); string GetDefaultVoiceId(); }

The SDK includes a Kokoro implementation. See Voice Output 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

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 }

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; } string TransportName { get; } }

Example: Custom logging transport

public class LoggingTransport : ILoreMindTransport { private readonly ILoreMindTransport _inner; public LoggingTransport(ILoreMindTransport inner) { _inner = inner; } public bool IsReady => _inner.IsReady; public string TransportName => $"Logging({_inner.TransportName})"; public async Task<NPCResponse> SendRequestAsync(NPCRespondRequest request) { Debug.Log($"Sending: {request.text}"); var response = await _inner.SendRequestAsync(request); Debug.Log($"Received: {response.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

CodeMeaningAction
INSUFFICIENT_CREDITSOut of creditsPurchase more at loremind.peekgames.dev 
RATE_LIMITEDToo many requestsWait retryAfter seconds
INVALID_ENTITY_MINDEntity Mind not foundCheck Entity Mind ID
PROJECT_SUSPENDEDProject disabledCheck billing/policy
CONTENT_FILTEREDResponse blockedAdjust prompts/restrictions
TRANSPORT_ERRORRequest failed to sendCheck network/backend configuration

Next Steps

Last updated on