realtime-chat.tsx 9.6 KB

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