Neocortex
IntegrationsUnreal SDK

API Reference

Reference for the Neocortex Unreal Engine plugin, covering the Smart Agent, Group Director, Quiz Agent, usage gate, microphone, lip sync and chat widgets, usable from C++ and Blueprints.

Every component, function and event here works from both C++ and Blueprints, unless it says C++ only. In Blueprints, the names read with spaces: SendMessage is Send Message, bStreamSpeech is Stream Speech.

Neocortex Smart Agent

UNeocortexSmartAgent is an actor component for one character. It sends messages, plays the reply as chat lines and runs the actions it triggers.

Properties

PropertyDescription
ProjectIdThe character's id. The Pick button next to it lists your characters.
ChatLinesModeHow replies are delivered. See Chat lines. Default PerLineAudio.
AudioComponentWhere the voice plays. Empty uses, or creates, one on the owner.
bStreamSpeechPlay speech as it is synthesized, so the voice starts sooner. Default on.
bLoadHistoryOnStartFetch and replay this character's stored conversation when play begins.
ActionTriggerWhen a reply's actions run: WhenResponseReceived, WhenSpeechStarts or AfterReplySpoken.
DelayBetweenActionsSeconds to wait after one action finishes before the next starts. Default 0.
bIncludeAllInteractablesSend what the character perceives with each message. Default on. See Perception.
bUseRadiusFilter, SearchRadiusOnly send interactables within SearchRadius (default 2000) of the owner.
MaxPerceivedEntitiesHow many interactables one message carries, nearest first. Default 10.

Functions

FunctionDescription
SendMessage(Message)Sends text. The reply arrives on OnChat and, in a chat lines mode, line by line.
SendMessageForAudio(Message)Sends text and asks for speech. In a chat lines mode it is the same as SendMessage.
SendAudioForAudio(WavData)The whole voice turn: transcribes the WAV, raises OnTranscribed, sends the text and speaks the reply.
TranscribeBytes(WavData)Speech to text only, on OnTranscribed.
RequestChatHistory(Limit, Before)A page of the stored conversation on OnChatHistory. See History.
RegisterAction(Keyword, Handler)Sets what performs an action keyword. See Actions. Blueprints use Register Action with an event.
UnregisterAction(Keyword)Removes the handler.
StopSpeaking()Stops what the character is saying and drops queued input.
Abort()Cancels the request in flight, a whole voice turn included, and stops speaking. No error is raised.
GetSessionId(), ClearSessionId()The conversation's session id. Clearing it starts a new conversation on the next message.
IsRequestPending()True while a request is in flight or a reply is still playing.
IsSpeaking()True while a reply is pending or its lines are still playing.
IsThinking()True while a reply is on its way and nothing plays yet. Drive a thinking pose here.
IsRunningActions()True while the reply's actions run.

Events

EventFires
OnChat(Response)With each whole reply, an FNeocortexChatResponseData.
OnChatLineStarted(Line)When a chat line drops in. Show it in your chat here. Not in Off mode.
OnEmotionChanged(Emotion)With each line's emotion. Drive animation here. Not in Off mode.
OnComposingNextLineIn Text mode, during the pause before the next line, for a typing indicator.
OnReplyFinishedOnce the whole reply has finished. Not in Off mode.
OnAudio(SoundWave)With each clip of speech. In a voiced mode it is already playing.
OnTranscribed(Text)When a transcription completes.
OnChatHistory(Messages, NextCursor)With a page of the stored conversation.
OnActionsCompletedWhen all actions of a reply have run.
OnUnhandledAction(Action)When an action has no handler. It is skipped.
OnRequestError(Error)When anything fails, with an FNeocortexRequestError. See Handling errors.
OnError(Message)When anything fails, with a short message.

Chat lines

A reply is split into lines, each with its own emotion. Their text joined is the whole reply. ChatLinesMode decides how they are delivered:

ModeWhat you getCost
PerLineAudio (default)Each line voiced in its own emotion, in order.About 1 audio credit per line
SingleAudioLines drop in while one clip voices the whole reply.1 audio credit
TextLines drop in with an emotion each, OnComposingNextLine before the next.No extra cost
OffThe whole reply at once on OnChat. Nothing is played for you.No extra cost

The voiced modes check your credits first: a low balance voices the reply with one clip, an empty one shows text only. In every mode but Off, input sent while the character is still speaking is queued and sent when the reply ends. Blank, punctuation only and emoji only lines are never sent for speech.

Actions

A reply can trigger several actions, in order. Each FNeocortexChatAction has a Name, the keyword set on the character, and a TargetId, the interactable it applies to, or empty.

C++
// Instant: done when the handler returns.
Agent->RegisterAction(TEXT("WAVE"), [this](const FNeocortexChatAction& Action) { PlayWave(); });

// Timed: call Finish when done; the next action waits for it.
Agent->RegisterAction(TEXT("DANCE"), [this](const FNeocortexChatAction& Action, TFunction<void()> Finish)
{
    PlayDance(MoveTemp(Finish));
});

In Blueprints, Register Action takes a keyword and an event, and the next action starts when the event returns. For handlers that finish later, add a Neocortex Action Queue component: it raises OnActionStarted(Action, Response) for each action and waits for NotifyActionFinished() before the next one. OnQueueCompleted fires when it drains.

ActionTrigger decides when actions run, and DelayBetweenActions adds a pause between them. Actions without a handler raise OnUnhandledAction, and OnActionsCompleted fires once all have run.

History

RequestChatHistory(Limit, Before) loads a page of the stored conversation, oldest turn first, on OnChatHistory(Messages, NextCursor). Pass NextCursor as Before to load the next, older page. It is empty at the start of the history. With bLoadHistoryOnStart on, the latest page is fetched and replayed when play begins.

Streaming

With bStreamSpeech on, speech plays as it is synthesized and the next line is fetched while the current one is heard. It works on Windows, Linux and Android, and falls back to whole clips elsewhere.

Perception

With bIncludeAllInteractables on, each message carries the interactables nearest the agent, up to MaxPerceivedEntities, and the agent's own position. Turn on bUseRadiusFilter to only send those within SearchRadius.

Data types

FNeocortexChatResponseData

MemberDescription
ResponseThe whole reply: every line's text joined.
LinesThe FNeocortexChatLines that make up the reply, in order.
ActionsEvery FNeocortexChatAction the character triggered, in order. Action is the first one's keyword.
EmotionThe first line's emotion.
FlowStateThe Conversation Flow checkpoint this turn landed on, or empty.
SpokenResponseThe reply as spoken, with numbers, dates and currencies spelled out.
SessionId, CharacterId, NameThe session, and the character that replied.
MetadataThe interactables after the turn, as the server echoed them.

FNeocortexChatLine

Text, the line's Emotion, and SpokenText, the line as spoken (empty when the server sent none).

FNeocortexChatAction

Name, the action keyword, and TargetId, the interactable it applies to, or empty.

FNeocortexChatHistoryEntry

MemberDescription
ContentThe message text.
Sender"USER" for the player, "ASSISTANT" for a character.
Name, SpeakerCharacterIdWho spoke, for character lines.
AddressedToIn a group session, who the line was directed at.
Emotion, ActionsThe emotion and action keywords of a character line.
CreatedAtWhen it was said, as an ISO timestamp.

Emotions

EEmotions: Neutral, Happy, Pleased, Disappointed, Upset, Amazed, Curious, Confused, Alarmed, Fascinated, Impressed, Annoyed, Angry, Confident, Reassured, Concerned, Scared.

UNeocortexFunctionLibrary::EmotionFromString(Name) reads a name in any casing, and EmotionToUpper(Emotion) gives the uppercase form, such as "HAPPY".

Neocortex Group Director

UNeocortexGroupDirector runs one conversation across up to six Smart Agents. See Group Chat.

MemberDescription
AgentsThe characters in the scene.
MaxTurnsHow many characters speak in one turn, 1 to 5. Default 5.
bIncludeAllInteractablesSend every interactable with each turn. Default on.
SessionIdThe shared session. Empty until the first turn.
Send(Message)The cast decides who answers.
SendTo(Agent, Message), SendToCharacter(CharacterId, Message)One character answers.
ContinueScene()The cast talks among themselves.
SendAudio(WavData)Transcribes the player's speech, raises OnPlayerSpeech, then sends it like Send.
AddAgent(Agent), RemoveAgent(Agent)Changes the cast while the scene runs.
RequestHistory(Limit, Before)A page of the shared transcript on OnHistory.
ClearSession()Starts a new conversation on the next turn.
Abort()Cancels the turn and silences every character.
IsBusy()True while a turn is fetched or played out.

Events: OnTurnStarted, OnGroupResponse(Response), OnSpeaker(Message), OnTurnFinished, OnPlayerSpeech(Text), OnHistory(Messages, NextCursor), OnRequestError(Error) and OnError(Message). Each speaker's FNeocortexGroupMessage has the character's CharacterId, Name, Lines, Actions and FlowState.

Neocortex Quiz Agent

UNeocortexQuizAgent runs a quiz hosted by one of your characters from a question set. See Quiz.

PropertyDescription
CharacterId, QuestionSetIdThe host and the question set, each with a Pick button.
QuestionCountQuestions in one run. 0 uses the set's count.
QuestionOrderSetDefault, InOrder or Shuffled.
PlayerIdYour id for a single player. Empty uses the device's player id.
ParticipantsEveryone playing, in a game with more than one player.
bBeginOnStartStart when play begins.
bSpeakHostLines, bStreamHostSpeechSpeak the host's lines, and play each as its voice arrives. Both default on.
AudioComponentWhere the host's voice plays.
bQueueInputWhileBusy, MaxPendingInputAgeHold input while the host is busy, for up to 4 seconds by default.
FunctionDescription
Begin(), BeginWithPlayers(Players)Starts the quiz.
Say(Text, bTyped), SayAs(ParticipantId, Text, bTyped)What the player said or typed. An empty string is a pass.
Choose(OptionId), ChooseAs(ParticipantId, OptionId)A tapped option.
PassTurn(), PassAs(ParticipantId)The player gives no answer.
Resync()Reads the run back from the server and catches up.
Abort()Silences the host and abandons what is in flight.

State: SessionId, bHasQuestion and CurrentQuestion, Progress (Asked of Total), Expecting, bBusy, bFinished, PendingParticipants, AnsweredParticipants, Attempt, AttemptsLeft, bHintGiven and LastIntent.

Events: OnHostLine(Line), OnEmotionChanged(Emotion), OnHostFinished, OnQuestionChanged(Question), OnUpcomingQuestion(Upcoming), OnExpectingChanged(Expecting), OnResult(Results), OnLeaderboardChanged(Leaderboard), OnQuizFinished(Leaderboard), OnTurnReceived(Turn), OnBusyChanged(bBusy), OnPendingChanged(Pending), OnInputDropped(Text, Reason), OnCreditsExhausted(Code), OnRequestError(Error) and OnError(Message).

Neocortex Usage Gate

UNeocortexUsageGate turns your account's usage into events and a yes or no, so a game can pause smart features instead of failing mid-conversation. Create one with UNeocortexUsageGate::CreateUsageGate(WorldContextObject).

UNeocortexUsageGate* Gate = UNeocortexUsageGate::CreateUsageGate(this);
Gate->OnLowCredits.AddDynamic(this, &AMyActor::HandleLow);
Gate->OnCreditsEmpty.AddDynamic(this, &AMyActor::HandleEmpty);

if (Gate->CanUseSmartNPC(TEXT(""), Agent->ProjectId))
{
    Agent->SendMessage(Message);
}
MemberDescription
CanUseSmartNPC(PlayerId, CharacterId)False when team credits are empty or the player or character is over a limit. Answers from the cache and refreshes it in the background when it is stale, so it is safe before every message. It fails open.
RefreshUsage(PlayerId, CharacterId), RefreshAccount()Fetches now. An empty PlayerId uses the device's player id.
StartAutoRefresh(Interval, PlayerId, CharacterId), StopAutoRefresh()Refreshes usage on an interval, every 300 seconds by default.
MinRefreshIntervalSeconds a cached result is served before a new request. Default 30.
LastUsage, LastAccount, bHasUsage, bHasAccountThe cached results.

Events: OnUsageUpdated, OnLowCredits, OnCreditsEmpty, OnPlayerOverLimit and OnCharacterOverLimit with an FNeocortexUsageResponse, OnAccountUpdated with an FNeocortexAccountResponse, and OnRequestFailed(Error). The limit events fire once each time the state is reached.

The calls behind it are on UNeocortexService, from GetGameInstance()->GetSubsystem<UNeocortexSubsystem>()->GetService(), in C++: GetAccount, GetUsage(PlayerId, CharacterId), GetCharacters and GetQuestionSets. They are read-only and never cost a credit.

Neocortex Interactable

UNeocortexInteractableComponent marks an actor as something characters can perceive and act on.

PropertyDescription
NameWhat the character calls it. Empty uses the actor's name.
PropertiesWhat it is and its state, as name and value pairs, such as Color: Red.
IdThe id actions use as TargetId. Empty derives a stable one from the actor. GetId() returns it.
CharacterIdSet when the actor is a Neocortex character. Empty uses the Smart Agent on the same actor, if any.
TypeCHARACTER or OBJECT. Empty derives it.
IsSubjectWhether this is the subject of the character's focus.

Neocortex Event Logger

Recent game events sent with each message, so the character knows what just happened.

FunctionDescription
PushEvent(WorldContext, Priority, Content)Records an event, Low, Medium or High priority. Content is cut to 64 characters, and the log holds 20 events.
ClearEvents(WorldContext)Clears the log.

Neocortex Microphone Recorder

UNeocortexMicrophoneRecorderComponent records the player's voice as 16 kHz mono WAV.

MemberDescription
StartListening()Waits for the player to speak, records, and once they have been quiet for MaxWaitTime sends the recording on OnWavReady and stops. Call it again for the next answer.
StopListening()Stops without sending.
StartRecording(), StopRecording(bAutoTranscribe)Records on demand, for push to talk. With SmartAgent set, stopping can send the recording to it.
VoiceThresholdThe level, 0 to 1, that counts as speech while listening. Default 0.15.
MaxWaitTimeSeconds of quiet after speech before the recording is sent. Default 1.
LeadInSeconds kept from before the voice crossed the threshold, so a soft first word is not cut. Default 0.3.
SilenceThresholdThe level below which Unreal's voice capture drops audio. Default 0.02. Raise it to ignore more background noise.
GetLevel(), GetWaitProgress()The microphone level and the silence countdown, 0 to 1, for meters.
IsListening(), IsUserSpeaking(), IsRecording()The microphone's state.
GetAvailableDeviceNames(), SetPreferredDevice(Name)Lists the input devices and picks one.

Events: OnWavReady(WavData), OnSpeechStarted, OnSpeechEnded and OnPcmChunk(PcmChunk).

On Android, ask for the microphone with UNeocortexMicrophonePermission::RequestMicrophonePermission(), and check it with HasMicrophonePermission(). On other platforms both report it as granted.

Neocortex Face Animator

UNeocortexFaceAnimator gives a character lip sync on ARKit style mouth morph targets (jawOpen, mouthFunnel, mouthPucker and the rest, in any casing), from the words being spoken and timed to the voice. The mouth rests when the voice stops.

MemberDescription
AgentThe Smart Agent to follow. Empty uses the one on the same actor.
QuizAgentA quiz host to follow.
MeshesThe meshes to animate. Empty uses every skeletal mesh on the owner with morph targets.
BlendSpeedHow fast the mouth moves toward each shape. Default 10.
PlayExpression(ShapeName, Weight), ClearExpressions()Holds a morph target on top of speech.
PlayText(Text, Duration), StartSpeaking(), Rest()Drives the mouth yourself, for speech that does not come from an agent.

UI widgets

The chat widgets are built in code, so no widget asset is needed. They are laid out in pixels on a 1920 x 1080 screen and scale with it.

WidgetDescription
UNeocortexChatUIA whole chat with one character: bubbles with each speaker's initial, a typing bubble, and a text field, voice controls or both. SetAgent(Agent), SetMicrophone(Recorder), SetPushToTalk(bEnabled).
UNeocortexGroupChatUIThe same for a group, with each speaker's name. SetDirector(Director).
UNeocortexQuizUIA whole quiz show screen for one to four players. Set PlayerNames, then SetQuiz(Quiz).
UNeocortexChatTranscriptThe scrolling bubbles on their own: AddMessage, AddNotice, SetTyping, ClearMessages.
UNeocortexTextInputA text field and send button. OnSubmitted(Text).
UNeocortexVoiceInputThe voice controls: the microphone level, whose turn it is, the silence countdown as a ring, and a hold button for push to talk.
UNeocortexLabel, UNeocortexPillButton, UNeocortexToggle, UNeocortexDropdownPieces in the same style for your own Widget Blueprints. Set them up in the Details panel.

UNeocortexChatUI properties: Layout (Bottom centre, or Side: on the left over a fading backdrop), ConversationHeight, bShowTextInput, bShowVoiceInput, bShowSenderNames, PlayerName, InputHint, bAskForAudio, and bAutoSend. Turn off bAutoSend to decide yourself what happens with each message, on OnSubmitted(Text).

The colours, text and shapes come from NeocortexUI in UI/NeocortexUIStyle.h. The Blueprint widgets NeocortexChatPanel, NeocortexTextChatInput and NeocortexAudioChatInput are still there for your own layouts. The chat panel's Writing Direction set to RightToLeft shapes and orders Arabic and Hebrew correctly, and its Message Font Override applies a font to every message.

Handling errors

Every agent, the group director and the quiz agent raise OnRequestError(FNeocortexRequestError). Branch on the error, not on the wording of its message. The checks are member functions in C++ and nodes in UNeocortexFunctionLibrary for Blueprints.

Status and codeCheckMeaning
401IsUnauthorizedMissing or invalid API key.
402 insufficient_creditsIsOutOfCreditsYour team has run out of credits.
403IsForbiddenThe key is inactive, the feature needs a higher plan, or you are not a team member.
429 rate_limit_exceededIsRateLimitedToo many requests. Slow down.
429 player_credit_limit, character_credit_limitIsOutOfCreditsA per-player or per-character limit set on the key was reached.
502 speech_failedIsSpeechFailureThe voice failed. The text still shows.
502 transcription_failedIsTranscriptionFailureSpeech recognition failed.
503 database_unavailableIsRetryableThe service is busy. Try again in a few seconds.
504 upstream_timeoutIsRetryableThe answer took too long. Try again.

FNeocortexRequestError has Status (the HTTP status, or 0 when there was no answer), Code (the API's error code, or empty), Message, bTimedOut and Url. A request that timed out is retryable too.

Requests time out after 30 seconds for messages, 20 for audio and 15 for lookups. Lookups, history and audio are retried once automatically when the error is retryable. Messages are never resent for you: check IsRetryable and send again if you want to.

Handling errors
void AMyActor::HandleError(const FNeocortexRequestError& Error)
{
    if (Error.IsUnauthorized()) { ShowMessage(TEXT("Check the API key in Tools > Neocortex.")); }
    else if (Error.IsOutOfCredits()) { ShowMessage(TEXT("Smart chat is paused for now.")); }
    else if (Error.IsRetryable()) { RetryLater(); }
}

Upgrading from 0.3

0.4 moves the plugin to the Neocortex API v3.

0.30.4
Beats Mode, OnBeatStartedReplies arrive as chat lines: ChatLinesMode, OnChatLineStarted and FNeocortexChatResponseData::Lines.
FNeocortexChatMessageFNeocortexChatHistoryEntry. OnChatHistory also passes the cursor to the next page.
The agent's Language and the Transcription Language settingRemoved. Speech is transcribed in the character's own language.
FNeocortexChatResponseData::ActionStill the first action's keyword. Actions holds every FNeocortexChatAction, with its TargetId.
A failed message was sent again on its ownIt is not. Check IsRetryable and decide.
The old sample maps and BlueprintsReplaced by the new samples.

On this page