realtime-chat.tsx 9.2 KB

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