框架集成
按框架选择完整接入流程:安装 → 预制组件 → 自定义 UI → 多模态 → TTS 语音播报 → 主题。
安装
安装依赖bash
1npm install @lingshuai/chat-react2# 或3pnpm add @lingshuai/chat-react
预制组件(推荐)
开箱即用的聊天组件,包含完整 UI 和交互逻辑。
App.tsx - 动态获取临时Tokentsx
1import { ChatProvider, ChatWidget } from '@lingshuai/chat-react';2import { useState, useEffect } from 'react';34// ⭐ 重要:从后端动态获取临时Token,不要写死在代码里!5function App() {6 const [tempToken, setTempToken] = useState<string>('');78 useEffect(() => {9 // 从你的后端获取临时Token10 fetch('/api/auth/temp-token', {11 method: 'POST',12 credentials: 'include' // 携带session cookie13 })14 .then(res => res.json())15 .then(data => setTempToken(data.tempToken))16 .catch(err => console.error('获取临时Token失败:', err));17 }, []);1819 if (!tempToken) {20 return <div>加载中...</div>;21 }2223 return (24 <ChatProvider25 config={{ apiKey: tempToken, appId: process.env.REACT_APP_LINGSHUAI_APP_ID }}26 >27 <YourApp />28 <ChatWidget29 apiKey={tempToken}30 appId={process.env.REACT_APP_LINGSHUAI_APP_ID}31 title="智能客服"32 welcomeMessage="您好!有什么可以帮助您的?"33 position="bottom-right"34 />35 </ChatProvider>36 );37}
自定义 UI(useChat Hook)
ChatPage.tsx - 动态获取临时Tokentsx
1import { useChat } from '@lingshuai/chat-react';2import { useState, useEffect } from 'react';34function ChatPage() {5 const [inputValue, setInputValue] = useState('');6 const [tempToken, setTempToken] = useState<string>('');78 // ⭐ 从后端动态获取临时Token9 useEffect(() => {10 fetch('/api/auth/temp-token', {11 method: 'POST',12 credentials: 'include'13 })14 .then(res => res.json())15 .then(data => setTempToken(data.tempToken));16 }, []);1718 const {19 messages,20 sendMessage,21 isLoading,22 isSending,23 error,24 } = useChat({25 apiKey: tempToken, // ⭐ 使用动态获取的临时Token26 appId: process.env.REACT_APP_LINGSHUAI_APP_ID,27 });2829 const handleSend = () => {30 if (!inputValue.trim() || isLoading) return;31 sendMessage(inputValue);32 setInputValue('');33 };3435 if (!tempToken) return <div>加载中...</div>;3637 return (38 <div className="flex flex-col h-screen">39 <div className="flex-1 overflow-y-auto p-4 space-y-4">40 {messages.map((msg) => (41 <div key={msg.id} className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}>42 <div className={`max-w-[70%] px-4 py-2 rounded-2xl ${43 msg.role === 'user' ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-900'44 }`}>45 {msg.content}46 {msg.status === 'streaming' && <span className="inline-block w-2 h-4 ml-1 bg-current animate-pulse" />}47 </div>48 </div>49 ))}50 </div>51 <div className="border-t p-4 flex space-x-2">52 <input53 value={inputValue}54 onChange={(e) => setInputValue(e.target.value)}55 onKeyDown={(e) => e.key === 'Enter' && handleSend()}56 placeholder="输入消息..."57 className="flex-1 px-4 py-2 border rounded-full"58 disabled={isLoading}59 />60 <button onClick={handleSend} disabled={isLoading || !inputValue.trim()}61 className="px-6 py-2 bg-blue-600 text-white rounded-full disabled:opacity-50">62 发送63 </button>64 </div>65 </div>66 );67}
多模态(图片 / 语音 / 视频)
useChat 同时返回 sendImage / sendVoice / sendVideo,无需额外安装。
多模态发送 - 使用动态Tokentsx
1import { useChat } from '@lingshuai/chat-react';2import { useState, useEffect } from 'react';34function ChatPage() {5 const [tempToken, setTempToken] = useState('');67 // ⭐ 从后端动态获取临时Token8 useEffect(() => {9 fetch('/api/auth/temp-token', { method: 'POST', credentials: 'include' })10 .then(res => res.json())11 .then(data => setTempToken(data.tempToken));12 }, []);1314 const {15 sendImage, // 发送图片16 sendVoice, // 发送语音17 sendVideo, // 发送视频18 uploadFile, // 手动上传19 sendWithAttachments,20 isUploading,21 } = useChat({22 apiKey: tempToken, // ⭐ 使用动态获取的临时Token(tmp_live_xxx格式)23 appId: process.env.REACT_APP_LINGSHUAI_APP_ID,24 });2526 // 一行代码发送图片27 const handleImageUpload = async (file: File) => {28 await sendImage(file, '请分析这张图片');29 };3031 // 手动控制:先上传再发送32 const handleCustomUpload = async (file: File) => {33 const result = await uploadFile(file, 'image');34 await sendWithAttachments('请看这张图', [{35 type: 'image',36 url: result.url,37 mimeType: result.mimeType,38 name: result.name,39 size: result.size,40 }]);41 };4243 return (44 <div>45 <input type="file" accept="image/*"46 onChange={(e) => { if (e.target.files?.[0]) handleImageUpload(e.target.files[0]); }}47 />48 {isUploading && <p>上传中...</p>}49 </div>50 );51}
TTS 语音播报
SDK 支持两种 TTS 模式:WebSocket 模式(推荐,低延迟流式播放)和 API 模式(传统 HTTP 合成)。 默认自动选择 WebSocket 模式,失败时回退到 API 模式。
TTS 用法 - 使用动态Tokentsx
1import { useChat } from '@lingshuai/chat-react';2import { useState, useEffect } from 'react';34function ChatPage() {5 const [tempToken, setTempToken] = useState('');67 // ⭐ 从后端动态获取临时Token8 useEffect(() => {9 fetch('/api/auth/temp-token', { method: 'POST', credentials: 'include' })10 .then(res => res.json())11 .then(data => setTempToken(data.tempToken));12 }, []);1314 const {15 messages,16 sendMessage,17 // TTS 相关18 ttsMuted, // 是否静音19 setTtsMuted, // 开关流式播报20 getTtsVoices, // 获取可用音色列表21 playTts, // 单条消息播放22 stopTts, // 停止播放23 ttsPlayingMessageId, // 正在播放的消息 ID24 ttsPlayState, // 播放状态:'idle' | 'loading' | 'playing' | 'paused' | 'error'25 } = useChat({26 apiKey: tempToken, // ⭐ 使用动态获取的临时Token(tmp_live_xxx格式)27 appId: process.env.REACT_APP_LINGSHUAI_APP_ID,28 // 可选:强制使用 WebSocket 模式29 // ttsWebSocket: { forceWebSocket: true }30 });3132 // 开启流式播报:AI 边回答边播放33 const enableStreaming = () => setTtsMuted(false);3435 // 单条消息播放(默认使用 WebSocket 模式)36 const handlePlay = (msg: { id: string; content: string }) => {37 // 方式1:自动模式(推荐)38 playTts(msg.id, msg.content);3940 // 方式2:指定音色和模式41 // playTts(msg.id, msg.content, { voice: 'longxiaochun', mode: 'websocket' });4243 // 方式3:指定 API 模式(传统 HTTP)44 // playTts(msg.id, msg.content, { mode: 'api' });45 };4647 return (48 <div>49 <button onClick={() => setTtsMuted(!ttsMuted)}>50 {ttsMuted ? '开启语音' : '关闭语音'}51 </button>52 {messages.map((msg) => (53 <div key={msg.id}>54 <p>{msg.content}</p>55 {msg.role === 'assistant' && (56 <button onClick={() => handlePlay(msg)}>57 {ttsPlayingMessageId === msg.id ? '播放中...' : '播放'}58 </button>59 )}60 </div>61 ))}62 </div>63 );64}
TTS 模式对比
| 特性 | WebSocket 模式 | API 模式 |
|---|---|---|
| 延迟 | 低(流式) | 高(完整合成) |
| 音频格式 | PCM | MP3 |
| 播放器 | Web Audio API | HTMLAudioElement |
| 适用场景 | 实时对话、自动播报 | 单条消息播放 |
主题定制
主题配置tsx
1<ChatWidget2 theme="glass" // 'minimal' | 'glass' | 'bubble'3 themeConfig={{4 primaryColor: '#6366f1',5 backgroundColor: '#f8fafc',6 textColor: '#1e293b',7 userBubbleColor: '#6366f1',8 assistantBubbleColor: '#f1f5f9',9 }}10/>