realtime-chat.tsx 8.7 KB

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