realtime-chat.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. audioHandlerRef.current?.stopStreamingPlayback();
  189. await item.waitForCompletion();
  190. if (item.transcription) {
  191. const userMessage = createMessage({
  192. role: "user",
  193. content: item.transcription,
  194. });
  195. chatStore.updateTargetSession(session, (session) => {
  196. session.messages = session.messages.concat([userMessage]);
  197. });
  198. // save input audio_url, and update session
  199. const { audioStartMillis, audioEndMillis } = item;
  200. // upload audio get audio_url
  201. const blob = audioHandlerRef.current?.saveRecordFile(
  202. audioStartMillis,
  203. audioEndMillis,
  204. );
  205. uploadImage(blob!).then((audio_url) => {
  206. userMessage.audio_url = audio_url;
  207. chatStore.updateTargetSession(session, (session) => {
  208. session.messages = session.messages.concat();
  209. });
  210. });
  211. }
  212. };
  213. const toggleRecording = async () => {
  214. if (!isRecording && clientRef.current) {
  215. try {
  216. if (!audioHandlerRef.current) {
  217. audioHandlerRef.current = new AudioHandler();
  218. await audioHandlerRef.current.initialize();
  219. }
  220. await audioHandlerRef.current.startRecording(async (chunk) => {
  221. await clientRef.current?.sendAudio(chunk);
  222. });
  223. setIsRecording(true);
  224. } catch (error) {
  225. console.error("Failed to start recording:", error);
  226. }
  227. } else if (audioHandlerRef.current) {
  228. try {
  229. audioHandlerRef.current.stopRecording();
  230. if (!useVAD) {
  231. const inputAudio = await clientRef.current?.commitAudio();
  232. await handleInputAudio(inputAudio!);
  233. await clientRef.current?.generateResponse();
  234. }
  235. setIsRecording(false);
  236. } catch (error) {
  237. console.error("Failed to stop recording:", error);
  238. }
  239. }
  240. };
  241. useEffect(
  242. useDebouncedCallback(() => {
  243. const initAudioHandler = async () => {
  244. const handler = new AudioHandler();
  245. await handler.initialize();
  246. audioHandlerRef.current = handler;
  247. await handleConnect();
  248. await toggleRecording();
  249. };
  250. initAudioHandler().catch((error) => {
  251. setStatus(error);
  252. console.error(error);
  253. });
  254. return () => {
  255. if (isRecording) {
  256. toggleRecording();
  257. }
  258. audioHandlerRef.current?.close().catch(console.error);
  259. disconnect();
  260. };
  261. }),
  262. [],
  263. );
  264. // update session params
  265. useEffect(() => {
  266. clientRef.current?.configure({ voice });
  267. }, [voice]);
  268. useEffect(() => {
  269. clientRef.current?.configure({ temperature });
  270. }, [temperature]);
  271. const handleClose = async () => {
  272. onClose?.();
  273. if (isRecording) {
  274. await toggleRecording();
  275. }
  276. disconnect().catch(console.error);
  277. };
  278. return (
  279. <div className={styles["realtime-chat"]}>
  280. <div
  281. className={clsx(styles["circle-mic"], {
  282. [styles["pulse"]]: true,
  283. })}
  284. >
  285. <div className={styles["icon-center"]}></div>
  286. </div>
  287. <div className={styles["bottom-icons"]}>
  288. <div>
  289. <IconButton
  290. icon={isRecording ? <VoiceOffIcon /> : <VoiceIcon />}
  291. onClick={toggleRecording}
  292. disabled={!isConnected}
  293. type={isRecording ? "danger" : isConnected ? "primary" : null}
  294. />
  295. </div>
  296. <div className={styles["icon-center"]}>{status}</div>
  297. <div>
  298. <IconButton
  299. icon={<PowerIcon />}
  300. onClick={handleClose}
  301. type={isConnecting || isConnected ? "danger" : "primary"}
  302. />
  303. </div>
  304. </div>
  305. </div>
  306. );
  307. }