Skip to content
ImagineWorld

Interfacing Large Language Models with ROS 2

node_idnode-book_mastering-ros-2-for-robotics-programming_chapter-14-interfacing-large-language-models-with-ros-2
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleInterfacing Large Language Models with ROS 2
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 14 — Interfacing Large Language Models with ROS 2

Section titled “Chapter 14 — Interfacing Large Language Models with ROS 2”

This chapter will explore the possibilities of using GenAI in robotics by interfacing different large language models (LLMs) into ROS 2 by building AI agents. LLMs are a subset of GenAI mainly focused on generating text. So why does interfacing LLMs and AI agents with ROS 2 robots matter? Using LLMs and agents, robots can understand user input and generate an intelligent response. Users can use text, images, and voice as input, making the robot capable of answering questions intelligently. Other than interaction, LLM-based AI agents can control a robot by generating corresponding actions for the robot based on user input.

In this chapter, we’re going to cover the following main topics:

  • LLMs for robotics
  • Integrating ROS 2 robots with LLM agents
  • Creating ROS 2 AI agents
  • Popular ROS 2 AI agent projects

To follow along in this chapter, you should install Ubuntu 24.04 LTS with ROS 2 Jazzy desktop. It can be in a VM, Docker, WSL 2, or a real machine. Your PC should have a decent NVIDIA RTX GPU with > 8 GB of VRAM. The reference materials for this chapter can be found in the Chapter14 folder of the following GitHub repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter14.

LLMs are large, deep-learning models trained on vast amounts of data. Their main component is the transformer model neural network [1].

A transformer model is a neural network that can learn the context and meaning of a sentence by tracking the relationship in sequential data, such as words, using a mathematical technique called attention. In simple words, transformers can learn and generate human-like text by analyzing patterns from large text data.

Google introduced attention in 2017 as a research paper, Attention is All You Need [2], and it is now the foundation model for all the famous LLMs like ChatGPT from OpenAI, Llama from Facebook, and Gemini from Google. These LLMs are great performers in understanding natural language, reasoning, and decision-making. Along with LLMs, there are:

  • Vision language models (VLMs), which combine an LLM with a vision encoder, enabling the LLM to understand images and videos that can be used for robot perception.
  • Audio language models (ALMs), which are designed to process and generate spoken language. They combine an LLM with speech processing techniques, enabling capabilities like speech-to-text (STT), text-to-speech (TTS), and spoken language understanding (SLU).

In robotics, LLMs can be used as an interface between robots and humans, allowing human-like communication with robots, adaptive learning, autonomous decision-making, and intelligent control of robots.

Here are some important LLM-based use cases that can be applied in robotics:

  • Natural language-based robot control: We can use LLMs to send robot commands. Users can communicate with the robot using plain language instead of programming or GUIs. For example, the user talks to the cleaning robot to clean the room, and the robot performs the task.
  • Autonomous navigation and manipulation: LLMs can interpret the high-level instructions for navigation goals and pick and place instructions for the robot. For example, a warehouse robot receives a command like Fetch a box from shelf five and deliver it to the exit, which can determine the optimal path for the robot to reach the goal. For the manipulation task example, the user can send instructions in natural language, such as Pick the red box and place it near the green box. The LLMs can generate high-level instructions for the robotic arm to perform pick-and-place operations.
  • Robot perception and reasoning: LLMs with vision can understand the robot environment and clearly describe the objects in the scene. For example, if a user asks the model what the coordinates of a red box are, the model can return them if the box is present in the scene.
  • Error diagnosis and self-repair guidance: The robot’s error logs can be fed to LLMs, which can suggest auto fixes.
  • Simulation and training assistance: LLMs can help generate training scenarios in robot simulators like Gazebo and Isaac Sim, creating a dynamic environment for robot simulation.

You can find more information about LLM robotics-related research in [3] and [4].

In the next section, we will see how to integrate LLMs directly with ROS 2 by building AI agents.

Integration of ROS 2 robots with LLM agents

Section titled “Integration of ROS 2 robots with LLM agents”

The basic idea of an AI agent is to use an LLM as a reasoning engine to determine the appropriate sequence and order of pre-coded actions to take.

By combining an LLM-based agent with ROS 2, we can create multiple robotic applications. For example, it can be used in service robots to interact with the robot and perform meaningful robot actions based on user input. We can also use LLM agents for autonomous navigation and manipulation.

Different software frameworks are available to create an LLM-based agent. We can create an AI agent from scratch, but the development will be much quicker by using a framework. Here are a few popular AI agent frameworks:

  • LangChain [5]: This is an open-source framework for creating LLM-based AI agents. Developers can create context-aware, reasoning-capable, and tool-integrated AI applications. LangChain has features such as chains, which are sequences of LLM calls or tools designed for multi-step processing. It integrates multiple LLMs from OpenAI, Hugging Face, etc. The tools in LangChain are the external services or functions that an AI agent can use to extend capabilities beyond text generation. For example, developers can use external APIs such as ROS 2 inside the agents to communicate with ROS 2-compatible robots. Developers can create custom tools that will trigger after the user’s reasoning for the prompt. Using LangChain, we can quickly prototype chatbots interacting with external frameworks such as ROS 2 and Gazebo. LangChain mainly supports Python-based APIs for creating agents. We will discuss LangChain-based ROS 2 agents in the next section.
  • AutoGen [6]: This is an open-source framework from Microsoft for building multi-agent AI systems that can collaborate and solve complex problems. It can also automate workflows. It helps AI agents communicate with each other and external tools, making it useful for task automation, research applications, and decision-making.

Multiple AI agent frameworks are available besides LangChain and AutoGen. Here is a curated list of the latest agent frameworks and agents: [7].

Choosing the proper framework for creating an AI agent for the robot can sometimes be difficult. We can use both frameworks with ROS 2 in different scenarios. LangChain can be better suited for knowledge retrieval and AI reasoning with ROS 2, whereas AutoGen may be suitable for creating autonomous AI agents to collaborate on robotic tasks. Most of the popular frameworks use Python as the programming language.

The following section shows the block diagram of an AI agent working with a ROS 2 system.

Figure 14.1 shows a high-level architecture diagram of a ROS 2 AI agent that integrates LLMs and VLMs using LangChain or a similar framework to interact with the simulation or real robot working in ROS 2.

Here are the core components of an AI agent:

  • Human-robot interface: This allows the user to interact with the agent. It can be done using voice or text, and we may have to use some speech recognition.
  • The ROS AI agent application: This central unit is responsible for processing user input using LangChain APIs and communicating with LLMS. It processes user input and triggers appropriate tools based on it. It also receives feedback from the ROS 2 robot through topics, services, parameters, and actions.
  • LangChain/AutoGen: The agents use APIs from an agent framework such as LangChain and AutoGen to integrate and orchestrate LLMs and multi-model VLMs.
  • Cloud/local models: LLMs/VLMs can be hosted in the cloud or can be loaded locally. LLMs such as GPT mostly run in the cloud, and open-source models such as Llama can be run in the cloud and locally. The computer should have a good specification if we want to load LLMs/VLMs locally. The specification depends on what model we are loading. For example, for loading Meta LLaMA 2 13B/LLaMA 3 8B, we may need specs such as an 8+ core CPU (Ryzen 7/Intel i7 or better) 32 GB RAM, NVIDIA GPU with 12–24 GB VRAM (e.g., RTX 3080, 3090, 4080, 4090).

We need tools (such as Ollama [8], LM-Studio [9], etc.) to load the LLMs on a local computer. Cloud APIs will be faster than local deployment because they mainly send a request to the cloud, and the cloud infrastructure is good enough to handle and process the request. Cloud inference will be a better choice than local deployment of LLMs for ROS 2 robots running with a small compute footprint. Use the local model only if it can safely run on the compute modules.

  • Custom tools: These are custom functions that interface the AI agent to an external system such as ROS 2. They are like utilities or plugins that can enhance the AI agent’s functionalities. These tools/functions are triggered based on the prompt the user sends to the agent. The tools are Python functions/classes that have external APIs such as rclpy (ROS 2 Python client library).
  • ROS 2-based real robot/simulation: This represents the actual robot or simulated environment running on ROS 2. In the case of a real robot, the ROS 2 driver should be running, and proper topics, services, and actions should be exposed. The agent can communicate with the ROS 2 robot only if the robot driver is up and running. The same applies to simulation. The simulation using Gazebo/Isaac Sim should be properly running along with the agent, and all the ROS 2 topics, services, and actions should be exposed.
  • Feedback, logs, and diagnostics: This represents real-time feedback from the ROS 2 system. The feedback to the agent can be using ROS 2 topics, services, actions, and parameters. The feedback helps to debug, monitor, and improve performance.
  • Agent response: This is the final response that the agent shows to the user after triggering the necessary tools. The agent response will give the user an idea of the result operation.

In the next section, we can see how these AI agents work.

Here is how the AI agent works. The agent gets the input request from a human via voice/text. Agents use APIs from LangChain/AutoGen to reason with the input. The APIs load the LLMs when the agent is initialized.

Figure 14.1: Block diagram of AI agent with ROS 2

Figure 14.1: Block diagram of AI agent with ROS 2

Based on the reasoning from the LLM, it executes specific actions coded as tools. The tools have ROS 2 APIs, which can publish/subscribe data to a ROS 2-based robot. The feedback from the ROS 2 system is sent back to the AI agent for diagnostics and monitoring. The agent will show a final response after getting the feedback.

Understanding AI agent architecture and working with it helps developers create new agents. In the next section, we will dive into the development of ROS-based AI agents.

This section will explore a few ROS 2 AI agent projects from the basics to advanced levels and see how to set them up on a local PC.

In Chapter14/docker_llm, you can find the Dockerfile and scripts to build a new image for the ROS 2 AI agent application.

You can use the following command to build the image:

./build_image.sh ros2_llm master_ros2_ws robot

In this command, ros2_llm is the Docker image name, master_ros2_ws is the ROS 2 workspace name, and robot is the username of the Docker container.

After building the image, we can create the container using the following command:

./create_container.sh ros2_llm master_ros2_ws ros2_ai

In this command, we have to provide the image name first, which is ros2_llm, and the second argument is the ROS 2 workspace, which is master_ros2_ws. The third argument is the container name, which is ros2_ai. The container will mount master_ros2_ws from the host machine, so we can build those packages from this container itself.

If we want to attach a new terminal to the container, we can use the following script and command:

./start_container.sh ros2_ai
source /ros_entrypoint.sh

There are Docker Compose files for this chapter. Switch to the Chapter14 | docker_compose_llm folder and execute the following command to start building the Docker image and start the container:

  • Use the following command if you are using a non-NVIDIA graphics card on your PC:
    docker compose -f docker-compose-gui.yml build
    docker compose -f docker-compose-gui.yml up
  • If you do have an NVIDIA graphics card and the driver is properly installed, use the following command to start the container:
    docker compose -f docker-compose-nvidia.yml build
    docker compose -f docker-compose-nvidia.yml up

Once you run this command, the image will be built first, the container will start, and you will have to use another terminal to attach to the container. You don’t have to close this terminal; if you cancel the command by pressing Ctrl + C, it will stop the running container.

You can create a new terminal from the running container using the following command:

./start_container.sh ros2_ai

Now source the ROS 2 environment:

source /ros_entrypoint.sh

After starting the container, if you want to stop the container and remove the container, you can execute the command from a new host terminal. Make sure you are executing from inside the docker_compose_llm folder:

docker compose -f docker-compose-gui.yml down

or

docker compose -f docker-compose-nvidia.yml down

In the next section, we will see how to set up VS Code Dev Containers for developing and running AI-agents.

ROS 2 AI-agent development using VS Code Dev Containers

Section titled “ROS 2 AI-agent development using VS Code Dev Containers”

If you are interested in setting up a development container in VS Code, make sure you have created the ROS 2 workspace named master_ros2_ws and then open the Chapter14 folder using VS Code. This folder has a .devcontainer folder. This has the devcontainer.json file, which has the instructions to use the Docker Compose file we used in the above section for the container. When you open the folder, it will prompt you to install the Dev Containers extension and reopen it in the container. If you select this option, it will build the container, set the environment, mount the ROS 2 workspace as a volume, and connect the editor to it. We can also see the mounted volume, which is the master_ros2_ws folder in VS Code itself.

Let’s start building the basic AI agent working with ROS 2.

In this section, we will discuss how we can develop our own AI agent for our ROS 2 application. The architecture of the agent will be based on Figure 14.1. We use LangChain as the framework for creating AI agents here.

Here is the list of demo AI agents we are going to discuss in this section.

  • Basic ROS 2 agent: This AI agent performs simple tasks, such as printing the name of the ROS 2 distribution and ROS domain ID. The user can ask about these values in natural language, and it can reply with the values.
  • Basic ROS 2 agent with ROS 2 tools: This agent can trigger ROS 2 command-line tools using natural language and show their results. For example, the user can ask about ROS 2 topics, services, actions, etc.
  • Agent for turtlesim control: This agent can move the turtle in turtlesim and get its current position.
  • AI agent for Nav2: This agent works with Nav2 and TurtleBot 3 simulation. We can ask the robot to navigate to any position on the map and inquire about its current position.
  • AI agent for MoveIt2: This agent works with MoveIt2 and universal robot (UR) simulation, which moves the robot end effector based on the user prompt. It can also retrieve the current gripper position.

The Chapter14/ros2_basic_agent package includes the complete source code of the AI agents. This is a simple ROS 2 Python package that has AI agent scripts, launch files, and a config file for OpenAI.

You can find agent scripts at ros2_basic_agent/ros2_basic_agent/ and launch files at ros2_basic_agent/launch. We can copy this package to the ROS workspace, which is ~/master_ros2_ws/src.

Build the package inside the Docker container using the following command:

colcon build --packages-select ros2_basic_agent --symlink-install

After building this package, we can launch each agent with the necessary simulator, if any.

For this package, we use cloud-based LLMs, specifically ChatGPT APIs. Cloud-based APIs work with any kind of computer, and the requirements are a steady internet connection and an OpenAI API paid account. If you have a very good local GPU infrastructure, using Ollama and LM-Studio with open-source LLMs such as Llama is another option for the agent. This approach requires no internet connection; the agent can work fully offline.

If we use cloud APIs, we may need to create an API key to access them. The following section shows how to configure OpenAI API keys.

To connect to cloud-based LLMs, initialize the agent, and connect, we need to generate an API key from the OpenAI website. The ChatGPT account and API access account are different, and the payment is also different. Here is the link to create API keys: [10]. You can create a secret key and copy the key. This is required in our ROS 2 package. Also, make sure you have added 5 to 10 USD to test this package. Figure 14.2 shows the API key entry once it is successfully created.

Figure 14.2: OpenAI API web page

Figure 14.2: OpenAI API web page

Once you copy the keys, navigate to ros2_basic_agent/config/openai.env and put it in the OPENAI_API_KEY field. Once this is done, you must build the ros2_basic_agent package using the following command:

colcon build --packages-select ros2_basic_agent --symlink-install

Once we have updated the OpenAI API key, we are done with the API key configuration. Now we can discuss the detailed architecture of an ROS 2 AI agent node and how it works.

In this section, we will see how the AI agent works inside a ROS 2 node in detail. Figure 14.3 shows a detailed architecture diagram of the ROS 2 AI agent node based on LangChain. This ROS 2 Python node has ROS 2 APIs and LangChain APIs. The ROS 2 APIs subscribe to a string topic named /prompt. This string data will be the input to the agent. The agent uses LangChain APIs and connects to OpenAI for cloud LLMs.

Once the agent understands the context of input, it triggers available tools that are defined and finally comes up with the result.

Figure 14.3: Workflow of a basic ROS 2 LangChain AI agent

Figure 14.3: Workflow of a basic ROS 2 LangChain AI agent

Here is the code template of a ROS 2 AI agent node. All AI agent APIs are wrapped in a ROS 2 node class:

class ROS2AIAgent(Node):
def init(self):
# 1. Node initialization
# 2. Tool setup
# 3. Prompt configuration
# 4. LLM initialization
# 5. Agent creation
# 6. Subscriber setup
@tool
def tool_function(self) -> str:
# Tool implementation
pass
def prompt_callback(self, msg):
# Message processing
pass
def main():
# Main execution loop

Inside the ROS 2 Node class, we initialize the ROS 2 node, LangChain-based custom tools, prompt configuration, and OpenAI LLM. The prompt configuration is a description we provide to the AI agent to respond to input prompts. The description defines the agent’s behavior, response style, constraint, and output format. The better the description, the better the agent understands the context.

After initializing, the ROS2 node creates the agent and a ROS 2 subscriber named /prompt for receiving input from the user. After receiving the input, it invokes the agent with this input, which triggers the appropriate tools that we have defined. After executing the tools, it will show the result.

Let’s start running each agent and see its working.

Let’s start with the first ROS 2 AI agent we include in the ros2_basic_agent package. You can find the basic agent ROS 2 node at ros2_basic_agent/ros2_basic_agent/ ros2_ai_agent_basic.py and the launch file at ros2_basic_agent/launch/ start_ros2_basic_agent.py.

In this agent, the user can ask about the current ROS 2 distribution and ROS domain ID. Based on the queries, the agent can return those values.

Figure 14.4 shows the flow diagram of this agent. It has the same architecture that we have seen in Figure 14.3; the only difference you can see is it has two tools, which are get_ros_domain_id and get_distribution:

  • get_ros_distro(): Retrieves the current ROS distribution name
  • get_domain_id(): Retrieves the current ROS domain ID

Figure 14.4: Flow diagram of the ROS 2 Langchain AI agent

Figure 14.4: Flow diagram of the ROS 2 Langchain AI agent

It is better to work with the agent from a Docker container because all the dependencies are pre-installed. If you have already started the container, follow the commands below to start the basic AI agent:

In Terminal 1

Switch to the docker_llm folder inside Chapter14. Make sure, you have created the container before starting the launch file. If not, create a container first:

./create_container.sh ros2_llm master_ros2_ws ros2_ai

If the container is already created, use the following script to start the container or to attach a new terminal:

./start_container.sh ros2_ai

Once you have the container terminal, execute the following commands to start the launch file:

source /ros_entrypoint.sh
source ~/master_ros2_ws/install/setup.bash

Here is the launch file to start the agent:

ros2 launch ros2_basic_agent start_ros2_basic_agent.py

If the agent is running correctly, you might get a message like the following:

[ros2_ai_agent_basic-1] [INFO] [1742935925.955416324] [ros2_ai_agent_basic]: ROS2 AI Agent has been started

Note

If you are getting an error from the OpenAI API, make sure you have properly entered the API key and have sufficient credit in the OpenAI account.

Once the agent starts working, we can send a prompt to the agent. Take another new terminal from the container and execute the following command:

In Terminal 2

We can publish the prompt to the /prompt topic as a string. You only have to publish it once. Once it is published, you can check in the agent terminal and find the response:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'What ROS distribution am I using?'}"

Here is a typical output that you can see in Terminal 1:

[ros2_ai_agent_basic-1] > Entering new AgentExecutor chain...
[ros2_ai_agent_basic-1] [ros2_ai_agent_basic-1] Invoking: get_ros_distro with {} [ros2_ai_agent_basic-1]
[ros2_ai_agent_basic-1] [ros2_ai_agent_basic-1] Current ROS distribution: jazzy Current ROS distribution: jazzy
[ros2_ai_agent_basic-1] [ros2_ai_agent_basic-1] > Finished chain. [ros2_ai_agent_basic-1] [INFO] [1742937262.050775675] [ros2_ai_agent_basic]: Result: Current ROS distribution: jazzy

In the response, it is printed that the current distribution is jazzy.

After publishing the first prompt, you can try the following prompt to get the ROS_DOMAIN_ID value:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'What is my ROS domain ID?'}"

After publishing, you can find the ROS domain ID printed in the agent terminal.

Note

If we prompt a more complex task to this agent, the agent may not be able to deliver it because of the limited number of tools in the agent. To handle more complex prompts, we should add more tools to the agent.

In the next section, we will show the demonstration of the next agent, which has tools that can list ROS 2 topics, services, and actions.

In this section, we can see how to run the ROS 2 tools agent and briefly explain its custom tools.

You can find the agent ROS 2 node at ros2_basic_agent/ros2_basic_agent/ ros2_ai_agent_basic_tools.py and the launch file at ros2_basic_agent/launch/start_ros2_tools_agent.py.

Using the ros2 command-line tools, we can enquire about topics, services, actions, and parameters. This agent does the same thing, but instead of using commands, we can enquire using natural language.

It has the following custom tools:

  • list_topics(): Lists all available ROS 2 topics
  • list_nodes(): Lists all running ROS 2 nodes
  • list_services(): Lists all available ROS 2 services
  • list_actions(): Lists all available ROS 2 actions

The difference between the first basic agent and the ROS 2 tool agent is that the former has different prompt configs and different custom tools. The basic architecture of the ROS 2 AI agent remains the same.

Here is the launch file to start the agent:

ros2 launch ros2_basic_agent start_ros2_tools_agent.py

If the agent starts properly, it will show the following message in the terminal:

[ros2_ai_agent_basic_tools-1] [INFO] [1742974052.972036533] [ros2_ai_agent_basic_tools]: ROS2 AI Agent has been started

Now, we can send the prompt to the agent by publishing to the /prompt topic. The following prompt asks the agent to list the available ROS 2 topics:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'Show me all available topics'}"

Figure 14.5 shows the output of the agent once we publish the prompt:

Figure 14.5: Output of the ROS 2 tool agent

Figure 14.5: Output of the ROS 2 tool agent

We can send prompts for services and actions as we did for topics. The example prompt for that is given below.

Here is the prompt for showing the service list:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'List all available services'}"

Here is the prompt for showing the action list:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'List all available actions}"

Here is a more complex prompt, asking the agent to list the ROS 2 topics that have a string message type:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'Which of these topic messages contain a string field?'}"

After interacting with the agent, let’s switch to the next agent. The following agent is for interacting with turtlesim.

This AI agent can move the turtle in turtlesim. We can prompt it to move or rotate or ask for its current position.

Figure 14.6 shows the node graph of the agent with turtlesim.

Figure 14.6: Workflow of the ROS 2 agent with turtlesim

Figure 14.6: Workflow of the ROS 2 agent with turtlesim

The agent publishes the cmd_vel and subscribes to the turtle’s pose. Based on the prompt from the user, it can trigger the custom tools for publishing cmd_vel for movement and printing the current position.

You can find the agent ROS 2 node at ros2_basic_agent/ros2_basic_agent/ros2_ai_agent_turtlesim.py. It has the following custom tools:

  • move_forward(distance: float): Move the turtle a particular distance.
  • rotate(angle: float): Rotate the turtle by a particular angle.
  • get_pose(): It should return the current pose of the turtle.

You can find the launch file at ros2_basic_agent/launch/start_turtlesim_agent.py.

Here is the command to start the turtlesim agent with the turtlesim:

ros2 launch ros2_basic_agent start_turtlesim_agent.py

If the agent starts properly, you can see the turtlesim and the agent started logs from the terminal, as shown in Figure 14.7:

Figure 14.7: Output of the ROS 2 agent for turtlesim

Figure 14.7: Output of the ROS 2 agent for turtlesim

After starting the agent in Terminal 1, publish the prompt as shown in Figure 14.7. Here is an example prompt. We can try to move the turtle in the turtlesim:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'Move the robot 30 meters forward '}"

This prompt will move the turtle forward for 30 meters. The value provided to the agent is just a factor. If the value is higher, there is more movement to the turtle.

Figure 14.8 shows the output of the move forward prompt to the turtlesim agent.

Figure 14.8: Output of the move forward prompt

Figure 14.8: Output of the move forward prompt

Similar to move forward, here are example prompts we can try for this agent.

The following prompt can rotate the turtle at a specific angle. In this example, it can rotate 90 degrees:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'rotate 90 degree '}"

The following prompt can retrieve the current position of the turtle in the turtlesim:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'get current pose '}"

The next agent we will discuss can work with Nav2.

Using this agent, we can command the robot to move to a position on the map and retrieve its current position.

Figure 14.9 shows the block diagram of the Nav2 AI agent.

Figure 14.9: Block diagram of the Nav2 AI agent

Figure 14.9: Block diagram of the Nav2 AI agent

The agent is connected to Nav2 and sends the target position. Nav2 generates command velocity to reach that position and moves the robot in Gazebo.

You can find the agent ROS 2 node at ros2_basic_agent/ros2_basic_agent/ros2_ai_agent_turtlebo3_nav2.py and the launch file at ros2_basic_agent/launch/start_turtlebot3_nav2_agent.py. This agent has the following custom-defined tools:

  • move_to_goal(x: float, y: float): Navigates the robot to specified x and y coordinates
  • get_current_pose(): Retrieves the current position and orientation of the robot

These tools use Nav2 simple commander APIs to command Nav2 to set the target position.

Here is the launch file to start the turtlebot3 simulation: ros2 launch ros2_basic_agent start_turtlebot3_nav2_agent.py

This will launch the turtlebot3 simulation in the Gazebo simulator, Nav2, Slam Toolbox, and the Nav2 AI agent. By default, mapping and navigation are enabled. The user can send a prompt to move the robot to a specific distance in x and y, and the robot can navigate to that position.

Here is a sample prompt we can use to move the robot and get the current position:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'Move the robot to position x=1.5, y=0.5'}"

Once you have given the prompt, the agent will send the target position to Nav2, and the robot will plan a path and navigate to the provided location. The workings of the agent are shown in Figure 14.10.

Figure 14.10: Workflow of the Nav2 AI agent

Figure 14.10: Workflow of the Nav2 AI agent

The following prompt will trigger the agent to return the robot’s current position:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'What is the current position of the robot?'}"

Here is the prompt to retrieve the current position and move the robot 1 meter from the current position:

ros2 topic pub --once /prompt std_msgs/msg/String "{data: 'Get the current position and then move the robot 1 meters forward'}"

Note

If we prompt a more complex task to this agent, the agent may not be able to deliver it because of the limited number of tools in the agent. For example, if we prompt the agent to move the robot into a particular shape, the agent may fail. To handle more complex prompts, we should add more tools to the agent.

In the next section, we will see how the MoveIt2 agent works.

This agent can work with MoveIt2. Like the Nav2 agent, we can command it to set the robotic arm’s target position and retrieve its end effector position.

Figure 14.11 shows the block diagram of the MoveIt2 agent. It is like the Nav2 agent architecture, but the only difference is that Nav2 is replaced with MoveIt2.

Figure 14.11: Block diagram of the MoveIt2 AI agent

Figure 14.11: Block diagram of the MoveIt2 AI agent

You can find the agent ROS 2 node at ros2_basic_agent/ros2_basic_agent/ros2_ai_agent_ur_moveit2.py and the launch file at ros2_basic_agent/launch/ start_ur_moveit2_agent.py.

This agent has the following custom-defined tools:

  • move_to_pose(self, x: float, y: float, z: float): Sets the end effector position of the robotic arm
  • get_current_pose(self): Retrieves the current end effector position of the robotic arm

Here is the launch file to start with the universal robot simulation in Gazebo and the MoveIt2 agent: ros2 launch ros2_basic_agent start_ur_moveit2_agent.py.

After starting the launch file, we can interact with the agent using the following prompts.

The following prompt will move the robot end effector to a specific position:

ros2 topic pub --once /prompt std_msgs/msg/String "data: 'Move the end effector to position x=-0.392, y=0.358, z=0.623'"

Figure 14.12 shows the prompt’s output. Once the prompt is published, the AI agent communicates with MoveIt2 to generate a plan and execute it in the commanded position.

Figure 14.12: Workflow of the MoveIt2 AI agent

Figure 14.12: Workflow of the MoveIt2 AI agent

Here is the prompt to move the robot to the home position:

ros2 topic pub --once /prompt std_msgs/msg/String "data: 'Move the robot to home position'"

Here is the prompt to get the current position of the end effector:

ros2 topic pub --once /prompt std_msgs/msg/String "data: 'Get the current gripper pose'"

The following prompt can get the current end effector position, reduce the z value by 0.2, and send it to MoveIt:

ros2 topic pub -1 /prompt std_msgs/msg/String "{data: 'Get the current position of end effector and reduce z value by 0.2'}"

Note

If we prompt a more complex task to this agent, the agent may not be able to deliver it because of the limited number of tools. For example, if we prompt the agent to perform a zig-zag movement, the agent may fail. To handle more complex prompts, we should add more tools to the agent.

We have completed the discussion of the custom agents we have created. Now, let’s start discussing the existing free ROS 2 agent projects that are available.

In this section, we will briefly explore some existing ROS 2 AI agent projects.

ROSA [11] is an AI agent by NASA designed to interact with ROS 1 and ROS 2-based robot systems using natural language queries. It helps robot developers inspect, diagnose, understand, and control robots. It is based on the LangChain framework and has many custom tools.

Figure 14.13 shows the ROSA project banner.

Figure 14.13: ROSA project banner (source: https://github.com/nasa-jpl/rosa)

Figure 14.13: ROSA project banner (source: https://github.com/nasa-jpl/rosa)

Developers can create their own ROS 1 and 2-based agents using their APIs. Here are the instructions to configure ROSA with the OpenAI API key: [15].

RAI [12] is like ROSA, which was created using LangChain and ROS 2. It has more capabilities than ROSA. It has interfaced with LLMs and VLMs and is vision- and voice-enabled. It has interfaced with Nav2 and MoveIt2, which makes it ideal for controlling any kind of robot.

Figure 14.14 shows the block diagram of the RAI project, which is like the agent we have already created.

Figure 14.14: Block diagram of RAI

Figure 14.14: Block diagram of RAI

ROS-LLM [13] is like the above project, focusing on embodied intelligence applications. It is supported in ROS Noetic and ROS 2 Humble. It mainly uses GPT-4 for the LLM and provides communication to the robot using conversational engagement.

The ROS 2 NanoLLM from NVIDIA [14] is the interface of NanoLLM to ROS 2. The NanoLLM optimizes LLMs, VLMs, and Vision Language Action (VLA) models to run on the NVIDIA Jetson Orin. This project can be directly run on the robot computer without connecting to the cloud.

There are many more agents available as open source. In this section, we have discussed the popular AI agents currently available as open source.

This chapter explored the integration of LLMs with ROS 2, highlighting their potential to enhance robotics through natural language interaction, autonomous decision-making, and intelligent control. It introduced LLMs, VLMs, and ALMs, explaining their relevance to robotics. The chapter covered key applications, including natural language-based robot control, autonomous navigation, perception, task planning, and error diagnosis. It then detailed the integration of AI agents with ROS 2 using frameworks such as LangChain and AutoGen, providing an architecture for AI agents interacting with robots. Several ROS 2 AI agent projects were discussed, demonstrating turtlesim, Nav2, and MoveIt2 implementations. The chapter concluded with an overview of ROS 2 AI projects such as ROSA, RAI, ROS-LLM, and NVIDIA’s ROS2-NanoLLM.

The next chapter will discuss how we can apply deep reinforcement learning in ROS 2.