|
| 1 | +# Copyright (C) 2024 Robotec.AI |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import argparse |
| 16 | +import logging |
| 17 | +import signal |
| 18 | +import time |
| 19 | +from queue import Queue |
| 20 | +from threading import Event, Thread |
| 21 | +from typing import Dict, List |
| 22 | + |
| 23 | +import rclpy |
| 24 | +from langchain_core.callbacks import BaseCallbackHandler |
| 25 | +from langchain_core.messages import AIMessage, HumanMessage, SystemMessage |
| 26 | +from rai.agents.base import BaseAgent |
| 27 | +from rai.communication import BaseConnector |
| 28 | +from rai.communication.ros2.api import IROS2Message |
| 29 | +from rai.communication.ros2.connectors import ROS2HRIConnector, TopicConfig |
| 30 | +from rai.utils.model_initialization import get_llm_model |
| 31 | + |
| 32 | +from rai_interfaces.msg import HRIMessage as InterfacesHRIMessage |
| 33 | + |
| 34 | +# NOTE: the Agent code included here is temporary until a dedicated speech agent is created |
| 35 | +# it can still serve as a reference for writing your own RAI agents |
| 36 | + |
| 37 | + |
| 38 | +class LLMTextHandler(BaseCallbackHandler): |
| 39 | + def __init__(self, connector: ROS2HRIConnector): |
| 40 | + self.connector = connector |
| 41 | + self.token_buffer = "" |
| 42 | + |
| 43 | + def on_llm_new_token(self, token: str, **kwargs): |
| 44 | + self.token_buffer += token |
| 45 | + if len(self.token_buffer) > 100 or token in [".", "?", "!", ",", ";", ":"]: |
| 46 | + self.connector.send_all_targets(AIMessage(content=self.token_buffer)) |
| 47 | + self.token_buffer = "" |
| 48 | + |
| 49 | + def on_llm_end( |
| 50 | + self, |
| 51 | + response, |
| 52 | + *, |
| 53 | + run_id, |
| 54 | + parent_run_id=None, |
| 55 | + **kwargs, |
| 56 | + ): |
| 57 | + if self.token_buffer: |
| 58 | + self.connector.send_all_targets(AIMessage(content=self.token_buffer)) |
| 59 | + self.token_buffer = "" |
| 60 | + |
| 61 | + |
| 62 | +class S2SConversationalAgent(BaseAgent): |
| 63 | + def __init__(self, connectors: Dict[str, BaseConnector]): # type: ignore |
| 64 | + super().__init__(connectors=connectors) |
| 65 | + self.message_history: List[HumanMessage | AIMessage | SystemMessage] = [ |
| 66 | + SystemMessage( |
| 67 | + content="Pretend you are a robot. Answer as if you were a robot." |
| 68 | + ) |
| 69 | + ] |
| 70 | + self.speech_queue: Queue[InterfacesHRIMessage] = Queue() |
| 71 | + |
| 72 | + self.llm = get_llm_model(model_type="complex_model", streaming=True) |
| 73 | + self._setup_ros_connector() |
| 74 | + self.main_thread = None |
| 75 | + self.stop_thread = Event() |
| 76 | + |
| 77 | + def run(self): |
| 78 | + logging.info("Running S2SConversationalAgent") |
| 79 | + self.main_thread = Thread(target=self._main_loop) |
| 80 | + self.main_thread.start() |
| 81 | + |
| 82 | + def _main_loop(self): |
| 83 | + while not self.stop_thread.is_set(): |
| 84 | + time.sleep(0.01) |
| 85 | + speech = "" |
| 86 | + while not self.speech_queue.empty(): |
| 87 | + speech += "".join(self.speech_queue.get().text) |
| 88 | + logging.info(f"Received human speech {speech}!") |
| 89 | + if speech != "": |
| 90 | + self.message_history.append(HumanMessage(content=speech)) |
| 91 | + assert isinstance(self.connectors["ros2"], ROS2HRIConnector) |
| 92 | + # ai_answer = AIMessage(content="Yes, I am Jar Jar Binks") |
| 93 | + # self.connectors["ros2"].send_all_targets(ai_answer) |
| 94 | + ai_answer = self.llm.invoke( |
| 95 | + speech, |
| 96 | + config={"callbacks": [LLMTextHandler(self.connectors["ros2"])]}, |
| 97 | + ) |
| 98 | + self.message_history.append(ai_answer) # type: ignore |
| 99 | + |
| 100 | + def _on_from_human(self, msg: IROS2Message): |
| 101 | + assert isinstance(msg, InterfacesHRIMessage) |
| 102 | + logging.info("Received message from human: %s", msg.text) |
| 103 | + self.speech_queue.put(msg) |
| 104 | + |
| 105 | + def _setup_ros_connector(self): |
| 106 | + self.connectors["ros2"] = ROS2HRIConnector( |
| 107 | + sources=[ |
| 108 | + ( |
| 109 | + "/from_human", |
| 110 | + TopicConfig( |
| 111 | + "rai_interfaces/msg/HRIMessage", |
| 112 | + is_subscriber=True, |
| 113 | + source_author="human", |
| 114 | + subscriber_callback=self._on_from_human, |
| 115 | + ), |
| 116 | + ) |
| 117 | + ], |
| 118 | + targets=[ |
| 119 | + ( |
| 120 | + "/to_human", |
| 121 | + TopicConfig( |
| 122 | + "rai_interfaces/msg/HRIMessage", |
| 123 | + source_author="ai", |
| 124 | + is_subscriber=False, |
| 125 | + ), |
| 126 | + ) |
| 127 | + ], |
| 128 | + ) |
| 129 | + |
| 130 | + def stop(self): |
| 131 | + assert isinstance(self.connectors["ros2"], ROS2HRIConnector) |
| 132 | + self.connectors["ros2"].shutdown() |
| 133 | + self.stop_thread.set() |
| 134 | + if self.main_thread is not None: |
| 135 | + self.main_thread.join() |
| 136 | + |
| 137 | + |
| 138 | +def parse_arguments(): |
| 139 | + parser = argparse.ArgumentParser( |
| 140 | + description="Text To Speech Configuration", |
| 141 | + allow_abbrev=True, |
| 142 | + ) |
| 143 | + |
| 144 | + # Use parse_known_args to ignore unknown arguments |
| 145 | + args, unknown = parser.parse_known_args() |
| 146 | + |
| 147 | + if unknown: |
| 148 | + print(f"Ignoring unknown arguments: {unknown}") |
| 149 | + |
| 150 | + return args |
| 151 | + |
| 152 | + |
| 153 | +if __name__ == "__main__": |
| 154 | + args = parse_arguments() |
| 155 | + rclpy.init() |
| 156 | + agent = S2SConversationalAgent(connectors={}) |
| 157 | + agent.run() |
| 158 | + |
| 159 | + def cleanup(signum, frame): |
| 160 | + print("\nCustom handler: Caught SIGINT (Ctrl+C).") |
| 161 | + print("Performing cleanup") |
| 162 | + # Optionally exit the program |
| 163 | + agent.stop() |
| 164 | + rclpy.shutdown() |
| 165 | + exit(0) |
| 166 | + |
| 167 | + signal.signal(signal.SIGINT, cleanup) |
| 168 | + |
| 169 | + print("Runnin") |
| 170 | + while True: |
| 171 | + time.sleep(1) |
0 commit comments