realtime-chat.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import VoiceIcon from "@/app/icons/voice.svg";
  2. import VoiceOffIcon from "@/app/icons/voice-off.svg";
  3. import Close24Icon from "@/app/icons/close-24.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 (!isConnected) {
  53. try {
  54. setIsConnecting(true);
  55. clientRef.current = isAzure
  56. ? new RTClient(new URL(endpoint), { key: apiKey }, { deployment })
  57. : new RTClient(
  58. { key: apiKey },
  59. { model: "gpt-4o-realtime-preview-2024-10-01" },
  60. );
  61. const modalities: Modality[] =
  62. modality === "audio" ? ["text", "audio"] : ["text"];
  63. const turnDetection: TurnDetection = useVAD
  64. ? { type: "server_vad" }
  65. : null;
  66. clientRef.current.configure({
  67. instructions: "Hi",
  68. input_audio_transcription: { model: "whisper-1" },
  69. turn_detection: turnDetection,
  70. tools: [],
  71. temperature: 0.9,
  72. modalities,
  73. });
  74. startResponseListener();
  75. setIsConnected(true);
  76. } catch (error) {
  77. console.error("Connection failed:", error);
  78. } finally {
  79. setIsConnecting(false);
  80. }
  81. } else {
  82. await disconnect();
  83. }
  84. };
  85. const disconnect = async () => {
  86. if (clientRef.current) {
  87. try {
  88. await clientRef.current.close();
  89. clientRef.current = null;
  90. setIsConnected(false);
  91. } catch (error) {
  92. console.error("Disconnect failed:", error);
  93. }
  94. }
  95. };
  96. const startResponseListener = async () => {
  97. if (!clientRef.current) return;
  98. try {
  99. for await (const serverEvent of clientRef.current.events()) {
  100. if (serverEvent.type === "response") {
  101. await handleResponse(serverEvent);
  102. } else if (serverEvent.type === "input_audio") {
  103. await handleInputAudio(serverEvent);
  104. }
  105. }
  106. } catch (error) {
  107. if (clientRef.current) {
  108. console.error("Response iteration error:", error);
  109. }
  110. }
  111. };
  112. const handleResponse = async (response: RTResponse) => {
  113. for await (const item of response) {
  114. if (item.type === "message" && item.role === "assistant") {
  115. const botMessage = createMessage({
  116. role: item.role,
  117. content: "",
  118. });
  119. // add bot message first
  120. chatStore.updateTargetSession(session, (session) => {
  121. session.messages = session.messages.concat([botMessage]);
  122. });
  123. for await (const content of item) {
  124. if (content.type === "text") {
  125. for await (const text of content.textChunks()) {
  126. botMessage.content += text;
  127. }
  128. } else if (content.type === "audio") {
  129. const textTask = async () => {
  130. for await (const text of content.transcriptChunks()) {
  131. botMessage.content += text;
  132. }
  133. };
  134. const audioTask = async () => {
  135. audioHandlerRef.current?.startStreamingPlayback();
  136. for await (const audio of content.audioChunks()) {
  137. audioHandlerRef.current?.playChunk(audio);
  138. }
  139. };
  140. await Promise.all([textTask(), audioTask()]);
  141. }
  142. // update message.content
  143. chatStore.updateTargetSession(session, (session) => {
  144. session.messages = session.messages.concat();
  145. });
  146. }
  147. // upload audio get audio_url
  148. const blob = audioHandlerRef.current?.savePlayFile();
  149. uploadImage(blob).then((audio_url) => {
  150. botMessage.audio_url = audio_url;
  151. // botMessage.date = new Date().toLocaleString();
  152. // update text and audio_url
  153. chatStore.updateTargetSession(session, (session) => {
  154. session.messages = session.messages.concat();
  155. });
  156. });
  157. }
  158. }
  159. };
  160. const handleInputAudio = async (item: RTInputAudioItem) => {
  161. audioHandlerRef.current?.stopStreamingPlayback();
  162. await item.waitForCompletion();
  163. if (item.transcription) {
  164. const userMessage = createMessage({
  165. role: "user",
  166. content: item.transcription,
  167. });
  168. chatStore.updateTargetSession(session, (session) => {
  169. session.messages = session.messages.concat([userMessage]);
  170. });
  171. // save input audio_url, and update session
  172. const { audioStartMillis, audioEndMillis } = item;
  173. // upload audio get audio_url
  174. const blob = audioHandlerRef.current?.saveRecordFile(
  175. audioStartMillis,
  176. audioEndMillis,
  177. );
  178. uploadImage(blob).then((audio_url) => {
  179. userMessage.audio_url = audio_url;
  180. chatStore.updateTargetSession(session, (session) => {
  181. session.messages = session.messages.concat();
  182. });
  183. });
  184. }
  185. };
  186. const toggleRecording = async () => {
  187. if (!isRecording && clientRef.current) {
  188. try {
  189. if (!audioHandlerRef.current) {
  190. audioHandlerRef.current = new AudioHandler();
  191. await audioHandlerRef.current.initialize();
  192. }
  193. await audioHandlerRef.current.startRecording(async (chunk) => {
  194. await clientRef.current?.sendAudio(chunk);
  195. });
  196. setIsRecording(true);
  197. } catch (error) {
  198. console.error("Failed to start recording:", error);
  199. }
  200. } else if (audioHandlerRef.current) {
  201. try {
  202. audioHandlerRef.current.stopRecording();
  203. if (!useVAD) {
  204. const inputAudio = await clientRef.current?.commitAudio();
  205. await handleInputAudio(inputAudio!);
  206. await clientRef.current?.generateResponse();
  207. }
  208. setIsRecording(false);
  209. } catch (error) {
  210. console.error("Failed to stop recording:", error);
  211. }
  212. }
  213. };
  214. useEffect(() => {
  215. const initAudioHandler = async () => {
  216. const handler = new AudioHandler();
  217. await handler.initialize();
  218. audioHandlerRef.current = handler;
  219. };
  220. initAudioHandler().catch(console.error);
  221. return () => {
  222. disconnect();
  223. audioHandlerRef.current?.close().catch(console.error);
  224. };
  225. }, []);
  226. // useEffect(() => {
  227. // if (
  228. // clientRef.current?.getTurnDetectionType() === "server_vad" &&
  229. // audioData
  230. // ) {
  231. // // console.log("appendInputAudio", audioData);
  232. // // 将录制的16PCM音频发送给openai
  233. // clientRef.current?.appendInputAudio(audioData);
  234. // }
  235. // }, [audioData]);
  236. // useEffect(() => {
  237. // console.log("isRecording", isRecording);
  238. // if (!isRecording.current) return;
  239. // if (!clientRef.current) {
  240. // const apiKey = accessStore.openaiApiKey;
  241. // const client = (clientRef.current = new RealtimeClient({
  242. // url: "wss://api.openai.com/v1/realtime",
  243. // apiKey,
  244. // dangerouslyAllowAPIKeyInBrowser: true,
  245. // debug: true,
  246. // }));
  247. // client
  248. // .connect()
  249. // .then(() => {
  250. // // TODO 设置真实的上下文
  251. // client.sendUserMessageContent([
  252. // {
  253. // type: `input_text`,
  254. // text: `Hi`,
  255. // // text: `For testing purposes, I want you to list ten car brands. Number each item, e.g. "one (or whatever number you are one): the item name".`
  256. // },
  257. // ]);
  258. // // 配置服务端判断说话人开启还是结束
  259. // client.updateSession({
  260. // turn_detection: { type: "server_vad" },
  261. // });
  262. // client.on("realtime.event", (realtimeEvent) => {
  263. // // 调试
  264. // console.log("realtime.event", realtimeEvent);
  265. // });
  266. // client.on("conversation.interrupted", async () => {
  267. // if (currentBotMessage.current) {
  268. // stopPlaying();
  269. // try {
  270. // client.cancelResponse(
  271. // currentBotMessage.current?.id,
  272. // currentTime(),
  273. // );
  274. // } catch (e) {
  275. // console.error(e);
  276. // }
  277. // }
  278. // });
  279. // client.on("conversation.updated", async (event: any) => {
  280. // // console.log("currentSession", chatStore.currentSession());
  281. // // const items = client.conversation.getItems();
  282. // const content = event?.item?.content?.[0]?.transcript || "";
  283. // const text = event?.item?.content?.[0]?.text || "";
  284. // // console.log(
  285. // // "conversation.updated",
  286. // // event,
  287. // // "content[0]",
  288. // // event?.item?.content?.[0]?.transcript,
  289. // // "formatted",
  290. // // event?.item?.formatted?.transcript,
  291. // // "content",
  292. // // content,
  293. // // "text",
  294. // // text,
  295. // // event?.item?.status,
  296. // // event?.item?.role,
  297. // // items.length,
  298. // // items,
  299. // // );
  300. // const { item, delta } = event;
  301. // const { role, id, status, formatted } = item || {};
  302. // if (id && role == "assistant") {
  303. // if (
  304. // !currentBotMessage.current ||
  305. // currentBotMessage.current?.id != id
  306. // ) {
  307. // // create assistant message and save to session
  308. // currentBotMessage.current = createMessage({ id, role });
  309. // chatStore.updateCurrentSession((session) => {
  310. // session.messages = session.messages.concat([
  311. // currentBotMessage.current!,
  312. // ]);
  313. // });
  314. // }
  315. // if (currentBotMessage.current?.id != id) {
  316. // stopPlaying();
  317. // }
  318. // if (content) {
  319. // currentBotMessage.current.content = content;
  320. // chatStore.updateCurrentSession((session) => {
  321. // session.messages = session.messages.concat();
  322. // });
  323. // }
  324. // if (delta?.audio) {
  325. // // typeof delta.audio is Int16Array
  326. // // 直接播放
  327. // addInt16PCM(delta.audio);
  328. // }
  329. // // console.log(
  330. // // "updated try save wavFile",
  331. // // status,
  332. // // currentBotMessage.current?.audio_url,
  333. // // formatted?.audio,
  334. // // );
  335. // if (
  336. // status == "completed" &&
  337. // !currentBotMessage.current?.audio_url &&
  338. // formatted?.audio?.length
  339. // ) {
  340. // // 转换为wav文件保存 TODO 使用mp3格式会更节省空间
  341. // const botMessage = currentBotMessage.current;
  342. // const wavFile = new WavPacker().pack(sampleRate, {
  343. // bitsPerSample: 16,
  344. // channelCount: 1,
  345. // data: formatted?.audio,
  346. // });
  347. // // 这里将音频文件放到对象里面wavFile.url可以使用<audio>标签播放
  348. // item.formatted.file = wavFile;
  349. // uploadImageRemote(wavFile.blob).then((audio_url) => {
  350. // botMessage.audio_url = audio_url;
  351. // chatStore.updateCurrentSession((session) => {
  352. // session.messages = session.messages.concat();
  353. // });
  354. // });
  355. // }
  356. // if (
  357. // status == "completed" &&
  358. // !currentBotMessage.current?.content
  359. // ) {
  360. // chatStore.updateCurrentSession((session) => {
  361. // session.messages = session.messages.filter(
  362. // (m) => m.id !== currentBotMessage.current?.id,
  363. // );
  364. // });
  365. // }
  366. // }
  367. // if (id && role == "user" && !text) {
  368. // if (
  369. // !currentUserMessage.current ||
  370. // currentUserMessage.current?.id != id
  371. // ) {
  372. // // create assistant message and save to session
  373. // currentUserMessage.current = createMessage({ id, role });
  374. // chatStore.updateCurrentSession((session) => {
  375. // session.messages = session.messages.concat([
  376. // currentUserMessage.current!,
  377. // ]);
  378. // });
  379. // }
  380. // if (content) {
  381. // // 转换为wav文件保存 TODO 使用mp3格式会更节省空间
  382. // const userMessage = currentUserMessage.current;
  383. // const wavFile = new WavPacker().pack(sampleRate, {
  384. // bitsPerSample: 16,
  385. // channelCount: 1,
  386. // data: formatted?.audio,
  387. // });
  388. // // 这里将音频文件放到对象里面wavFile.url可以使用<audio>标签播放
  389. // item.formatted.file = wavFile;
  390. // uploadImageRemote(wavFile.blob).then((audio_url) => {
  391. // // update message content
  392. // userMessage.content = content;
  393. // // update message audio_url
  394. // userMessage.audio_url = audio_url;
  395. // chatStore.updateCurrentSession((session) => {
  396. // session.messages = session.messages.concat();
  397. // });
  398. // });
  399. // }
  400. // }
  401. // });
  402. // })
  403. // .catch((e) => {
  404. // console.error("Error", e);
  405. // });
  406. // }
  407. // return () => {
  408. // stop();
  409. // // TODO close client
  410. // clientRef.current?.disconnect();
  411. // };
  412. // }, [isRecording.current]);
  413. const handleClose = () => {
  414. onClose?.();
  415. disconnect();
  416. };
  417. return (
  418. <div className={styles["realtime-chat"]}>
  419. <div
  420. className={clsx(styles["circle-mic"], {
  421. [styles["pulse"]]: true,
  422. })}
  423. >
  424. <div className={styles["icon-center"]}></div>
  425. </div>
  426. <div className={styles["bottom-icons"]}>
  427. <div>
  428. <IconButton
  429. icon={isRecording ? <VoiceOffIcon /> : <VoiceIcon />}
  430. onClick={toggleRecording}
  431. disabled={!isConnected}
  432. bordered
  433. shadow
  434. />
  435. </div>
  436. <div className={styles["icon-center"]}>
  437. <IconButton
  438. icon={<PowerIcon />}
  439. text={
  440. isConnecting
  441. ? "Connecting..."
  442. : isConnected
  443. ? "Disconnect"
  444. : "Connect"
  445. }
  446. onClick={handleConnect}
  447. disabled={isConnecting}
  448. bordered
  449. shadow
  450. />
  451. </div>
  452. <div onClick={handleClose}>
  453. <IconButton
  454. icon={<Close24Icon />}
  455. onClick={handleClose}
  456. bordered
  457. shadow
  458. />
  459. </div>
  460. </div>
  461. </div>
  462. );
  463. }