Neocortex
IntegrationsGodot SDK

API Reference

GDScript reference for the Neocortex Godot SDK 0.2 with AI NPC agents, chat lines, actions, group chat, quizzes, usage, voice, lip sync and errors in Godot 4.

Every node and class the Neocortex Godot SDK 0.2 ships, with its properties, methods and signals. For setup, start with the Quick Start.

The SDK follows Godot's conventions: nodes you add to a scene, snake_case members, signals for events, and coroutines you await for calls that return a result. Everything talks to the Neocortex API v3.

Node or classWhat it does
NeocortexSmartAgentOne character. Sends text or voice, plays the reply as chat lines and runs the actions it asks for.
NeocortexGroupDirectorSeveral characters in one conversation.
NeocortexQuizAgentA character hosts a quiz from a question set.
NeocortexUsageGateYour team's usage and per-player or per-character limits, as flags and signals.
NeocortexInteractableMarks a 3D object the character can see. Actions can target it by id.
NeocortexEventLoggerRecent gameplay events, sent with each message as context.
NeocortexAudioReceiverThe microphone, with voice detection or push to talk.
NeocortexFaceAnimatorLip sync on ARKit style mouth blend shapes.
UI nodesChat panel, inputs, thinking indicator, and the controllers that wire them to an agent, a group or a quiz.
ApiRequestEvery API endpoint as an awaitable call, for full control.
NeocortexSessionManagerConversation sessions and the player id.

NeocortexSmartAgent

NeocortexSmartAgent (a Node) is one character. Set its character_id, then call one of the send methods. The reply arrives as chat lines, each with its own emotion, and the agent plays them for you: voiced, as text, or whole, depending on chat_lines_mode.

While a reply is pending or still playing, is_speaking is true. Anything you send in that window is queued and sent once the reply ends, so the player cannot talk over the character. This holds in every mode except OFF.

Properties

PropertyDefaultDescription
character_id""The character this agent talks as. The Inspector shows a dropdown of your characters.
chat_lines_modePER_LINE_AUDIOHow a reply is delivered. See Chat lines.
audio_playernoneWhere the voice plays: an AudioStreamPlayer, AudioStreamPlayer2D or AudioStreamPlayer3D. Falls back to one under the agent, and one is created for a voiced mode when there is none.
load_history_on_startfalseFetch this character's stored conversation when the scene starts and raise it on chat_history_received. Only runs when a session already exists.
auto_voice_inputtrueListen through a NeocortexAudioReceiver under or beside the agent, and answer by itself. Turn it off when a chat UI, a group director or your own script feeds the agent.
action_triggerWHEN_RESPONSE_RECEIVEDWhen a reply's actions run. See Actions.
delay_between_actions0.0Seconds to wait after one action finishes before the next one starts. 0 runs them back to back.
stream_speechtruePlay speech as it is generated instead of waiting for the whole clip. Falls back to whole clips when streaming is not available.
bodyparentWhere the character stands, for perception. Defaults to the parent when it is a Node3D.
perception_radius0.0Only perceive interactables within this many meters. 0 means no limit.
max_perceived_entities10The most interactables sent with one message, nearest first.
is_speakingread onlyTrue while a reply is pending or its lines are still playing.
is_running_actionsread onlyTrue while the reply's actions are running.

Methods

MethodDescription
text_to_text(message: String)Sends a text message.
text_to_audio(message: String)Sends a text message. In OFF mode, also fetches one clip for the whole reply and raises it on audio_response_received.
audio_to_text(audio: AudioStreamWAV)Transcribes the recording, raises transcription_received, then sends it.
audio_to_audio(audio: AudioStreamWAV)The same as audio_to_text. In OFF mode, also fetches one clip for the whole reply.
register_action(keyword: String, handler: Callable)Assigns what performs an action keyword. See Actions.
unregister_action(keyword: String)Removes a handler.
get_chat_history(limit: int = 10)Fetches the last messages of this character's session and raises chat_history_received.
request_chat_history(limit: int = 10, before: String = "")Awaitable. Returns a page of history as a NeocortexApiChatHistory, without raising the signal. See History.
generate_chat_line_audio(line: NeocortexChatLine)Awaitable. Returns one voice clip for a line, in its emotion.
stop_speaking()Stops whatever the character is saying and drops queued input.
get_session_id()The current conversation session id, or "".
clean_session_id()Forgets the conversation, so the next message starts a new session.
speak(message: NeocortexGroupMessage)Awaitable. Plays a reply produced elsewhere through this character. The group director uses it.
get_api_request()The ApiRequest node this agent uses, for endpoints it does not wrap.

In the chat lines modes (PER_LINE_AUDIO, SINGLE_AUDIO, TEXT), text_to_text and text_to_audio behave the same: chat_lines_mode decides whether the reply is voiced. The _to_audio variants only change what happens in OFF mode.

Signals

SignalDescription
chat_line_started(line: NeocortexChatLine)A line drops in. Add it to your chat panel here.
emotion_changed(emotion: NeocortexEnums.Emotions)Each line's emotion as it drops in. Drive animation here.
composing_next_lineTEXT mode: raised in the pause before the next line, for a typing indicator.
reply_finishedThe whole reply has finished playing.
chat_response_received(response: NeocortexChatResponse)The whole reply, as soon as it arrives.
audio_response_received(audio: AudioStream)A clip of speech: each spoken line in the voiced modes, or the whole reply in OFF mode with text_to_audio.
transcription_received(text: String)What the player said, after an audio_to_* call.
chat_history_received(history: Array)An array of NeocortexChatHistoryEntry.
actions_completedAll of a reply's actions have run.
unhandled_action(action: NeocortexChatAction)An action arrived with no handler registered.
request_failed(error: String)A request failed, with a short message.
request_error(error: NeocortexApiError)The same failure, classified. See Handling errors.

Chat lines

A reply is split into ordered lines, each with its own emotion. chat_lines_mode decides how they are delivered.

chat_lines_modeShowsPlays
PER_LINE_AUDIO (default)each line as it is spokeneach line in its own emotion
SINGLE_AUDIOlines one after anotherone clip for the whole reply
TEXTlines at reading pacenothing
OFFthe whole reply in chat_response_receivednothing. text_to_audio and audio_to_audio raise audio_response_received for you to play.

PER_LINE_AUDIO voices each line separately, so it uses the most of your plan. SINGLE_AUDIO voices one clip per reply, and TEXT adds no voice at all.

In the voiced modes the agent checks your team's usage first. The check is cached for 30 seconds. When your team has run out of usage, the agent shows the reply as text only. When usage is low, PER_LINE_AUDIO voices the reply as one clip instead of one per line.

A voiced mode needs somewhere to play. Without an audio_player, the agent creates an AudioStreamPlayer when the scene starts.

Chat lines
agent.chat_lines_mode = NeocortexEnums.ChatLinesMode.TEXT
agent.chat_line_started.connect(func(line: NeocortexChatLine):
	thinking_indicator.display(false)
	chat_panel.add_message(line.text, false, "Cora"))
agent.composing_next_line.connect(func(): thinking_indicator.display(true))

Actions

Actions are the keywords you author on the character's Action node. A reply can carry several, in the order the character wants to perform them. Each one is a NeocortexChatAction with a name and a target_id, the id of the interactable it applies to, or "".

Register a handler for each keyword with register_action. The handler receives the action. It can be a plain function, a coroutine, or return a Signal. The next action waits until the current one is done, so "jump, then dance" plays in order.

register_action
func _ready() -> void:
	agent.register_action("JUMP", func(action: NeocortexChatAction):
		animation_player.play("jump")
		return animation_player.animation_finished)
	agent.register_action("WAVE", func(action: NeocortexChatAction):
		animation_tree.set("parameters/wave/request", AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE))
	agent.unhandled_action.connect(func(action: NeocortexChatAction):
		print("No handler for ", action.name))

action_trigger decides when a reply's actions start:

action_triggerActions run
WHEN_RESPONSE_RECEIVED (default)the moment the reply arrives, so the character may act before it speaks
WHEN_SPEECH_STARTSas the character starts speaking
AFTER_REPLY_SPOKENonce the character has finished speaking the reply

The last two need a chat lines mode. In OFF mode they fall back to running on arrival, with a warning.

To give each action room to breathe, set delay_between_actions to the seconds to wait after one action finishes before the next starts. It is 0 by default, so actions run back to back.

NeocortexActionQueue from 0.1 still works for existing projects. Its handlers now receive (action, response). New code should use register_action on the agent, which honors action_trigger.

History

Conversations are stored per character session. Set load_history_on_start to replay the stored conversation when the scene starts, or call get_chat_history(limit) and listen to chat_history_received.

To page back through a long conversation, await request_chat_history. Pass the previous page's next_cursor as before to load older messages.

Paging through history
var page := await agent.request_chat_history(20)
while page != null:
	for entry in page.messages:
		print(entry.name if not entry.is_user() else "You", ": ", entry.content)
	if page.next_cursor.is_empty():
		break
	page = await agent.request_chat_history(20, page.next_cursor)

NeocortexApiChatHistory has session_id, messages (oldest first) and next_cursor (empty at the start of the conversation).

Streaming

stream_speech is on by default. Speech plays as it is generated, so the voice starts before the whole line is ready. When the server does not offer streamed speech, the agent falls back to whole clips.

Perception

Every NeocortexInteractable in the scene is sent with each message, nearest to body first and capped at max_perceived_entities, so the character knows what is around it and where. The agent also sends its own position. Use perception_radius to ignore things far away.

Data classes

NeocortexChatResponse

The whole reply, raised on chat_response_received.

MemberDescription
messageThe whole reply, every line's text joined.
spoken_messageThe reply as it should be spoken, with numbers, dates and currencies spelled out.
linesArray[NeocortexChatLine], the reply's lines in order.
emotionThe first line's emotion.
actionsArray[NeocortexChatAction], every action in order. Empty when none.
actionThe first action's name, for code that reads a single action.
action_names()The action names in order, as a PackedStringArray.
flow_stateThe Conversation Flow checkpoint this turn landed on. Empty when the character has no flow.
character_id, nameThe character that replied, and its display name.
session_idThe conversation session this turn belongs to.
metadataThe scene's interactables after the turn, as the server echoed them.

NeocortexChatLine

MemberDescription
textThe line's text.
emotionA NeocortexEnums.Emotions value.
spoken_textThe phonetic text for speech, or "" when the server sent none.
speech_text()spoken_text when there is one, else text.

NeocortexChatAction

MemberDescription
nameThe action keyword, for example GO_TO_LOCATION.
target_idThe id of the interactable it applies to, or "".

NeocortexChatHistoryEntry

MemberDescription
contentWhat was said.
sender"USER" for the player, "ASSISTANT" for a character.
is_user()True when the player said it.
nameThe speaker's display name. Empty for the player.
speaker_character_idIn a group session, which character spoke.
addressed_toIn a group session, who the line was directed at.
emotionThe emotion a character's line was delivered in.
actionsThe action names this turn triggered.
created_atWhen it was said.

NeocortexGroupDirector

NeocortexGroupDirector (a Node) runs one conversation across several NeocortexSmartAgent nodes. It sends one turn for the whole cast and plays each speaker's reply through its own agent, one after the other. A cast of two or more characters needs a Pro or Team plan. See Group Chat for a walkthrough.

PropertyDescription
agentsArray[NeocortexSmartAgent], the cast. Up to six characters. Adding an agent turns its auto_voice_input off.
max_turnsThe most characters that speak in one turn, 1 to 5. Default 5.
session_idThe shared session. Empty until the first turn. Kept in memory only.
is_busyTrue while a turn is being fetched or played out.
MethodDescription
send(message: String)The player speaks to the group. The cast decides who answers.
send_to(target, message: String)One character answers. target is an agent or a character id.
continue_scene()No player input: the cast talks among themselves.
send_audio(audio: AudioStreamWAV)Transcribes the recording, raises player_speech, then sends it like send.
add_agent(agent), remove_agent(agent)Change the cast while the conversation runs.
get_history(limit: int = 20, before: String = "")Awaitable. Loads the shared transcript and raises history_received. Returns null before the first turn.
clear_session()Forgets the session, so the next turn starts a new conversation.
SignalDescription
turn_startedA turn starts. Lock your input here.
group_response_received(response: NeocortexGroupChatResponse)The whole turn, once, before anyone speaks.
speaker(message: NeocortexGroupMessage)A character is about to speak its part.
turn_finishedEvery speaker has finished, or the turn could not run.
player_speech(text: String)The transcript of send_audio.
history_received(history: Array)An array of NeocortexChatHistoryEntry.
request_failed(error: String), request_error(error: NeocortexApiError)A request failed.

Input sent while a turn is running is ignored, with a warning. Wait for turn_finished.

NeocortexQuizAgent

NeocortexQuizAgent (a Node) lets a character host a quiz, a game show or a spoken test from a question set. The server handles question order, retries, hints and scoring. Your game hands over what the player said and renders what comes back. Quizzes need a Team plan. See Quiz for a walkthrough.

PropertyDefaultDescription
character_id""The host.
question_set_id""The question set to play. The Inspector shows a dropdown of your sets.
question_count0Questions in one run. 0 uses the set's own count.
question_orderSET_DEFAULTSET_DEFAULT, IN_ORDER or SHUFFLED.
player_id""Your own id for a single player. Empty uses the device's player id.
participants[]Array[NeocortexQuizParticipant], everyone playing in a game with more than one player.
begin_on_startfalseStart the quiz as soon as the scene runs.
speak_host_linestrueSpeak the host's lines in the character's voice.
stream_host_speechtruePlay each line as its voice arrives.
audio_playernoneWhere the host's voice plays. One is created when none is assigned.
queue_input_while_busytrueHold what the player says while the host is busy, and send it once ready.
max_pending_input_age4.0Seconds a held answer stays worth sending.
MethodDescription
begin(players: Array = [])Starts the quiz. Pass NeocortexQuizParticipants to replace participants.
say(text: String, typed: bool = false)What the player said or typed. A typed answer is judged as written.
choose(option_id: String)A tapped option, for multiple choice and true or false questions.
pass_turn()The player gives no answer: they skipped, or your timer ran out.
say_as(participant_id, text, typed = false), choose_as(participant_id, option_id), pass_as(participant_id)The same, naming which player in a multiplayer game.
resync()Reads the run back from the server and puts the agent in step, after a turn whose response never arrived.
abort()Abandons whatever is in flight and silences the host, without ending the run on the server.
SignalDescription
host_line(line: NeocortexQuizLine)A line the host says, as it starts.
emotion_changed(emotion)The host's emotion changed.
host_finishedThe host has finished speaking this turn.
question_changed(question: NeocortexQuizQuestion)A new question, raised as the host starts asking it.
upcoming_question(upcoming)The next question's question_id and keyword, so its scene can load early.
expecting_changed(expecting: NeocortexEnums.QuizExpecting)What to collect next. Open the microphone on anything but NOTHING.
result(results: Array)How the last answer was judged, per player.
leaderboard_changed(leaderboard: Array)The standings changed.
pending_changed(pending: PackedStringArray)The players the round is still waiting on.
busy_changed(busy: bool)A turn is in flight, or done.
quiz_finished(leaderboard: Array)The host has signed off, with the final standings.
input_dropped(text: String, reason)Something the player said that never reached the host, and why.
turn_received(turn: NeocortexQuizTurnResponse)The whole turn, if you would rather read it yourself.
credits_exhausted(code: String)Your team has run out of usage, or a usage limit was reached. Input stays closed until resync().
request_failed(error: String), request_error(error: NeocortexApiError)A request failed.

State you can read at any time: session_id, current_question, progress (asked, total), expecting, is_busy, is_finished, pending_participants, answered_participants, attempt, attempts_left, hint_given, last_intent, last_error_code.

NeocortexUsageGate

NeocortexUsageGate turns the account and usage endpoints into flags and signals, so your game can turn smart features off before a limit is hit, instead of failing mid-conversation. Its calls don't count toward your usage. Results are cached.

It is a RefCounted, not a node. Create it with a host node it can add its request node to:

NeocortexUsageGate
var gate: NeocortexUsageGate

func _ready() -> void:
	gate = NeocortexUsageGate.new(self)
	gate.credits_empty.connect(func(_usage): smart_npc_button.disabled = true)
	gate.player_over_limit.connect(func(_usage): show_message("You've reached today's limit."))
	gate.start_auto_refresh(300.0)

func _on_send_pressed(message: String) -> void:
	if await gate.can_use_service("", agent.character_id):
		agent.text_to_text(message)
MemberDescription
refresh_usage(player_id = "", character_id = "")Awaitable. Fetches usage, raises the signals and returns a NeocortexApiUsage, or null on failure. An empty player_id uses NeocortexSessionManager.get_player_id().
get_usage_cached(player_id = "", character_id = "")Awaitable. The cached usage while it is younger than min_refresh_interval, otherwise a fresh fetch.
can_use_service(player_id = "", character_id = "")Awaitable. False when your team has run out of usage, or the player or character is over its limit. Returns true when no usage data is available at all. can_use_smart_npc is the same call.
refresh_account()Awaitable. Returns a NeocortexApiAccount with your plan tier, the masked owner email and next_refresh.
start_auto_refresh(interval_seconds = 300.0, player_id = "", character_id = ""), stop_auto_refresh()Refresh usage on a timer.
min_refresh_intervalSeconds a cached result is served. Default 30.0.
last_usage, last_accountThe last results.
SignalRaised when
usage_updated(usage)Every refresh.
low_credits(usage)Your team's usage is running low.
credits_empty(usage)Your team has run out of usage.
player_over_limit(usage)The player reached the per-player limit set on the key.
character_over_limit(usage)The character reached the per-character limit.
request_failed(error: String)A usage request failed.

The limit signals fire on the change only, so a popup hooked to one shows once, not on every refresh.

NeocortexApiUsage has status (NeocortexEnums.UsageStatus: OK, LOW or EMPTY), is_player_over_limit() and is_character_over_limit(). When you pass a player or character id, player and character carry their usage, with over_limit. player.interactions_today counts the player's messages today.

NeocortexInteractable

NeocortexInteractable (a Node3D) marks an object the character can see. Every interactable in the scene is sent with each message, with its position and properties, so the character knows what is around it. An action can then target it by id.

PropertyDescription
idThe id actions use as target_id. Leave it empty to derive one from the node's name and path. The Inspector shows the resolved id with a Copy button.
propertiesArray[Dictionary] of { "name": ..., "value": ... } pairs, for example color and red. A name property is what the character calls it. Filled with the node name when you add it in the editor.
typeOBJECT or CHARACTER. Set to CHARACTER automatically when a NeocortexSmartAgent sits on this node or directly under it.
MethodDescription
get_id()The explicit id, or the derived one.
get_display_name()The name property, or the node name.
get_agent()The agent this interactable represents, when it is a character.

Interactables join the neocortex_interactable group (NeocortexInteractable.GROUP), so finding the target of an action is a short loop:

Walking to a target
func _ready() -> void:
	agent.register_action("GO_TO_LOCATION", _go_to)

func _go_to(action: NeocortexChatAction) -> void:
	for node in get_tree().get_nodes_in_group(NeocortexInteractable.GROUP):
		if node.get_id() == action.target_id:
			await walk_to(node.global_position)
			return

NeocortexEventLogger

NeocortexEventLogger is a static buffer of recent gameplay events. They are sent with every chat request, so the character knows what just happened in your game.

NeocortexEventLogger
NeocortexEventLogger.push(NeocortexEnums.EventPriority.HIGH, "Player picked up the ancient sword")
MethodDescription
push(priority, content: String, date: String = "")Records an event. priority is LOW, MEDIUM or HIGH.
push_log(log: NeocortexEventLog)Records a prepared event.
get_logs()The events that will be sent, as a JSON string.
clear()Clears every event.

Each message carries at most 20 events: high priority first, newest first within each priority, sent in their original order. An event longer than 64 characters is dropped with a warning. Events stay in the buffer until you call clear().

NeocortexAudioReceiver

NeocortexAudioReceiver (a Node) is the microphone. In voice detection mode it listens, detects speech by its level, and ends the recording after a moment of silence. In push to talk mode a button starts and stops it. The trimmed recording is raised on audio_recorded.

PropertyDefaultDescription
use_push_to_talkfalseRecord while a button is held, instead of by voice detection.
amplitude_threshold0.1Input level, 0 to 1, above which the player counts as speaking.
max_wait_time1.0Seconds of silence after speech that end a recording.
keep_microphone_openfalseKeep the input running between recordings, so the next one starts with no warm up. Uses a little CPU while idle.
request_permission_on_starttrueAsk for microphone permission when the scene starts (Android).
amplitude, elapsed_wait_time, is_user_speakingread onlyLive values for your own UI.
MethodDescription
start_microphone()Starts listening.
stop_microphone()Stops and raises the recording. Push to talk calls this on release.
is_listening()True while listening.
set_push_to_talk(value: bool)Switches mode.
get_microphones()The input devices, for a picker.
select_microphone(index: int)Picks a device and remembers it in user://.
SignalDescription
audio_recorded(audio: AudioStreamWAV)A recording with speech in it.
recording_failed(error: String)The microphone could not start, with the reason.
permission_deniedThe player refused microphone access.

The microphone closes after each recording. A NeocortexSmartAgent with auto_voice_input, and the chat UIs, open it again after each reply. Sounds shorter than 0.15 seconds, like a cough or a click, are not sent. A recording stops at 29 seconds.

The receiver records through a muted NeocortexRecord audio bus, created when the scene starts if your bus layout has none. It needs Project Settings > Audio > Driver > Enable Input.

NeocortexFaceAnimator

NeocortexFaceAnimator (a Node) moves a character's mouth to the words it speaks, on ARKit style blend shapes (jawOpen, mouthFunnel, mouthPucker and so on) on MeshInstance3D nodes. It follows the text of each line and is timed to the clip, so it needs no audio analysis.

Add it under or beside a NeocortexSmartAgent. It finds the agent and the meshes by itself.

PropertyDescription
agentThe agent whose speech this face follows. Defaults to the parent or a sibling.
face_rootThe node the face meshes are under. Defaults to the agent's body, else its parent.
meshesThe meshes to animate. Empty means every MeshInstance3D with blend shapes under face_root.
blend_speedHow fast the mouth moves toward each shape. Default 10.0.
MethodDescription
play_text(text: String, duration: float)Moves the mouth through text over duration seconds.
start_speaking()Random mouth movement, for speech you have no text for.
rest()Closes the mouth.
play_expression(shape_name: String, weight: float = 1.0)Holds a blend shape on top of speech, for example a smile.
clear_expressions()Releases held shapes.

UI nodes

The ready-made widgets live in addons/neocortex-godot-sdk/nodes/. Instance the scenes, or add them from Project > Tools > Neocortex. A controller node wires them to an agent, a group or a quiz.

Controllers

NodeWires
NeocortexChatUIOne NeocortexSmartAgent to a chat panel, a text input, a voice input and a thinking indicator. Turns the agent's auto_voice_input off, because it feeds the agent itself.
NeocortexGroupChatUIA NeocortexGroupDirector to the same widgets. Every speaker comes back as a named bubble.
NeocortexQuizUIA NeocortexQuizAgent to a chat panel, a text input and a thinking indicator. The input only shows while the host is waiting for an answer.

Each controller has player_name (default "You") and export slots for its widgets. Every slot is optional: an empty one is found among the controller's children. NeocortexChatUI and NeocortexGroupChatUI also take a voice_input, a NeocortexAudioReceiver.

Widgets

SceneDescription
NeocortexChatPanelScrollable chat with bubbles, newest at the bottom. add_message(text, is_user, sender), show_writing_indicator(visible), clear_messages(). Options: display_avatars, display_sender_names, fade, writing_direction for right to left text, font_overwrite, and the player and character bubble colors.
NeocortexMessageOne bubble, sized to its text. show_typing(true) turns it into the three-dot typing bubble.
NeocortexTextChatInputA text box with a send button. Raises send_submitted(message).
NeocortexAudioChatInputThe round voice widget: a level disc, a state disc with the silence countdown, and a hold to talk button in push to talk mode. Set its audio_receiver.
NeocortexThinkingIndicatorThe character's avatar with three pulsing dots. display(visible).
NeocortexMicrophoneDropdownPicks the input device. The choice is saved for next time.
NeocortexPushToTalkButtonA hold to talk button. Raises pushed and released.

The widgets use NeocortexTheme.tres: dark pills with amber outlines and accents. Edit it, or set your own theme on a widget, to restyle them. The bubble colors are on NeocortexChatPanel.

ApiRequest

ApiRequest (a Node) is the API client every component uses. Use it directly when you want full control. It has to be in the scene tree: add it as a child, or get the agent's with agent.get_api_request().

Calls that return a value are coroutines: await them. They return null (or "" or false) on failure, after raising request_failed and request_error.

ApiRequest
var api := ApiRequest.new()

func _ready() -> void:
	add_child(api)
	var characters = await api.get_characters()
	if characters != null:
		for character in characters:
			print(character.name, " ", character.id)

	var clip := await api.generate_audio("YOUR_CHARACTER_ID", "Well done!", "PLEASED")
	if clip != null:
		$AudioStreamPlayer.stream = clip
		$AudioStreamPlayer.play()
MethodReturns
request_chat(character_ids, session_id = "", message = "", speaker_character_id = "", max_turns = 0, metadata = null, events = null, self_character_id = "", play_as = "")A NeocortexGroupChatResponse for one character or a cast. An empty message is an ambient turn. Interactables and events are gathered for you when left null. request_group_chat is the same call.
request_chat_turn(character_id, message)A NeocortexChatResponse for one character. Stores the session id for you.
request_chat_history(session_id, limit = 10, before = "")A NeocortexApiChatHistory page.
request_transcription(character_id, audio)The text of a recording, without chatting.
generate_audio(character_id, message, emotion, spoken_text = "")An AudioStream of message, voiced in emotion (uppercase, for example "HAPPY").
get_account()A NeocortexApiAccount.
get_usage(player_id = "", character_id = "")A NeocortexApiUsage.
get_characters()Your team's characters, each with id and name.
get_question_sets()Your team's question sets, each with id, name and question_count.
begin_quiz(...), continue_quiz(...), get_quiz_session(session_id)The quiz endpoints NeocortexQuizAgent runs on.
abort()Cancels everything this node has in flight. Cancelled requests raise no failure.

send_text_to_text, send_text_to_audio, send_audio_to_text and send_audio_to_audio run a whole turn and raise transcription_received, chat_response_received and audio_response_received.

MemberDescription
ApiRequest.base_url_overrideStatic. Send every request to another server, for example your own proxy. Empty uses https://api.neocortex.link/v3.
retry_attempts, retry_delayHow often, and after how many seconds, a retryable failure of a lookup, history or audio request is sent again. Defaults 1 and 1.5. Chat and quiz turns are never resent for you.
last_api_error, last_error, last_error_code, last_response_code, was_cancelledThe last failure.

Requests time out after 30 seconds for chat and quiz turns, 20 seconds for audio and 15 seconds for lookups.

NeocortexSessionManager

NeocortexSessionManager keeps one conversation session per character, saved in user://neocortex_sessions.cfg, so conversations survive restarts and work in exported builds. It also owns the player id sent with every request.

MemberDescription
get_session_id(character_id)The stored session id, or "".
set_session_id(character_id, session_id)Stores a session id.
clean_session_id(character_id)Clears it, so the next message starts a new conversation.
get_player_id()The id this player is known by: player_id_override, else the device id, else a random id stored once.
player_id_overrideStatic. Set it to your own player id, like an account or platform user id, to track usage and memory per player across devices.
Start a fresh conversation
NeocortexSessionManager.clean_session_id(agent.character_id)

NeocortexEnums

EnumValues
EmotionsNEUTRAL, HAPPY, PLEASED, DISAPPOINTED, UPSET, AMAZED, CURIOUS, CONFUSED, ALARMED, FASCINATED, IMPRESSED, ANNOYED, ANGRY, CONFIDENT, REASSURED, CONCERNED, SCARED
ChatLinesModePER_LINE_AUDIO, SINGLE_AUDIO, TEXT, OFF
ActionTriggerWHEN_RESPONSE_RECEIVED, WHEN_SPEECH_STARTS, AFTER_REPLY_SPOKEN
EventPriorityLOW, MEDIUM, HIGH
InteractableTypeCHARACTER, OBJECT
UsageStatusOK, LOW, EMPTY
WritingDirectionLEFT_TO_RIGHT, RIGHT_TO_LEFT
QuizExpectingNOTHING, ANSWER, CONFIRMATION
QuizIntentUNCLEAR, ANSWER, AFFIRM, DECLINE, REPEAT, HINT, STOP
QuizLineRoleREACTION, GREETING, QUESTION, CLOSING
QuizVerdictUNANSWERED, CORRECT, PARTIAL, INCORRECT
QuizInputDropReasonSUPERSEDED, EXPIRED, FINISHED, NO_SESSION, FAILED, BUSY

NeocortexEnums.emotion_to_string(emotion) gives the title case name ("Happy"), emotion_to_upper(emotion) the form the audio endpoints expect ("HAPPY"), and emotion_from_string(value) parses any casing.

Handling errors

Every agent, the group director, the quiz agent and ApiRequest raise request_failed(message) and request_error(NeocortexApiError). Branch on the error, not on the wording of its message.

Status and codeHelperMeaning
401is_unauthorized()Missing or invalid API key.
402 insufficient_creditsis_out_of_credits()Your team has run out of usage.
403is_forbidden()The key is inactive, the feature needs a higher plan, or you are not a team member.
429 rate_limit_exceededis_rate_limited()Too many requests. Slow down.
429 player_credit_limit, character_credit_limitis_out_of_credits()A per-player or per-character usage limit set on the key was reached.
502 speech_failedis_speech_failure()The voice failed. The text still shows.
502 transcription_failedis_transcription_failure()Speech recognition failed.
503 database_unavailableis_retryable()The service is busy. Try again in a few seconds.
504 upstream_timeoutis_retryable()The answer took too long. Try again.

NeocortexApiError has status (the HTTP status, or 0 when there was no answer), code (the API's error code, or ""), message, timed_out, cancelled and url. A request that timed out is retryable too.

Lookups, history and audio are retried once automatically when the error is retryable. Messages are never resent for you: check is_retryable() and send again if you want to.

Handling errors
agent.request_error.connect(func(error: NeocortexApiError):
	if error.is_unauthorized():
		show_message("Check the API key in the Neocortex dock.")
	elif error.is_out_of_credits():
		show_message("Smart chat is paused for now.")
	elif error.is_retryable():
		await get_tree().create_timer(2.0).timeout
		agent.text_to_text(last_message))

Upgrading from 0.1

0.2 moves the SDK to the Neocortex API v3. A key saved by 0.1 is picked up once and moved to neocortex_settings.tres.

0.10.2
request_beats, BeatsMode, NeocortexBeatRemoved. Replies always arrive as chat lines: chat_line_started and NeocortexChatResponse.lines.
NeocortexChatResponse.beatsNeocortexChatResponse.lines
NeocortexChatMessageNeocortexChatHistoryEntry
NeocortexChatResponse.actionsHolds NeocortexChatAction objects. action_names() gives the keywords.
audio_response_received(AudioStreamMP3)audio_response_received(AudioStream)
NeocortexActionQueue handlersReceive (action, response). New code should use agent.register_action().

All requests go to https://api.neocortex.link/v3. The player id comes from NeocortexSessionManager.get_player_id(). The microphone choice is now saved in user://, and the recording bus is created when it is missing. The full list is in the SDK's CHANGELOG.

On this page