realtime-chat.tsx 9.2 KB

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