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
| Property | Description |
|---|---|
ProjectId | The character's id. The Pick button next to it lists your characters. |
ChatLinesMode | How replies are delivered. See Chat lines. Default PerLineAudio. |
AudioComponent | Where the voice plays. Empty uses, or creates, one on the owner. |
bStreamSpeech | Play speech as it is synthesized, so the voice starts sooner. Default on. |
bLoadHistoryOnStart | Fetch and replay this character's stored conversation when play begins. |
ActionTrigger | When a reply's actions run: WhenResponseReceived, WhenSpeechStarts or AfterReplySpoken. |
DelayBetweenActions | Seconds to wait after one action finishes before the next starts. Default 0. |
bIncludeAllInteractables | Send what the character perceives with each message. Default on. See Perception. |
bUseRadiusFilter, SearchRadius | Only send interactables within SearchRadius (default 2000) of the owner. |
MaxPerceivedEntities | How many interactables one message carries, nearest first. Default 10. |
Functions
| Function | Description |
|---|---|
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
| Event | Fires |
|---|---|
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. |
OnComposingNextLine | In Text mode, during the pause before the next line, for a typing indicator. |
OnReplyFinished | Once 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. |
OnActionsCompleted | When 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:
| Mode | What you get | Cost |
|---|---|---|
PerLineAudio (default) | Each line voiced in its own emotion, in order. | About 1 audio credit per line |
SingleAudio | Lines drop in while one clip voices the whole reply. | 1 audio credit |
Text | Lines drop in with an emotion each, OnComposingNextLine before the next. | No extra cost |
Off | The 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.
// 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
| Member | Description |
|---|---|
Response | The whole reply: every line's text joined. |
Lines | The FNeocortexChatLines that make up the reply, in order. |
Actions | Every FNeocortexChatAction the character triggered, in order. Action is the first one's keyword. |
Emotion | The first line's emotion. |
FlowState | The Conversation Flow checkpoint this turn landed on, or empty. |
SpokenResponse | The reply as spoken, with numbers, dates and currencies spelled out. |
SessionId, CharacterId, Name | The session, and the character that replied. |
Metadata | The 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
| Member | Description |
|---|---|
Content | The message text. |
Sender | "USER" for the player, "ASSISTANT" for a character. |
Name, SpeakerCharacterId | Who spoke, for character lines. |
AddressedTo | In a group session, who the line was directed at. |
Emotion, Actions | The emotion and action keywords of a character line. |
CreatedAt | When 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.
| Member | Description |
|---|---|
Agents | The characters in the scene. |
MaxTurns | How many characters speak in one turn, 1 to 5. Default 5. |
bIncludeAllInteractables | Send every interactable with each turn. Default on. |
SessionId | The 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.
| Property | Description |
|---|---|
CharacterId, QuestionSetId | The host and the question set, each with a Pick button. |
QuestionCount | Questions in one run. 0 uses the set's count. |
QuestionOrder | SetDefault, InOrder or Shuffled. |
PlayerId | Your id for a single player. Empty uses the device's player id. |
Participants | Everyone playing, in a game with more than one player. |
bBeginOnStart | Start when play begins. |
bSpeakHostLines, bStreamHostSpeech | Speak the host's lines, and play each as its voice arrives. Both default on. |
AudioComponent | Where the host's voice plays. |
bQueueInputWhileBusy, MaxPendingInputAge | Hold input while the host is busy, for up to 4 seconds by default. |
| Function | Description |
|---|---|
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);
}| Member | Description |
|---|---|
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. |
MinRefreshInterval | Seconds a cached result is served before a new request. Default 30. |
LastUsage, LastAccount, bHasUsage, bHasAccount | The 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.
| Property | Description |
|---|---|
Name | What the character calls it. Empty uses the actor's name. |
Properties | What it is and its state, as name and value pairs, such as Color: Red. |
Id | The id actions use as TargetId. Empty derives a stable one from the actor. GetId() returns it. |
CharacterId | Set when the actor is a Neocortex character. Empty uses the Smart Agent on the same actor, if any. |
Type | CHARACTER or OBJECT. Empty derives it. |
IsSubject | Whether 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.
| Function | Description |
|---|---|
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.
| Member | Description |
|---|---|
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. |
VoiceThreshold | The level, 0 to 1, that counts as speech while listening. Default 0.15. |
MaxWaitTime | Seconds of quiet after speech before the recording is sent. Default 1. |
LeadIn | Seconds kept from before the voice crossed the threshold, so a soft first word is not cut. Default 0.3. |
SilenceThreshold | The 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.
| Member | Description |
|---|---|
Agent | The Smart Agent to follow. Empty uses the one on the same actor. |
QuizAgent | A quiz host to follow. |
Meshes | The meshes to animate. Empty uses every skeletal mesh on the owner with morph targets. |
BlendSpeed | How 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.
| Widget | Description |
|---|---|
UNeocortexChatUI | A 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). |
UNeocortexGroupChatUI | The same for a group, with each speaker's name. SetDirector(Director). |
UNeocortexQuizUI | A whole quiz show screen for one to four players. Set PlayerNames, then SetQuiz(Quiz). |
UNeocortexChatTranscript | The scrolling bubbles on their own: AddMessage, AddNotice, SetTyping, ClearMessages. |
UNeocortexTextInput | A text field and send button. OnSubmitted(Text). |
UNeocortexVoiceInput | The 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, UNeocortexDropdown | Pieces 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 code | Check | Meaning |
|---|---|---|
| 401 | IsUnauthorized | Missing or invalid API key. |
402 insufficient_credits | IsOutOfCredits | Your team has run out of credits. |
| 403 | IsForbidden | The key is inactive, the feature needs a higher plan, or you are not a team member. |
429 rate_limit_exceeded | IsRateLimited | Too many requests. Slow down. |
429 player_credit_limit, character_credit_limit | IsOutOfCredits | A per-player or per-character limit set on the key was reached. |
502 speech_failed | IsSpeechFailure | The voice failed. The text still shows. |
502 transcription_failed | IsTranscriptionFailure | Speech recognition failed. |
503 database_unavailable | IsRetryable | The service is busy. Try again in a few seconds. |
504 upstream_timeout | IsRetryable | The 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.
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.3 | 0.4 |
|---|---|
Beats Mode, OnBeatStarted | Replies arrive as chat lines: ChatLinesMode, OnChatLineStarted and FNeocortexChatResponseData::Lines. |
FNeocortexChatMessage | FNeocortexChatHistoryEntry. OnChatHistory also passes the cursor to the next page. |
The agent's Language and the Transcription Language setting | Removed. Speech is transcribed in the character's own language. |
FNeocortexChatResponseData::Action | Still the first action's keyword. Actions holds every FNeocortexChatAction, with its TargetId. |
| A failed message was sent again on its own | It is not. Check IsRetryable and decide. |
| The old sample maps and Blueprints | Replaced by the new samples. |
Quiz
Run a spoken quiz, game show or test in Unreal Engine 5 with a Neocortex AI character as the host, for one player or several, using the Quiz Agent and a question set.
Quick Start
Install the Neocortex Godot SDK and talk to an AI character in Godot 4 by text or voice, with a ready chat scene, seven samples and a few lines of GDScript.