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.

csharp
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

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

csharp
void Respond(string playerText)

Example: Event-based dialogue

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

csharp
void SetLocation(string location, string details = null)

Example: Location-aware responses

csharp
// 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.

csharp
void SetCustomContext(string key, string value)
string GetCustomContext(string key)
void RemoveCustomContext(string key)

Example: Quest-aware NPC

csharp
// 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.

csharp
void ClearConversationHistory()

Example: Ending a conversation

csharp
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 reply text (successful replies only)
LastResponseDataNPCResponseMost recent response, success or failure
EnableMemoryRetrievalboolRecall what this player said before (needs playerId, added by your backend, and Long-Term Memory on for the project)
ActiveKnowledgeTagsstring[]Restrict the NPC's lore to these tags (see Active Knowledge Tags)
AutoSenseNearbyboolAuto-detect nearby ContextTags
SyncGlobalContextboolSync with GlobalContextManager

Events

EventTypeWhen
OnResponseReceivedUnityEvent<string>A reply arrived (success only)
OnResponseCompleteUnityEvent<NPCResponse>A reply arrived, with the full response (success only, after the event above)
OnErrorUnityEvent<string>The request failed
OnRequestFinishedUnityEvent<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

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

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

csharp
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
metadataResponseMetadataInternal protocol metadata
errorstringError code if failed
messagestringError message if failed
retryAfterintSeconds 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

csharp
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

FieldTypeDescription
memoryCheckpointboolTrue when the server auto-saved memories because the conversation was long. The SDK uses this internally to trim conversation history
warningsstring[]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

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

Example: Zone setup via code

csharp
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

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

csharp
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

MethodDescription
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

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

csharp
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

csharp
enum STTProviderType
{
    None,
    Whisper
}

ISpeechToTextProvider

Namespace: Peek.LoreMind.Services

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

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

csharp
public interface INpcContextProvider
{
    NpcContextData GetCurrentContext();
}

Example: Quest system integration

csharp
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

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

TransportMode

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

csharp
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

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

csharp
#if UNITY_EDITOR || UNITY_SERVER
var transport = new DirectApiTransport(baseUrl, serverApiKey, playerId);
npc.SetTransport(transport);
#endif

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

csharp
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 be https without a user name or password (plain http only to localhost in the Editor and Development Builds). Otherwise the transport is not ready (IsReady is false) and every request fails with CONFIG_ERROR without 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 as Authorization: Bearer <token>. CustomBackendTransport.DefaultAuthTokenProvider applies to every instance that has none. See Sending the Player's Session Token.
  • ConfigureRequest (Action<UnityWebRequest>): adds your own headers. CustomBackendTransport.DefaultConfigureRequest applies 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):

SettingValueDescription
RequestTimeoutSeconds600Matches LoreMind's 600-second request limit. Used for NPC requests and every Editor API call
MaxAttempts3A 503 that carries Retry-After is retried after exactly that delay: one request plus up to two retries
MaxRetryAfterSeconds25A 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.

CodeMeaningAction
CONFIG_ERRORNot 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 playerCheck the Control Panel
EMPTY_TEXTRespondAsync was called with empty textSend the player's text
BUSYThe NPC is still answering the previous request (no event fires)Wait for OnRequestFinished
CANCELLEDCancelled: NPC destroyed, Play mode ended, or your tokenNothing to show
VALIDATION_ERRORRequest rejected as invalid (HTTP 400), e.g. text over 2,000 characters, more than 50 knowledge tags, or an empty knowledge tagCheck message
UNKNOWN_KNOWLEDGE_TAGSNone of the request's activeKnowledgeTags exist on the Entity Mind (HTTP 400). No reply, no credits used. message names the tagsFix the NPC's Active Knowledge Tags (a tag renamed or removed in the dashboard); retrying doesn't help
AUTH_FAILEDKey or player token rejected (HTTP 401), or your AuthTokenProvider returned no tokenCheck the key (sk_server_) or the player's login
INSUFFICIENT_CREDITSOut of credits (HTTP 402)Top up at loremind.peekgames.dev
FORBIDDENKey not allowed for this call (HTTP 403), e.g. an Editor key (sk_editor_) used for NPC requestsUse a Server key
TERMS_NOT_ACCEPTEDA team owner or admin must accept the updated Terms of Service (HTTP 403)Sign in to the dashboard and accept them
ENTITY_MIND_NOT_FOUNDThe Entity Mind ID doesn't exist in this project (HTTP 404)Pick the NPC again in the Inspector
NOT_FOUNDSomething else wasn't found (HTTP 404), e.g. the backend pathCheck URLs
RATE_LIMITEDToo many requests (HTTP 429)Wait retryAfter seconds (from the Retry-After header)
LORE_UNAVAILABLEThe NPC's lore couldn't be searched (HTTP 503), even after the SDK's automatic retries. No credits usedLet the player try again after retryAfter seconds
SERVICE_UNAVAILABLEGeneration failed (HTTP 503). No credits usedRetry later
SERVER_ERRORUnexpected server error (HTTP 5xx)Retry later
REQUEST_FAILEDNo usable response from LoreMind: no connection, or no reply within 600 s (message is Request timeout)Check the connection, then retry
CONNECTION_ERRORCustomBackendTransport couldn't reach your backend, or got no reply within timeoutSecondsCheck the backend is up and its timeouts
RESPONSE_TOO_LARGEThe response was larger than 1 MiBCheck what your backend returns
PARSE_ERRORThe response wasn't valid NPCResponse JSONReturn LoreMind's body unchanged
TRANSPORT_ERRORThe transport threw an exception, or a custom transport returned nothingCheck 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