realtime-chat.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. }
  98. } catch (error) {
  99. console.error("Connection failed:", error);
  100. setStatus("Connection failed");
  101. } finally {
  102. setIsConnecting(false);
  103. }
  104. } else {
  105. await disconnect();
  106. }
  107. };
  108. const disconnect = async () => {
  109. if (clientRef.current) {
  110. try {
  111. await clientRef.current.close();
  112. clientRef.current = null;
  113. setIsConnected(false);
  114. } catch (error) {
  115. console.error("Disconnect failed:", error);
  116. }
  117. }
  118. };
  119. const startResponseListener = async () => {
  120. if (!clientRef.current) return;
  121. try {
  122. for await (const serverEvent of clientRef.current.events()) {
  123. if (serverEvent.type === "response") {
  124. await handleResponse(serverEvent);
  125. } else if (serverEvent.type === "input_audio") {
  126. await handleInputAudio(serverEvent);
  127. }
  128. }
  129. } catch (error) {
  130. if (clientRef.current) {
  131. console.error("Response iteration error:", error);
  132. }
  133. }
  134. };
  135. const handleResponse = async (response: RTResponse) => {
  136. for await (const item of response) {
  137. if (item.type === "message" && item.role === "assistant") {
  138. const botMessage = createMessage({
  139. role: item.role,
  140. content: "",
  141. });
  142. // add bot message first
  143. chatStore.updateTargetSession(session, (session) => {
  144. session.messages = session.messages.concat([botMessage]);
  145. });
  146. for await (const content of item) {
  147. if (content.type === "text") {
  148. for await (const text of content.textChunks()) {
  149. botMessage.content += text;
  150. }
  151. } else if (content.type === "audio") {
  152. const textTask = async () => {
  153. for await (const text of content.transcriptChunks()) {
  154. botMessage.content += text;
  155. }
  156. };
  157. const audioTask = async () => {
  158. audioHandlerRef.current?.startStreamingPlayback();
  159. for await (const audio of content.audioChunks()) {
  160. audioHandlerRef.current?.playChunk(audio);
  161. }
  162. };
  163. await Promise.all([textTask(), audioTask()]);
  164. }
  165. // update message.content
  166. chatStore.updateTargetSession(session, (session) => {
  167. session.messages = session.messages.concat();
  168. });
  169. }
  170. // upload audio get audio_url
  171. const blob = audioHandlerRef.current?.savePlayFile();
  172. uploadImage(blob!).then((audio_url) => {
  173. botMessage.audio_url = audio_url;
  174. // botMessage.date = new Date().toLocaleString();
  175. // update text and audio_url
  176. chatStore.updateTargetSession(session, (session) => {
  177. session.messages = session.messages.concat();
  178. });
  179. });
  180. }
  181. }
  182. };
  183. const handleInputAudio = async (item: RTInputAudioItem) => {
  184. audioHandlerRef.current?.stopStreamingPlayback();
  185. await item.waitForCompletion();
  186. if (item.transcription) {
  187. const userMessage = createMessage({
  188. role: "user",
  189. content: item.transcription,
  190. });
  191. chatStore.updateTargetSession(session, (session) => {
  192. session.messages = session.messages.concat([userMessage]);
  193. });
  194. // save input audio_url, and update session
  195. const { audioStartMillis, audioEndMillis } = item;
  196. // upload audio get audio_url
  197. const blob = audioHandlerRef.current?.saveRecordFile(
  198. audioStartMillis,
  199. audioEndMillis,
  200. );
  201. uploadImage(blob!).then((audio_url) => {
  202. userMessage.audio_url = audio_url;
  203. chatStore.updateTargetSession(session, (session) => {
  204. session.messages = session.messages.concat();
  205. });
  206. });
  207. }
  208. };
  209. const toggleRecording = async () => {
  210. if (!isRecording && clientRef.current) {
  211. try {
  212. if (!audioHandlerRef.current) {
  213. audioHandlerRef.current = new AudioHandler();
  214. await audioHandlerRef.current.initialize();
  215. }
  216. await audioHandlerRef.current.startRecording(async (chunk) => {
  217. await clientRef.current?.sendAudio(chunk);
  218. });
  219. setIsRecording(true);
  220. } catch (error) {
  221. console.error("Failed to start recording:", error);
  222. }
  223. } else if (audioHandlerRef.current) {
  224. try {
  225. audioHandlerRef.current.stopRecording();
  226. if (!useVAD) {
  227. const inputAudio = await clientRef.current?.commitAudio();
  228. await handleInputAudio(inputAudio!);
  229. await clientRef.current?.generateResponse();
  230. }
  231. setIsRecording(false);
  232. } catch (error) {
  233. console.error("Failed to stop recording:", error);
  234. }
  235. }
  236. };
  237. useEffect(
  238. useDebouncedCallback(() => {
  239. const initAudioHandler = async () => {
  240. const handler = new AudioHandler();
  241. await handler.initialize();
  242. audioHandlerRef.current = handler;
  243. await handleConnect();
  244. await toggleRecording();
  245. };
  246. initAudioHandler().catch((error) => {
  247. setStatus(error);
  248. console.error(error);
  249. });
  250. return () => {
  251. if (isRecording) {
  252. toggleRecording();
  253. }
  254. audioHandlerRef.current?.close().catch(console.error);
  255. disconnect();
  256. };
  257. }),
  258. [],
  259. );
  260. const handleClose = async () => {
  261. onClose?.();
  262. if (isRecording) {
  263. await toggleRecording();
  264. }
  265. disconnect().catch(console.error);
  266. };
  267. return (
  268. <div className={styles["realtime-chat"]}>
  269. <div
  270. className={clsx(styles["circle-mic"], {
  271. [styles["pulse"]]: true,
  272. })}
  273. >
  274. <div className={styles["icon-center"]}></div>
  275. </div>
  276. <div className={styles["bottom-icons"]}>
  277. <div>
  278. <IconButton
  279. icon={isRecording ? <VoiceOffIcon /> : <VoiceIcon />}
  280. onClick={toggleRecording}
  281. disabled={!isConnected}
  282. type={isRecording ? "danger" : isConnected ? "primary" : null}
  283. />
  284. </div>
  285. <div className={styles["icon-center"]}>{status}</div>
  286. <div>
  287. <IconButton
  288. icon={<PowerIcon />}
  289. onClick={handleClose}
  290. type={isConnecting || isConnected ? "danger" : "primary"}
  291. />
  292. </div>
  293. </div>
  294. </div>
  295. );
  296. }