realtime-chat.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import { useDebouncedCallback } from "use-debounce";
  2. import VoiceIcon from "@/app/icons/voice.svg";
  3. import VoiceOffIcon from "@/app/icons/voice-off.svg";
  4. import PowerIcon from "@/app/icons/power.svg";
  5. import styles from "./realtime-chat.module.scss";
  6. import clsx from "clsx";
  7. import { useState, useRef, useEffect } from "react";
  8. import {
  9. useAccessStore,
  10. useChatStore,
  11. ChatMessage,
  12. createMessage,
  13. } from "@/app/store";
  14. import { IconButton } from "@/app/components/button";
  15. import {
  16. Modality,
  17. RTClient,
  18. RTInputAudioItem,
  19. RTResponse,
  20. TurnDetection,
  21. Voice,
  22. } from "rt-client";
  23. import { AudioHandler } from "@/app/lib/audio";
  24. import { uploadImage } from "@/app/utils/chat";
  25. interface RealtimeChatProps {
  26. onClose?: () => void;
  27. onStartVoice?: () => void;
  28. onPausedVoice?: () => void;
  29. }
  30. export function RealtimeChat({
  31. onClose,
  32. onStartVoice,
  33. onPausedVoice,
  34. }: RealtimeChatProps) {
  35. const currentItemId = useRef<string>("");
  36. const currentBotMessage = useRef<ChatMessage | null>();
  37. const currentUserMessage = useRef<ChatMessage | null>();
  38. const accessStore = useAccessStore.getState();
  39. const chatStore = useChatStore();
  40. const session = chatStore.currentSession();
  41. const [status, setStatus] = useState("");
  42. const [isRecording, setIsRecording] = useState(false);
  43. const [isConnected, setIsConnected] = useState(false);
  44. const [isConnecting, setIsConnecting] = useState(false);
  45. const [modality, setModality] = useState("audio");
  46. const [isAzure, setIsAzure] = useState(false);
  47. const [endpoint, setEndpoint] = useState("");
  48. const [deployment, setDeployment] = useState("");
  49. const [useVAD, setUseVAD] = useState(true);
  50. const [voice, setVoice] = useState<Voice>("alloy");
  51. const [temperature, setTemperature] = useState(0.9);
  52. const clientRef = useRef<RTClient | null>(null);
  53. const audioHandlerRef = useRef<AudioHandler | null>(null);
  54. const apiKey = accessStore.openaiApiKey;
  55. const handleConnect = async () => {
  56. if (isConnecting) return;
  57. if (!isConnected) {
  58. try {
  59. setIsConnecting(true);
  60. clientRef.current = isAzure
  61. ? new RTClient(new URL(endpoint), { key: apiKey }, { deployment })
  62. : new RTClient(
  63. { key: apiKey },
  64. { model: "gpt-4o-realtime-preview-2024-10-01" },
  65. );
  66. const modalities: Modality[] =
  67. modality === "audio" ? ["text", "audio"] : ["text"];
  68. const turnDetection: TurnDetection = useVAD
  69. ? { type: "server_vad" }
  70. : null;
  71. clientRef.current.configure({
  72. instructions: "",
  73. voice,
  74. input_audio_transcription: { model: "whisper-1" },
  75. turn_detection: turnDetection,
  76. tools: [],
  77. temperature,
  78. modalities,
  79. });
  80. startResponseListener();
  81. setIsConnected(true);
  82. try {
  83. const recentMessages = chatStore.getMessagesWithMemory();
  84. for (const message of recentMessages) {
  85. const { role, content } = message;
  86. if (typeof content === "string") {
  87. await clientRef.current.sendItem({
  88. type: "message",
  89. role: role as any,
  90. content: [
  91. {
  92. type: (role === "assistant" ? "text" : "input_text") as any,
  93. text: content as string,
  94. },
  95. ],
  96. });
  97. }
  98. }
  99. } catch (error) {
  100. console.error("Set message failed:", error);
  101. }
  102. } catch (error) {
  103. console.error("Connection failed:", error);
  104. setStatus("Connection failed");
  105. } finally {
  106. setIsConnecting(false);
  107. }
  108. } else {
  109. await disconnect();
  110. }
  111. };
  112. const disconnect = async () => {
  113. if (clientRef.current) {
  114. try {
  115. await clientRef.current.close();
  116. clientRef.current = null;
  117. setIsConnected(false);
  118. } catch (error) {
  119. console.error("Disconnect failed:", error);
  120. }
  121. }
  122. };
  123. const startResponseListener = async () => {
  124. if (!clientRef.current) return;
  125. try {
  126. for await (const serverEvent of clientRef.current.events()) {
  127. if (serverEvent.type === "response") {
  128. await handleResponse(serverEvent);
  129. } else if (serverEvent.type === "input_audio") {
  130. await handleInputAudio(serverEvent);
  131. }
  132. }
  133. } catch (error) {
  134. if (clientRef.current) {
  135. console.error("Response iteration error:", error);
  136. }
  137. }
  138. };
  139. const handleResponse = async (response: RTResponse) => {
  140. for await (const item of response) {
  141. if (item.type === "message" && item.role === "assistant") {
  142. const botMessage = createMessage({
  143. role: item.role,
  144. content: "",
  145. });
  146. // add bot message first
  147. chatStore.updateTargetSession(session, (session) => {
  148. session.messages = session.messages.concat([botMessage]);
  149. });
  150. for await (const content of item) {
  151. if (content.type === "text") {
  152. for await (const text of content.textChunks()) {
  153. botMessage.content += text;
  154. }
  155. } else if (content.type === "audio") {
  156. const textTask = async () => {
  157. for await (const text of content.transcriptChunks()) {
  158. botMessage.content += text;
  159. }
  160. };
  161. const audioTask = async () => {
  162. audioHandlerRef.current?.startStreamingPlayback();
  163. for await (const audio of content.audioChunks()) {
  164. audioHandlerRef.current?.playChunk(audio);
  165. }
  166. };
  167. await Promise.all([textTask(), audioTask()]);
  168. }
  169. // update message.content
  170. chatStore.updateTargetSession(session, (session) => {
  171. session.messages = session.messages.concat();
  172. });
  173. }
  174. // upload audio get audio_url
  175. const blob = audioHandlerRef.current?.savePlayFile();
  176. uploadImage(blob!).then((audio_url) => {
  177. botMessage.audio_url = audio_url;
  178. // botMessage.date = new Date().toLocaleString();
  179. // update text and audio_url
  180. chatStore.updateTargetSession(session, (session) => {
  181. session.messages = session.messages.concat();
  182. });
  183. });
  184. }
  185. }
  186. };
  187. const handleInputAudio = async (item: RTInputAudioItem) => {
  188. await item.waitForCompletion();
  189. if (item.transcription) {
  190. const userMessage = createMessage({
  191. role: "user",
  192. content: item.transcription,
  193. });
  194. chatStore.updateTargetSession(session, (session) => {
  195. session.messages = session.messages.concat([userMessage]);
  196. });
  197. // save input audio_url, and update session
  198. const { audioStartMillis, audioEndMillis } = item;
  199. // upload audio get audio_url
  200. const blob = audioHandlerRef.current?.saveRecordFile(
  201. audioStartMillis,
  202. audioEndMillis,
  203. );
  204. uploadImage(blob!).then((audio_url) => {
  205. userMessage.audio_url = audio_url;
  206. chatStore.updateTargetSession(session, (session) => {
  207. session.messages = session.messages.concat();
  208. });
  209. });
  210. }
  211. // stop streaming play after get input audio.
  212. audioHandlerRef.current?.stopStreamingPlayback();
  213. };
  214. const toggleRecording = async () => {
  215. if (!isRecording && clientRef.current) {
  216. try {
  217. if (!audioHandlerRef.current) {
  218. audioHandlerRef.current = new AudioHandler();
  219. await audioHandlerRef.current.initialize();
  220. }
  221. await audioHandlerRef.current.startRecording(async (chunk) => {
  222. await clientRef.current?.sendAudio(chunk);
  223. });
  224. setIsRecording(true);
  225. } catch (error) {
  226. console.error("Failed to start recording:", error);
  227. }
  228. } else if (audioHandlerRef.current) {
  229. try {
  230. audioHandlerRef.current.stopRecording();
  231. if (!useVAD) {
  232. const inputAudio = await clientRef.current?.commitAudio();
  233. await handleInputAudio(inputAudio!);
  234. await clientRef.current?.generateResponse();
  235. }
  236. setIsRecording(false);
  237. } catch (error) {
  238. console.error("Failed to stop recording:", error);
  239. }
  240. }
  241. };
  242. useEffect(
  243. useDebouncedCallback(() => {
  244. const initAudioHandler = async () => {
  245. const handler = new AudioHandler();
  246. await handler.initialize();
  247. audioHandlerRef.current = handler;
  248. await handleConnect();
  249. await toggleRecording();
  250. };
  251. initAudioHandler().catch((error) => {
  252. setStatus(error);
  253. console.error(error);
  254. });
  255. return () => {
  256. if (isRecording) {
  257. toggleRecording();
  258. }
  259. audioHandlerRef.current?.close().catch(console.error);
  260. disconnect();
  261. };
  262. }),
  263. [],
  264. );
  265. // update session params
  266. useEffect(() => {
  267. clientRef.current?.configure({ voice });
  268. }, [voice]);
  269. useEffect(() => {
  270. clientRef.current?.configure({ temperature });
  271. }, [temperature]);
  272. const handleClose = async () => {
  273. onClose?.();
  274. if (isRecording) {
  275. await toggleRecording();
  276. }
  277. disconnect().catch(console.error);
  278. };
  279. return (
  280. <div className={styles["realtime-chat"]}>
  281. <div
  282. className={clsx(styles["circle-mic"], {
  283. [styles["pulse"]]: true,
  284. })}
  285. >
  286. <div className={styles["icon-center"]}></div>
  287. </div>
  288. <div className={styles["bottom-icons"]}>
  289. <div>
  290. <IconButton
  291. icon={isRecording ? <VoiceOffIcon /> : <VoiceIcon />}
  292. onClick={toggleRecording}
  293. disabled={!isConnected}
  294. type={isRecording ? "danger" : isConnected ? "primary" : null}
  295. />
  296. </div>
  297. <div className={styles["icon-center"]}>{status}</div>
  298. <div>
  299. <IconButton
  300. icon={<PowerIcon />}
  301. onClick={handleClose}
  302. type={isConnecting || isConnected ? "danger" : "primary"}
  303. />
  304. </div>
  305. </div>
  306. </div>
  307. );
  308. }