Cortex#

Cortex is the component that turns the rest of a recipe into an agent. Every action, action server, service, routine and plugin action the recipe has becomes a tool it can call, and a goal in plain language becomes a plan of those calls, carried out while it watches the results. If an agentic harness is what lets a language model work a codebase, Cortex is the same idea applied to a robot: read the environment, plan, dispatch tools, watch what happens, replan.

A recipe with a Cortex stops being a programmed pipeline and becomes something you talk to.

See also

For the introductory walkthrough, start with Cortex: The Agentic Harness. For Cortex paired with spatio-temporal memory, see Memory and Cortex, and for the full showcase with navigation on top, Cortex Driving the Full Stack.


What Cortex replaces#

A recipe without Cortex earns each behaviour by wiring it: a vision component publishes detections, an event matches a class, an LLM step parses what the user said into a typed goal, and every link is yours to write and keep working. A recipe with Cortex has the same components and none of the wiring:

Without Cortex

With Cortex

One event and action pair per behaviour, wired in the recipe.

No behavioural wiring. Cortex plans the behaviour at run time from the goal it is given.

Each capability needs a handler that knows when to trigger it.

Each capability is an action on its component, and Cortex finds them all when it activates.

User input goes through a bespoke LLM step into a typed goal.

User input is a sentence sent to Cortex’s action server.

Recovery is wired per component.

A confirmation before each step handles the step, and replanning handles the plan.

You write the orchestration.

You write the components. Cortex does the orchestration.

A capability the recipe lacks is code you write first.

When allowed, the planner writes the action or condition a task needs, as it needs it.


How it works#

Every task runs through the same loop: plan, then execute with a check before each step, then replan if the plan did not get to the end.

Planning#

The planner works with two sets of tools. The planning tools are for finding things out and change nothing on the robot: inspect_component, any component action marked for the planning phase, list_events when events are enabled, and the four function-writing tools when the planner is allowed to write its own. The execution tools are the ones that make something happen: component actions, goals to action servers, service requests, routines, plugin actions, custom actions, and Cortex’s own update_parameter and wait.

On each round the model does one of three things. It can call planning tools to find out what it needs, in which case the results are appended to the conversation and planning continues. It can call execution tools, which commits the plan as an ordered list of steps and ends the planning phase. Or it can answer in text alone, which is published on output and ends the task. The planner gets up to max_planning_steps rounds of research before it has to commit, and a plan longer than max_execution_steps is cut at that length.

All the rounds of a task, including any replanning, happen in one conversation with the model. Like any other model component, Cortex keeps the conversation within the model’s context window. By default every task starts with a new conversation. If session_history is set, the planner also remembers that many earlier tasks. For each one it keeps the task, the calls it made, what they returned and how the task ended, so a follow-up like “now set the LED to the opposite colour” can be understood. A task that consists of just the reset phrase, “chat reset” by default, clears this memory.

Execution#

The steps run in order. Before each one, Cortex makes a short confirmation call in which the model decides what to do with the step by calling exactly one tool:

The model calls

Effect

execute_step

Run the step as planned.

the step’s own tool

Run the step with its arguments filled in, for instance a placeholder like <output from step 1> bound to what step 1 returned. A step whose arguments hold a placeholder can only be run this way.

skip_step

Leave this step out and go on.

abort_plan

Stop the plan, and the task ends as aborted.

continue_executing

Hold the step while an action started earlier is still running.

If the confirmation call fails, or the model answers without calling a tool, the step is not run. It is recorded as failed, with the consequences described below.

continue_executing is what allows long-running tasks. When a step has sent a goal to an action server without waiting for it, Cortex keeps reporting the goal’s status and latest feedback to the model at each confirmation, and the model can keep holding the next step until the goal succeeds.

When a step fails, the rest of the plan is not attempted. The remaining steps are recorded as not run, and the plan goes back to the planner together with the failure, so that it can plan around it.

Consecutive steps that need no such decisions are not run one at a time. When two or more component actions, plugin actions, awaited goals or waits follow each other with all their arguments known, they are compiled into a single routine hosted by the Monitor and run as a unit, and each step’s message is reported back as its result. A step that depends on an earlier result, a service call or a routine tool breaks the run and goes through confirmation as before. compile_routines=False turns this off, and step_timeout limits how long each compiled step may take.

Replanning#

If the plan did not reach its end, because a step failed or because a goal was still running when the steps ran out, Cortex plans again from where it stopped, with everything that happened so far in the conversation. A task like “patrol until you see a person” is carried out as a sequence of such rounds.


What it can call#

Cortex does not search the recipe itself. The launcher builds a registry of everything in the recipe that can be asked to do something by name, from every component in every process, and hands it to Cortex, which turns the entries into tools when it activates. You register nothing.

Source

Tool

A component action or fallback with a description

<component>-<method>, for example vision-take_picture or tts-say. The description is what the planner reads, so a method without one is not offered.

A component’s action server

send_goal_to_<component>_<server>, with the goal’s fields as parameters and a wait_to_finish flag, true by default. Both the main server of a component run as an action server and any it reports besides.

A component’s service

send_request_to_<component>_<service>, the same way.

A plugin’s actions

<plugin id>-<action>, for example lite3-stand_up, with the plugin’s own description.

A routine the Monitor hosts

routine-<name>, plus pause_routine, resume_routine and abort_routine.

Cortex itself

inspect_component for planning, and update_parameter and wait for execution.

A function the planner wrote

scratch-<name>, with the parameters of its signature, once enable_scratch_functions is on. See Functions the planner writes.

Lifecycle methods such as start, stop and restart are left out, since the Monitor manages those, and so are Cortex’s own actions.

Which phase a component action belongs to is set in its decorator. The default is execution; phase=ActionPhase.PLANNING makes it a research tool, and ActionPhase.BOTH offers it in both phases, which suits a quick read the planner may want both while researching and as a step, such as the body_status action of Memory:

from agents.components import Component
from agents.ros import ActionPhase, ActionReturnType, component_action

class MyComponent(Component):
    @component_action(description={...}, phase=ActionPhase.BOTH)
    def body_status(self) -> ActionReturnType: ...

The ask action of a DecisionComponent is one of these, offered in both phases as <component>-ask. It gives the planner a quick, typed check on what the robot sees or hears, or on a state the planner passes in, answered with a probability in a single forward pass rather than reasoned about in text.

A component’s action server takes one goal at a time. When Cortex sends a goal to a server that is still running one of its own, it cancels that goal, waits for the server to return, and sends the new one. A goal that some other client started is not touched: the planner is told the server is busy and shown the component’s cancel_main_goal tool, so stopping it is its decision.

Capabilities that do not belong to any component, such as a light to toggle, a database to query or an external API to call, are passed in as custom actions, each with a description:

from agents.ros import Action

cortex = Cortex(
    actions=[
        Action(method=toggle_led, description="Toggle the robot's LED on or off."),
        Action(method=query_inventory, description="Look up the current item inventory."),
    ],
    ...,
)

When a robot plugin is attached, its actions arrive through the same registry, and the planner is told what the robot is and who makes it, along with the sensor plugins attached to the recipe. Robot Plugins covers what a plugin brings.


Routines as skills#

A routine hosted by the Monitor is a skill the planner can use, a single tool that runs a whole procedure with its own success tests and retries. A routine reaches the Monitor when an event triggers it, when it is passed to enable_ui, or when it is given to Cortex directly, which needs neither of the other two:

cortex = Cortex(routines=[pick_object, patrol], ...)

A routine given to Cortex needs a description, since that is what the planner reads. Starting one returns at once; Cortex then follows its progress and reports its status, active step and last message to the planner until it completes, fails or is aborted. Routines a task started are aborted when the task ends, as its running goals are cancelled.


Standing instructions#

An instruction like “whenever the battery is low, go to the dock” is not a step in a plan but an event, and Cortex can install one. The tools for this are off by default, since they are the most involved ones Cortex offers; CortexConfig(enable_events=True) turns them on. The planner then has add_event, remove_event and list_events. To add an event it gives an id, one or more conditions on the fields of a topic that some component reads or writes, whether all of them or any one must hold, the tool calls to run, and whether the event fires once or every time. In place of topic conditions, an event can name a ready-made condition, either one a plugin offers, such as a low battery with its threshold, or one the planner wrote itself, as described in the next section. A topic or field that does not exist is refused before anything is installed. Once installed, an event outlives the task that created it.


Functions the planner writes#

Sometimes a task needs something the recipe does not have, such as a way to send an email or a reading that no component publishes. With CortexConfig(enable_scratch_functions=True), the planner is allowed to write the missing piece itself as a Python function and use it straight away. The tools for this are write_function, list_functions, read_function and remove_function. A written function is one of two kinds:

Kind

What the planner writes

What it becomes

action

def <name>(<typed parameters>) -> tuple[bool, str] with a docstring. It returns (True, message) or (False, why) and never raises.

The execution tool scratch-<name>, which a standing event can run as well.

condition

def <name>() -> bool with a docstring. It is quick, never blocks, and returns False rather than raising when it cannot tell.

A condition that add_event polls at a check_rate, named scratch-<name>.

Every function is checked when it is written. If it does not parse, does not keep the signature of its kind, has no docstring, or uses a name it did not import, it is refused and the planner is told why. A function may import the standard library, read the process environment through os.environ, and call the recipe’s existing actions through run_action("<tool name>", **arguments), which returns (success, message) like any action. It cannot send a goal to an action server; that remains a step of the plan. Writing a name again replaces the function, but any event that was installed with the earlier version keeps using it until the event is removed and added again. A condition that raises, returns something other than a bool, or takes longer than its polling period counts as not met, and the problem is reported once in the log.

The planner knows nothing about the environment its functions will run in except what scratch_notes tells it. This is a note in plain words in the config that says which variables hold credentials, what the machine can reach, and what is installed; without it the planner can only guess. Two other settings matter. A written function’s source has to fit in a single reply, so max_new_tokens needs a generous budget, 2000 or more. And if the planner is a thinking model, turn its thinking off with OllamaModel(think=False), because thinking spends the same budget before the answer begins.

Warning

A written function runs in the launcher process, with that process’s privileges, regardless of where the other components run, and it can do anything Python can do. Turn this on only with a planning model and on a deployment that you trust to that degree.

Cortex Writes Its Own Tools walks through it with two standing instructions.


Public API#

from agents.components import Cortex
from agents.config import CortexConfig
from agents.ros import Action, Topic

cortex_output = Topic(name="cortex_output", msg_type="StreamingString")

cortex = Cortex(
    actions=[Action(method=toggle_led, description="...")],
    routines=[patrol],
    output=cortex_output,
    model_client=planner_client,
    db_client=chroma_client,                          # optional: enables RAG context
    config=CortexConfig(
        max_planning_steps=5,
        max_execution_steps=15,
        enable_rag=True,
        collection_name="robot_manual",
    ),
    component_name="cortex",
)

Argument

Purpose

actions

Custom actions to offer as execution tools.

routines

Routines to host and offer as skills.

output

The topic Cortex publishes to when a goal can be answered in text alone. Wire it into TextToSpeech to give the robot a voice, or into the web interface to show replies.

model_client

The client of the model used for planning and confirmation. Optional with enable_local_model=True.

db_client

A vector database client. When set, Cortex queries it before each planning call and puts the result in front of the planner.

config

A CortexConfig, which extends LLMConfig.

CortexConfig field

Default

Effect

max_planning_steps

10

Rounds of research before the planner must commit.

max_execution_steps

10

The longest plan that is run.

session_history

0

How many earlier tasks the planner remembers.

confirmation_temperature

0.3

Sampling temperature of the confirmation call.

confirmation_max_tokens

500

Length budget of the confirmation call.

monitoring_interval

2.0 s

How often running goals and routines are reported to the planner.

compile_routines

true

Run consecutive compilable steps as one routine.

step_timeout

60 s

Time allowed for a component or plugin action inside a compiled run.

enable_events

false

Offer the standing-instruction tools.

enable_scratch_functions

false

Let the planner write its own actions and event conditions.

scratch_notes

empty

What the planner is told about the environment its functions run in.

The fields of LLMConfig apply too, among them enable_local_model, enable_rag, collection_name, n_results, temperature and max_new_tokens, whose default for Cortex is 1000. Two of them cannot be changed: chat_history is always on, because planning is a conversation, and stream is always off. history_budget works as in any other model component. With Ollama or a local model it is worked out from the model’s context window.

Cortex always runs as an action server, so run_type is not yours to set. Its action type is VisionLanguageAction and the goal carries the task as a string.


Cortex is also the Monitor#

When a recipe contains a Cortex, the launcher installs it in place of the default Monitor. It hosts the recipe’s events, actions and routines, holds the lifecycle clients of every component, and serves the runtime API, on top of being the agent. That is why it needs no list of components to work with: the launcher gives it the whole recipe.


Memory-aware planning#

When a Memory component is in the recipe, Cortex’s planning prompt is extended on activation, without any wiring:

  • Memory’s retrieval tools, semantic_search, locate, recall and the rest, and its body-status tool are listed, so the planner knows the difference between what the robot perceived and what it felt.

  • Memory’s inspect_component output is computed ahead and put in the prompt, so the planner knows the layer names without spending a planning step on them.

  • Every task is first classified as a perception query, a body query or an action task, each with its own protocol. A perception query opens no episode; an action task wraps itself in start_episode and end_episode and checks the body status first.

  • The body-status check is mandatory for action tasks, so a Cortex with an interoception layer, battery or fault flags, can decline a mission on the readings rather than discover the problem half way.

Memory and Cortex shows the pattern.


Observability#

Cortex publishes feedback on its action server as it works: each step with its tool name, whether it was executed, skipped, failed or aborted or is waiting, the status and latest feedback of goals in flight with stall warnings, the progress of routines it started, and the results of a compiled run. The recipe’s web interface shows these lines in the main log next to the components’ own, so an operator sees the agent’s reasoning and the Kompass controller’s path-tracking feedback side by side.


RAG context#

With a db_client, Cortex queries a vector database with the user’s task before each planning call and prepends what it finds:

from agents.clients import ChromaClient
from agents.vectordbs import ChromaDB

cortex = Cortex(
    output=cortex_output,
    model_client=planner_client,
    db_client=ChromaClient(db=ChromaDB(), host="localhost", port=8000),
    config=CortexConfig(
        enable_rag=True,
        collection_name="building_layout",
        n_results=5,
        add_metadata=True,
    ),
    component_name="cortex",
)

# Populate the database ahead of time
cortex.add_documents(
    ids=["floor1", "floor2"],
    metadatas=[{"floor": 1}, {"floor": 2}],
    documents=[
        "Floor 1 contains the kitchen, dining room, and main entrance.",
        "Floor 2 contains the bedrooms and the office.",
    ],
)

This is for facts the planner should not have to learn from the running recipe: robot manuals, building layouts, earlier conversations. What the robot learns as it runs belongs in Memory.


Recipes#

  • Cortex: The Agentic Harness, the introductory tutorial. Vision, a VLM, speech and a custom action, addressed in plain English with no orchestration code.

  • Cortex Driving the Full Stack, the showcase. Cortex orchestrates a Kompass navigation stack, Vision, a VLM, Memory and speech for compound goals.

  • Memory and Cortex, spatio-temporal memory wired into the planner, with perception and interoception layers, episodes and persistence across sessions.