deepseek-stream-demo.html 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>DeepSeek 流式输出示例</title>
  7. <style>
  8. * {
  9. margin: 0;
  10. padding: 0;
  11. box-sizing: border-box;
  12. }
  13. body {
  14. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
  15. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  16. min-height: 100vh;
  17. padding: 20px;
  18. }
  19. .container {
  20. max-width: 1200px;
  21. margin: 0 auto;
  22. background: white;
  23. border-radius: 16px;
  24. box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  25. overflow: hidden;
  26. }
  27. .header {
  28. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  29. color: white;
  30. padding: 30px;
  31. text-align: center;
  32. }
  33. .header h1 {
  34. font-size: 28px;
  35. margin-bottom: 10px;
  36. }
  37. .header p {
  38. opacity: 0.9;
  39. font-size: 14px;
  40. }
  41. .content {
  42. padding: 30px;
  43. }
  44. .form-group {
  45. margin-bottom: 20px;
  46. }
  47. .form-group label {
  48. display: block;
  49. margin-bottom: 8px;
  50. font-weight: 600;
  51. color: #333;
  52. }
  53. .form-group input,
  54. .form-group textarea,
  55. .form-group select {
  56. width: 100%;
  57. padding: 12px;
  58. border: 2px solid #e0e0e0;
  59. border-radius: 8px;
  60. font-size: 14px;
  61. transition: border-color 0.3s;
  62. }
  63. .form-group input:focus,
  64. .form-group textarea:focus,
  65. .form-group select:focus {
  66. outline: none;
  67. border-color: #667eea;
  68. }
  69. .form-group textarea {
  70. min-height: 120px;
  71. resize: vertical;
  72. font-family: inherit;
  73. }
  74. .form-row {
  75. display: grid;
  76. grid-template-columns: 1fr 1fr;
  77. gap: 20px;
  78. }
  79. .btn {
  80. padding: 12px 30px;
  81. border: none;
  82. border-radius: 8px;
  83. font-size: 16px;
  84. font-weight: 600;
  85. cursor: pointer;
  86. transition: all 0.3s;
  87. }
  88. .btn-primary {
  89. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  90. color: white;
  91. }
  92. .btn-primary:hover:not(:disabled) {
  93. transform: translateY(-2px);
  94. box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
  95. }
  96. .btn-primary:disabled {
  97. opacity: 0.6;
  98. cursor: not-allowed;
  99. }
  100. .btn-danger {
  101. background: #ef4444;
  102. color: white;
  103. margin-left: 10px;
  104. }
  105. .btn-danger:hover:not(:disabled) {
  106. background: #dc2626;
  107. }
  108. .output-section {
  109. margin-top: 30px;
  110. display: none;
  111. }
  112. .output-section.active {
  113. display: block;
  114. }
  115. .output-box {
  116. background: #f8f9fa;
  117. border: 2px solid #e0e0e0;
  118. border-radius: 8px;
  119. padding: 20px;
  120. margin-bottom: 20px;
  121. }
  122. .output-box h3 {
  123. color: #667eea;
  124. margin-bottom: 15px;
  125. font-size: 18px;
  126. display: flex;
  127. align-items: center;
  128. gap: 10px;
  129. }
  130. .output-box .content-area {
  131. background: white;
  132. padding: 15px;
  133. border-radius: 6px;
  134. min-height: 100px;
  135. max-height: 400px;
  136. overflow-y: auto;
  137. white-space: pre-wrap;
  138. word-wrap: break-word;
  139. line-height: 1.6;
  140. font-size: 14px;
  141. color: #333;
  142. }
  143. .status-badge {
  144. display: inline-block;
  145. padding: 4px 12px;
  146. border-radius: 12px;
  147. font-size: 12px;
  148. font-weight: 600;
  149. }
  150. .status-connecting {
  151. background: #fef3c7;
  152. color: #92400e;
  153. }
  154. .status-streaming {
  155. background: #dbeafe;
  156. color: #1e40af;
  157. animation: pulse 2s infinite;
  158. }
  159. .status-completed {
  160. background: #d1fae5;
  161. color: #065f46;
  162. }
  163. .status-error {
  164. background: #fee2e2;
  165. color: #991b1b;
  166. }
  167. @keyframes pulse {
  168. 0%, 100% { opacity: 1; }
  169. 50% { opacity: 0.7; }
  170. }
  171. .loading-spinner {
  172. display: inline-block;
  173. width: 16px;
  174. height: 16px;
  175. border: 2px solid #667eea;
  176. border-top-color: transparent;
  177. border-radius: 50%;
  178. animation: spin 0.8s linear infinite;
  179. }
  180. @keyframes spin {
  181. to { transform: rotate(360deg); }
  182. }
  183. .stats {
  184. display: grid;
  185. grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  186. gap: 15px;
  187. margin-top: 20px;
  188. }
  189. .stat-item {
  190. background: white;
  191. padding: 15px;
  192. border-radius: 8px;
  193. border: 1px solid #e0e0e0;
  194. }
  195. .stat-item .label {
  196. font-size: 12px;
  197. color: #666;
  198. margin-bottom: 5px;
  199. }
  200. .stat-item .value {
  201. font-size: 20px;
  202. font-weight: 700;
  203. color: #667eea;
  204. }
  205. .script-preview {
  206. background: white;
  207. padding: 20px;
  208. border-radius: 8px;
  209. margin-top: 15px;
  210. }
  211. .script-section {
  212. margin-bottom: 20px;
  213. padding-bottom: 20px;
  214. border-bottom: 1px solid #e0e0e0;
  215. }
  216. .script-section:last-child {
  217. border-bottom: none;
  218. }
  219. .script-section h4 {
  220. color: #667eea;
  221. margin-bottom: 10px;
  222. font-size: 16px;
  223. }
  224. .script-section p {
  225. line-height: 1.8;
  226. color: #333;
  227. }
  228. .episode-item {
  229. background: #f8f9fa;
  230. padding: 15px;
  231. border-radius: 6px;
  232. margin-bottom: 10px;
  233. }
  234. .episode-title {
  235. font-weight: 600;
  236. color: #667eea;
  237. margin-bottom: 8px;
  238. }
  239. .file-upload-area {
  240. border: 2px dashed #e0e0e0;
  241. border-radius: 8px;
  242. padding: 30px;
  243. text-align: center;
  244. cursor: pointer;
  245. transition: all 0.3s;
  246. }
  247. .file-upload-area:hover {
  248. border-color: #667eea;
  249. background: #f8f9fa;
  250. }
  251. .file-upload-area.dragover {
  252. border-color: #667eea;
  253. background: #eff6ff;
  254. }
  255. .file-info {
  256. margin-top: 10px;
  257. padding: 10px;
  258. background: #f0fdf4;
  259. border-radius: 6px;
  260. color: #166534;
  261. font-size: 14px;
  262. }
  263. </style>
  264. </head>
  265. <body>
  266. <div class="container">
  267. <div class="header">
  268. <h1>🤖 DeepSeek 流式输出示例</h1>
  269. <p>实时查看 AI 生成剧本的过程</p>
  270. </div>
  271. <div class="content">
  272. <!-- 输入表单 -->
  273. <form id="chatForm">
  274. <div class="form-row">
  275. <div class="form-group">
  276. <label>剧本 ID *</label>
  277. <input type="number" id="scriptId" name="script_id" value="1" required placeholder="请输入剧本ID">
  278. </div>
  279. <div class="form-group">
  280. <label>模型选择</label>
  281. <select id="model" name="model">
  282. <option value="v3">DeepSeek-V3 (推荐)</option>
  283. <option value="r1">DeepSeek-R1 (思考模式)</option>
  284. </select>
  285. </div>
  286. </div>
  287. <div class="form-row">
  288. <div class="form-group">
  289. <label>开始集数</label>
  290. <input type="number" id="startEpisode" name="start_episode_sequence" value="1" min="1">
  291. </div>
  292. <div class="form-group">
  293. <label>总集数</label>
  294. <input type="number" id="totalEpisode" name="total_episode_num" value="30" min="1">
  295. </div>
  296. </div>
  297. <div class="form-group">
  298. <label>文件上传 (可选)</label>
  299. <div class="file-upload-area" id="fileUploadArea">
  300. <p>📁 点击或拖拽文件到此处</p>
  301. <p style="font-size: 12px; color: #666; margin-top: 5px;">支持 TXT、PDF 格式</p>
  302. </div>
  303. <input type="file" id="fileInput" accept=".txt,.pdf" style="display: none;">
  304. <div id="fileInfo" class="file-info" style="display: none;"></div>
  305. </div>
  306. <div class="form-group">
  307. <label>文本内容 (可选)</label>
  308. <textarea id="content" name="content" placeholder="或者直接输入文本内容..."></textarea>
  309. </div>
  310. <div class="form-group">
  311. <label>自定义问题 (可选)</label>
  312. <textarea id="question" name="question" rows="3" placeholder="留空使用默认问题"></textarea>
  313. </div>
  314. <div style="text-align: center; margin-top: 30px;">
  315. <button type="submit" class="btn btn-primary" id="submitBtn">
  316. 🚀 开始生成
  317. </button>
  318. <button type="button" class="btn btn-danger" id="stopBtn" style="display: none;">
  319. ⏹️ 停止生成
  320. </button>
  321. </div>
  322. </form>
  323. <!-- 输出区域 -->
  324. <div class="output-section" id="outputSection">
  325. <div class="output-box">
  326. <h3>
  327. <span>📊 生成状态</span>
  328. <span class="status-badge" id="statusBadge">准备中</span>
  329. </h3>
  330. <div class="stats">
  331. <div class="stat-item">
  332. <div class="label">已接收字符</div>
  333. <div class="value" id="charCount">0</div>
  334. </div>
  335. <div class="stat-item">
  336. <div class="label">生成时间</div>
  337. <div class="value" id="elapsedTime">0s</div>
  338. </div>
  339. <div class="stat-item">
  340. <div class="label">Token 使用</div>
  341. <div class="value" id="tokenUsage">-</div>
  342. </div>
  343. </div>
  344. </div>
  345. <!-- 思维链输出 (仅 R1 模型) -->
  346. <div class="output-box" id="reasoningBox" style="display: none;">
  347. <h3>
  348. <span class="loading-spinner"></span>
  349. 💭 思维链 (Reasoning)
  350. </h3>
  351. <div class="content-area" id="reasoningContent"></div>
  352. </div>
  353. <!-- 内容输出 -->
  354. <div class="output-box">
  355. <h3>
  356. <span class="loading-spinner"></span>
  357. ✍️ 生成内容
  358. </h3>
  359. <div class="content-area" id="contentOutput"></div>
  360. </div>
  361. <!-- 最终结果 -->
  362. <div class="output-box" id="resultBox" style="display: none;">
  363. <h3>✅ 剧本结构化数据</h3>
  364. <div class="script-preview" id="scriptPreview"></div>
  365. </div>
  366. </div>
  367. </div>
  368. </div>
  369. <script>
  370. // 全局变量
  371. let isStreaming = false;
  372. let startTime = null;
  373. let timerInterval = null;
  374. let charCount = 0;
  375. let selectedFile = null;
  376. let currentReader = null; // 保存当前的 reader 引用
  377. let abortController = null; // 用于中断请求
  378. // DOM 元素
  379. const form = document.getElementById('chatForm');
  380. const submitBtn = document.getElementById('submitBtn');
  381. const stopBtn = document.getElementById('stopBtn');
  382. const outputSection = document.getElementById('outputSection');
  383. const statusBadge = document.getElementById('statusBadge');
  384. const reasoningBox = document.getElementById('reasoningBox');
  385. const reasoningContent = document.getElementById('reasoningContent');
  386. const contentOutput = document.getElementById('contentOutput');
  387. const resultBox = document.getElementById('resultBox');
  388. const scriptPreview = document.getElementById('scriptPreview');
  389. const charCountEl = document.getElementById('charCount');
  390. const elapsedTimeEl = document.getElementById('elapsedTime');
  391. const tokenUsageEl = document.getElementById('tokenUsage');
  392. const fileUploadArea = document.getElementById('fileUploadArea');
  393. const fileInput = document.getElementById('fileInput');
  394. const fileInfo = document.getElementById('fileInfo');
  395. // 文件上传处理
  396. fileUploadArea.addEventListener('click', () => fileInput.click());
  397. fileInput.addEventListener('change', (e) => {
  398. const file = e.target.files[0];
  399. if (file) {
  400. selectedFile = file;
  401. fileInfo.textContent = `已选择: ${file.name} (${(file.size / 1024).toFixed(2)} KB)`;
  402. fileInfo.style.display = 'block';
  403. }
  404. });
  405. // 拖拽上传
  406. fileUploadArea.addEventListener('dragover', (e) => {
  407. e.preventDefault();
  408. fileUploadArea.classList.add('dragover');
  409. });
  410. fileUploadArea.addEventListener('dragleave', () => {
  411. fileUploadArea.classList.remove('dragover');
  412. });
  413. fileUploadArea.addEventListener('drop', (e) => {
  414. e.preventDefault();
  415. fileUploadArea.classList.remove('dragover');
  416. const file = e.dataTransfer.files[0];
  417. if (file && (file.name.endsWith('.txt') || file.name.endsWith('.pdf'))) {
  418. selectedFile = file;
  419. fileInput.files = e.dataTransfer.files;
  420. fileInfo.textContent = `已选择: ${file.name} (${(file.size / 1024).toFixed(2)} KB)`;
  421. fileInfo.style.display = 'block';
  422. } else {
  423. alert('请上传 TXT 或 PDF 格式的文件');
  424. }
  425. });
  426. // 表单提交
  427. form.addEventListener('submit', async (e) => {
  428. e.preventDefault();
  429. if (isStreaming) return;
  430. // 重置状态
  431. resetOutput();
  432. outputSection.classList.add('active');
  433. isStreaming = true;
  434. submitBtn.disabled = true;
  435. stopBtn.style.display = 'inline-block';
  436. startTime = Date.now();
  437. startTimer();
  438. // 更新状态
  439. updateStatus('connecting', '连接中...');
  440. // 准备表单数据
  441. const formData = new FormData();
  442. formData.append('script_id', document.getElementById('scriptId').value);
  443. formData.append('model', document.getElementById('model').value);
  444. formData.append('start_episode_sequence', document.getElementById('startEpisode').value);
  445. formData.append('total_episode_num', document.getElementById('totalEpisode').value);
  446. const content = document.getElementById('content').value;
  447. if (content) {
  448. formData.append('content', content);
  449. }
  450. const question = document.getElementById('question').value;
  451. if (question) {
  452. formData.append('question', question);
  453. }
  454. if (selectedFile) {
  455. formData.append('file', selectedFile);
  456. }
  457. // 检查是否为 R1 模型
  458. const isR1Model = document.getElementById('model').value === 'r1';
  459. if (isR1Model) {
  460. reasoningBox.style.display = 'block';
  461. }
  462. // 创建 AbortController 用于中断请求
  463. abortController = new AbortController();
  464. try {
  465. // 发起流式请求,传入 signal 用于中断
  466. const response = await fetch('/api/addChat', {
  467. method: 'POST',
  468. body: formData,
  469. signal: abortController.signal // 关键:添加中断信号
  470. });
  471. if (!response.ok) {
  472. throw new Error(`HTTP error! status: ${response.status}`);
  473. }
  474. updateStatus('streaming', '生成中...');
  475. // 读取流式响应
  476. currentReader = response.body.getReader();
  477. const decoder = new TextDecoder();
  478. let buffer = '';
  479. console.log('开始读取流式数据...'); // 调试日志
  480. while (true) {
  481. const { done, value } = await currentReader.read();
  482. if (done) {
  483. console.log('流式读取完成'); // 调试日志
  484. break;
  485. }
  486. buffer += decoder.decode(value, { stream: true });
  487. const lines = buffer.split('\n');
  488. buffer = lines.pop(); // 保留不完整的行
  489. for (const line of lines) {
  490. if (line.startsWith('data: ')) {
  491. const data = line.slice(6);
  492. console.log('收到原始数据:', data); // 调试日志
  493. if (data === '[DONE]') {
  494. console.log('收到结束标记'); // 调试日志
  495. handleStreamComplete();
  496. return;
  497. }
  498. try {
  499. const json = JSON.parse(data);
  500. handleStreamData(json);
  501. } catch (e) {
  502. console.error('解析 JSON 失败:', e, '原始数据:', data);
  503. }
  504. }
  505. }
  506. }
  507. } catch (error) {
  508. if (error.name === 'AbortError') {
  509. console.log('请求已被用户中断');
  510. updateStatus('error', '已停止');
  511. } else {
  512. console.error('流式请求错误:', error);
  513. updateStatus('error', '生成失败');
  514. alert('生成失败: ' + error.message);
  515. }
  516. } finally {
  517. stopStreaming();
  518. }
  519. });
  520. // 停止按钮
  521. stopBtn.addEventListener('click', () => {
  522. // 中断请求
  523. if (abortController) {
  524. abortController.abort();
  525. }
  526. // 取消 reader
  527. if (currentReader) {
  528. currentReader.cancel();
  529. }
  530. stopStreaming();
  531. updateStatus('error', '已停止');
  532. });
  533. // 处理流式数据
  534. function handleStreamData(data) {
  535. console.log('收到数据:', data); // 调试日志
  536. if (data.type === 'reasoning') {
  537. // 思维链内容
  538. // 注释掉下面两行则不展示思维链内容,仅计数
  539. reasoningContent.textContent = data.full_reasoning || '';
  540. reasoningContent.scrollTop = reasoningContent.scrollHeight;
  541. charCount += (data.content || '').length;
  542. updateCharCount();
  543. } else if (data.type === 'content') {
  544. // 最终回答内容
  545. contentOutput.textContent = data.full_content || '';
  546. contentOutput.scrollTop = contentOutput.scrollHeight;
  547. charCount += (data.content || '').length;
  548. updateCharCount();
  549. } else if (data.type === 'done') {
  550. // 完成
  551. handleComplete(data);
  552. } else if (data.type === 'error') {
  553. // 错误
  554. updateStatus('error', '生成失败');
  555. alert('错误: ' + data.message);
  556. }
  557. }
  558. // 处理完成
  559. function handleComplete(data) {
  560. updateStatus('completed', '生成完成');
  561. // 显示 Token 使用情况
  562. if (data.usage) {
  563. const total = data.usage.total_tokens || 0;
  564. tokenUsageEl.textContent = total.toLocaleString();
  565. }
  566. // 显示结构化剧本数据
  567. if (data.script) {
  568. displayScript(data.script);
  569. resultBox.style.display = 'block';
  570. }
  571. }
  572. // 显示剧本结构
  573. function displayScript(script) {
  574. let html = '';
  575. if (script.intro) {
  576. html += `<div class="script-section">
  577. <h4>📖 故事梗概</h4>
  578. <p>${escapeHtml(script.intro)}</p>
  579. </div>`;
  580. }
  581. if (script.highlights) {
  582. html += `<div class="script-section">
  583. <h4>✨ 剧本亮点</h4>
  584. <p>${escapeHtml(script.highlights)}</p>
  585. </div>`;
  586. }
  587. if (script.role_relationship) {
  588. html += `<div class="script-section">
  589. <h4>👥 人物关系</h4>
  590. <p>${escapeHtml(script.role_relationship)}</p>
  591. </div>`;
  592. }
  593. if (script.episodes && script.episodes.length > 0) {
  594. html += `<div class="script-section">
  595. <h4>🎬 分集剧本 (共 ${script.episodes.length} 集)</h4>`;
  596. script.episodes.forEach(ep => {
  597. html += `<div class="episode-item">
  598. <div class="episode-title">${escapeHtml(ep.title || ep.episode_number)}</div>
  599. <p>${escapeHtml(ep.content || '').substring(0, 200)}...</p>
  600. </div>`;
  601. });
  602. html += `</div>`;
  603. }
  604. scriptPreview.innerHTML = html || '<p style="color: #666;">暂无结构化数据</p>';
  605. }
  606. // 流式完成
  607. function handleStreamComplete() {
  608. stopStreaming();
  609. updateStatus('completed', '生成完成');
  610. }
  611. // 停止流式传输
  612. function stopStreaming() {
  613. isStreaming = false;
  614. submitBtn.disabled = false;
  615. stopBtn.style.display = 'none';
  616. stopTimer();
  617. }
  618. // 重置输出
  619. function resetOutput() {
  620. reasoningContent.textContent = '';
  621. contentOutput.textContent = '';
  622. scriptPreview.innerHTML = '';
  623. resultBox.style.display = 'none';
  624. reasoningBox.style.display = 'none';
  625. charCount = 0;
  626. updateCharCount();
  627. tokenUsageEl.textContent = '-';
  628. }
  629. // 更新状态
  630. function updateStatus(type, text) {
  631. statusBadge.className = 'status-badge status-' + type;
  632. statusBadge.textContent = text;
  633. }
  634. // 更新字符计数
  635. function updateCharCount() {
  636. charCountEl.textContent = charCount.toLocaleString();
  637. }
  638. // 开始计时器
  639. function startTimer() {
  640. timerInterval = setInterval(() => {
  641. const elapsed = Math.floor((Date.now() - startTime) / 1000);
  642. elapsedTimeEl.textContent = elapsed + 's';
  643. }, 1000);
  644. }
  645. // 停止计时器
  646. function stopTimer() {
  647. if (timerInterval) {
  648. clearInterval(timerInterval);
  649. timerInterval = null;
  650. }
  651. }
  652. // HTML 转义
  653. function escapeHtml(text) {
  654. const div = document.createElement('div');
  655. div.textContent = text;
  656. return div.innerHTML;
  657. }
  658. </script>
  659. </body>
  660. </html>