vue3 + thinkphp 接入 七牛云 DeepSeek-R1/V3 流式调用和非流式调用

news2025/2/21 7:26:19

如何获取七牛云 Token API 密钥

https://eastern-squash-d44.notion.site/Token-API-1932c3f43aee80fa8bfafeb25f1163d8

后端

// 七牛云 DeepSeek API 地址
    private $deepseekUrl = 'https://api.qnaigc.com/v1/chat/completions';
    private $deepseekKey = '秘钥';
    
    // 流式调用
    public function qnDSchat()
    {
        // 禁用所有缓冲
        while (ob_get_level()) ob_end_clean();
    
        // 设置流式响应头(必须最先执行)
        header('Content-Type: text/event-stream');
        header('Cache-Control: no-cache, must-revalidate');
        header('X-Accel-Buffering: no'); // 禁用Nginx缓冲
        header('Access-Control-Allow-Origin: *');
    
        // 获取用户输入
        $userMessage = input('get.content');
    
        // 构造API请求数据
        $data = [
            'model' => 'deepseek-v3', // 支持模型:"deepseek-r1"和"deepseek-v3"
            'messages' => [['role' => 'user', 'content' => $userMessage]],
            'stream' => true, // 启用流式响应
            'temperature' => 0.7
        ];
    
        // 初始化 cURL
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->deepseekUrl,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->deepseekKey,
                'Content-Type: application/json',
                'Accept: text/event-stream'
            ],
            CURLOPT_WRITEFUNCTION => function($ch, $data) {
                // 解析七牛云返回的数据结构
                $lines = explode("\n", $data);
                foreach ($lines as $line) {
                    if (strpos($line, 'data: ') === 0) {
                        $payload = json_decode(substr($line, 6), true);
                        $content = $payload['choices'][0]['delta']['content'] ?? '';
                        
                        // 按SSE格式输出
                        echo "data: " . json_encode([
                            'content' => $content,
                            'finish_reason' => $payload['choices'][0]['finish_reason'] ?? null
                        ]) . "\n\n";
                        
                        ob_flush();
                        flush();
                    }
                }
                return strlen($data);
            },
            CURLOPT_RETURNTRANSFER => false,
            CURLOPT_TIMEOUT => 120
        ]);
    
        // 执行请求
        curl_exec($ch);
        curl_close($ch);
        exit();
    }
    
    

    // 非流式调用
    public function qnDSchat2()
    {
        $userMessage = input('post.content');
    
        // 构造API请求数据
        $data = [
            'model' => 'deepseek-v3', // 支持模型:"deepseek-r1"和"deepseek-v3"
            'messages' => [['role' => 'user', 'content' => $userMessage]],
            'temperature' => 0.7
        ];
    
        // 发起API请求
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->deepseekUrl,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->deepseekKey,
                'Content-Type: application/json'
            ],
            CURLOPT_RETURNTRANSFER => true, // 获取返回结果
            CURLOPT_TIMEOUT => 120
        ]);
    
        // 执行请求并获取返回数据
        $response = curl_exec($ch);
        curl_close($ch);
    
        // 解析API返回结果
        $responseData = json_decode($response, true);
    
        // 根据实际的API响应格式返回数据
        return json([
            'content' => $responseData['choices'][0]['message']['content'] ?? '没有返回内容',
            'finish_reason' => $responseData['choices'][0]['finish_reason'] ?? null
        ]);
    }

前端

npm i markdown-it github-markdown-css
<template>
  <div class="chat-container">
    <div class="messages" ref="messagesContainer">
      <div class="default-questions">
        <div v-for="(question, index) in defaultQuestions" :key="index" @click="handleQuestionClick(question)"
          class="default-question">
          {{ question }}
        </div>
      </div>
      <div v-for="(message, index) in messages" :key="index" class="message"
        :class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'assistant' }">
        <div class="message-content">
          <!-- <span v-if="message.role === 'assistant' && message.isStreaming"></span> -->
          <div v-if="message.role === 'assistant'" v-html="message.content" class="markdown-body"></div>
          <div v-if="message.role === 'user'" v-text="message.content"></div>
        </div>
      </div>
      <div v-if="isLoading" class="orbit-spinner">
        <div class="orbit"></div>
        <div class="orbit"></div>
        <div class="orbit"></div>
      </div>
    </div>

    <div class="input-area">
      <textarea v-model="inputText" maxlength="9999" ref="inputRef"
        @keydown.enter.exact.prevent="sendMessage(inputText.trim())" placeholder="输入你的问题..."
        :disabled="isLoading"></textarea>
      <div class="input-icons">
        <button @click="sendMessage(inputText.trim())" :disabled="isLoading || !inputText.trim()" class="send-button">
          {{ isLoading ? '生成中...' : '发送' }}
        </button>
        <button @click="stopMessage" :disabled="!isLoading" class="stop-button">
          停止
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, Ref, onMounted, onBeforeUnmount } from 'vue'
import MarkdownIt from 'markdown-it'
import 'github-markdown-css'
// import { marked } from 'marked';

interface ChatMessage {
  role: 'user' | 'assistant'
  content: string
  isStreaming?: boolean
}

const eventSource: Ref = ref(null)
const messages = ref<ChatMessage[]>([])
const inputText = ref('')
const isLoading = ref(false)
const messagesContainer = ref<HTMLElement | null>(null)
const inputRef: Ref = ref(null)
const stopReceived: Ref = ref(true)

let aiMessage: ChatMessage = {
  role: 'assistant',
  content: '',
  isStreaming: true
};

const defaultQuestions = ref([
  "中医有哪些治疗方法?",
  "中医有哪些经典著作?",
  "中医有哪些传统方剂?",
  "中医有哪些养生方法?",
])

onMounted(() => {
  setTimeout(() => {
    inputRef.value?.focus()
  }, 1000)
})

onBeforeUnmount(() => {
  stopMessage();
});

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const stopMessage = () => {
  stopReceived.value = true
  if (eventSource.value) {
    eventSource.value.close();
  }
}

// 流式接收处理
const processStreamResponse = async (userMessage: any) => {
  aiMessage = {
    role: 'assistant',
    content: '',
    isStreaming: true
  };
  stopReceived.value = false;
  messages.value.push(aiMessage);
  eventSource.value = new EventSource(`https://api.ecom20200909.com/Other/qnDSchat?content=${encodeURIComponent(userMessage)}`);
  let buffer = '';
  let index = 0;
  const md = new MarkdownIt();
  const typeWriter = () => {
    if (stopReceived.value) {
      // 如果接收数据完成,则不用打字机形式一点点显示,而是把剩余数据全部显示完
      aiMessage.content = md.render(buffer); // 渲染剩余的所有内容
      // aiMessage.content = marked(buffer);
      aiMessage.isStreaming = false;
      messages.value[messages.value.length - 1] = { ...aiMessage };
      isLoading.value = false;
      nextTick(() => {
        inputRef.value?.focus();
      });
      scrollToBottom();
      return
    }
    // 确保不会超出buffer的长度
    const toRenderLength = Math.min(index + 1, buffer.length);
    if (index < buffer.length) {
      aiMessage.content = md.render(buffer.substring(0, toRenderLength));
      // aiMessage.content = marked(buffer.substring(0, toRenderLength));
      messages.value[messages.value.length - 1] = { ...aiMessage };
      index = toRenderLength; // 更新index为实际处理的长度
      setTimeout(typeWriter, 30); // 控制打字速度,30ms显示最多1个字符
      scrollToBottom()
    } else {
      // 超过几秒没有新数据,重新检查index
      setTimeout(() => {
        if (!stopReceived.value || index < buffer.length) {
          typeWriter(); // 如果还没有收到停止信号并且还有未处理的数据,则继续处理
        } else {
          aiMessage.isStreaming = false;
          messages.value[messages.value.length - 1] = { ...aiMessage };
          isLoading.value = false;
          nextTick(() => {
            inputRef.value?.focus();
          });
          scrollToBottom();
        }
      }, 2000);
    }
  };
  eventSource.value.onmessage = (e: MessageEvent) => {
    try {
      const data = JSON.parse(e.data);
      const newContent = data.choices[0].delta.content;
      if (newContent) {
        buffer += newContent; // 将新内容添加到缓冲区
        if (index === 0) {
          typeWriter();
        }
      }
      if (data.choices[0].finish_reason === 'stop') {
        stopReceived.value = true;
        eventSource.value.close();
      }
    } catch (error) {
      console.error('Parse error:', error);
    }
  };
  eventSource.value.onerror = (e: Event) => {
    console.error('EventSource failed:', e);
    isLoading.value = false;
    aiMessage.content = md.render(buffer) + '\n[模型服务过载,请稍后再试.]';
    // aiMessage.content = marked(buffer) + '\n[模型服务过载,请稍后再试.]';
    aiMessage.isStreaming = false;
    messages.value[messages.value.length - 1] = { ...aiMessage };
    scrollToBottom()
    eventSource.value.close();
  };
};

// 流式调用
const sendMessage = async (question?: any) => {
  let userMessage = question || inputText.value.trim();
  if (!userMessage || isLoading.value) return;
  inputText.value = '';
  messages.value.push({
    role: 'user',
    content: userMessage
  });
  isLoading.value = true;
  scrollToBottom();
  try {
    await processStreamResponse(userMessage);
  } catch (error) {
    console.error('Error:', error);
    messages.value.push({
      role: 'assistant',
      content: '⚠️ 请求失败,请稍后再试'
    });
    isLoading.value = false;
    nextTick(() => {
      inputRef.value?.focus();
    });
  } finally {
    scrollToBottom();
  }
};

const handleQuestionClick = (question: string) => {
  sendMessage(question);
}

// 非流式调用
// const sendMessage = async () => {
//   if (!inputText.value.trim() || isLoading.value) return

//   const userMessage = inputText.value.trim()
//   inputText.value = ''

//   // 添加用户消息
//   messages.value.push({
//     role: 'user',
//     content: userMessage
//   })

//   isLoading.value = true
//   scrollToBottom()

//   try {
//     // 调用后端接口
//     const response = await qnDeepseekChat(userMessage)

//     // 解析 AI 的回复并添加到消息中
//     const md = new MarkdownIt();
//     const markdownContent = response.content || '没有返回内容';
//     const htmlContent = md.render(markdownContent);

//     messages.value.push({
//       role: 'assistant',
//       content: htmlContent
//     })
//   } catch (error) {
//     messages.value.push({
//       role: 'assistant',
//       content: '⚠️ 请求失败,请稍后再试'
//     })
//   } finally {
//     isLoading.value = false
//     nextTick(() => {
//       inputRef.value?.focus()
//     })
//     scrollToBottom()
//   }
// }

</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f5f5;
}

.message {
  margin-bottom: 20px;
}

.message-content {
  max-width: 100%;
  padding: 12px 20px;
  border-radius: 12px;
  display: inline-block;
  position: relative;
  font-size: 16px;
}

.user-message {
  text-align: right;
}

.user-message .message-content {
  background: #42b983;
  color: white;
  margin-left: auto;
}

.ai-message .message-content {
  background: white;
  border: 1px solid #ddd;
}

.input-area {
  padding: 12px 20px;
  background: #f1f1f1;
  border-top: 1px solid #ddd;
  display: flex;
  gap: 10px;
  align-items: center;
  min-height: 100px;
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  height: 100%;
  max-height: 180px;
  background-color: #f1f1f1;
  font-size: 14px;
}

textarea:focus {
  outline: none;
  border: 1px solid #ddd;
}

.input-icons {
  display: flex;
  align-items: center;
  flex-direction: column;
}

.send-button {
  padding: 8px 16px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: opacity 0.2s;
  font-size: 14px;
}

.send-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.stop-button {
  padding: 8px 16px;
  background: #b94a42;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: opacity 0.2s;
  font-size: 14px;
  margin-top: 5px;
}

.stop-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.default-questions {
  padding: 10px;
  margin-bottom: 10px;
  background-color: #f0f0f0;
  border-radius: 8px;
}

.default-question {
  padding: 8px;
  margin: 4px;
  cursor: pointer;
  background-color: #fff;
  border-radius: 5px;
  transition: background-color .3s ease;
}

.default-question:hover {
  background-color: #e0e0e0;
}

.orbit-spinner,
.orbit-spinner * {
  box-sizing: border-box;
}

.orbit-spinner {
  height: 55px;
  width: 55px;
  border-radius: 50%;
  perspective: 800px;
}

.orbit-spinner .orbit {
  position: absolute;
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.orbit-spinner .orbit:nth-child(1) {
  left: 0%;
  top: 0%;
  animation: orbit-spinner-orbit-one-animation 1200ms linear infinite;
  border-bottom: 3px solid #ff1d5e;
}

.orbit-spinner .orbit:nth-child(2) {
  right: 0%;
  top: 0%;
  animation: orbit-spinner-orbit-two-animation 1200ms linear infinite;
  border-right: 3px solid #ff1d5e;
}

.orbit-spinner .orbit:nth-child(3) {
  right: 0%;
  bottom: 0%;
  animation: orbit-spinner-orbit-three-animation 1200ms linear infinite;
  border-top: 3px solid #ff1d5e;
}

@keyframes orbit-spinner-orbit-one-animation {
  0% {
    transform: rotateX(35deg) rotateY(-45deg) rotateZ(0deg);
  }

  100% {
    transform: rotateX(35deg) rotateY(-45deg) rotateZ(360deg);
  }
}

@keyframes orbit-spinner-orbit-two-animation {
  0% {
    transform: rotateX(50deg) rotateY(10deg) rotateZ(0deg);
  }

  100% {
    transform: rotateX(50deg) rotateY(10deg) rotateZ(360deg);
  }
}

@keyframes orbit-spinner-orbit-three-animation {
  0% {
    transform: rotateX(35deg) rotateY(55deg) rotateZ(0deg);
  }

  100% {
    transform: rotateX(35deg) rotateY(55deg) rotateZ(360deg);
  }
}

::v-deep .markdown-body h1,
::v-deep .markdown-body h2,
::v-deep .markdown-body h3,
::v-deep .markdown-body h4,
::v-deep .markdown-body h5,
::v-deep .markdown-body h6 {
  margin: 0 !important;
}

::v-deep .markdown-body p,
::v-deep .markdown-body blockquote,
::v-deep .markdown-body ul,
::v-deep .markdown-body ol,
::v-deep .markdown-body dl,
::v-deep .markdown-body table,
::v-deep .markdown-body pre,
::v-deep .markdown-body details {
  margin: 0 !important;
}
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2300817.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Rook-ceph(1.92最新版)

安装前准备 #确认安装lvm2 yum install lvm2 -y #启用rbd模块 modprobe rbd cat > /etc/rc.sysinit << EOF #!/bin/bash for file in /etc/sysconfig/modules/*.modules do[ -x \$file ] && \$file done EOF cat > /etc/sysconfig/modules/rbd.modules &l…

第2章 信息技术发展(一)

2.1 信息技术及其发展 2.1.1 计算机软硬件 计算机硬件(Computer Hardware)是指计算机系统中由电子、机械和光电元件等组成的各种物理装置的总称。 计算机软件 (Computer Software)是指计算机系统中的程序及其文档&#xff0c;程序是计算任务的处理对象和处理规则的描述; 文档…

【网络基本知识--2】

网络基本知识--2 1.主机A和主机B通过三次握手TCP连接&#xff0c;过程是&#xff1a; TCP三次握手连接过程如下&#xff1a; 1.客户端发送SYN(SEQx)报文发送给服务器端&#xff0c;进入SYN_SEND状态&#xff1b; 2.服务器端收到SYN报文&#xff0c;回应一个SYN(SEQy)ACK(ACKx1)…

摄影——曝光三要素

曝光三要素 光圈&#xff08;F&#xff09;&#xff1a;控制进光量的装置快门&#xff08;1/X&#xff09;&#xff1a;接受光线的时间感光度&#xff08;ISO&#xff09;&#xff1a;感光器件对光线的敏感程度 一、快门&#xff08;1/X&#xff09; 静物 1/125 动物 1/500 …

DeepSeek-R1论文阅读及蒸馏模型部署

DeepSeek-R1论文阅读及蒸馏模型部署 文章目录 DeepSeek-R1论文阅读及蒸馏模型部署摘要Abstract一、DeepSeek-R1论文1. 论文摘要2. 引言3. DeepSeek-R1-Zero的方法3.1 强化学习算法3.2 奖励建模3.3 训练模版3.4 DeepSeek-R1-Zero的性能、自进化过程和顿悟时刻 4. DeepSeek-R1&am…

Python的那些事第二十五篇:高效Web开发与扩展应用实践FastAPI

FastAPI:高效Web开发与扩展应用实践 摘要 FastAPI 是一种基于 Python 的现代 Web 框架,以其高性能、自动文档生成、数据验证和异步支持等特性受到开发者的青睐。本文首先介绍了 FastAPI 的核心特性及其开发流程,然后通过实际案例探讨了其在异步编程、微服务架构、WebSocket…

情书网源码 情书大全帝国cms7.5模板

源码介绍 帝国cms7.5仿《情书网》模板源码&#xff0c;同步生成带手机站带采集。适合改改做文学类的网站。 效果预览 源码获取 情书网源码 情书大全帝国cms7.5模板

深入解析iOS视频录制(二):自定义UI的实现

深入解析 iOS 视频录制&#xff08;一&#xff09;&#xff1a;录制管理核心MWRecordingController 类的设计与实现 深入解析iOS视频录制&#xff08;二&#xff09;&#xff1a;自定义UI的实现​​​​​​​ 深入解析 iOS 视频录制&#xff08;三&#xff09;&#xff1a;完…

Deepseek 万能提问公式:高效获取精准答案

### **Deepseek 万能提问公式&#xff1a;高效获取精准答案** 在使用 Deepseek 或其他 AI 工具时&#xff0c;提问的质量直接决定了答案的精准度和实用性。以下是一个万能的提问公式回答&#xff1a; --- ### **1. 明确背景&#xff08;Context&#xff09;** - **作用**…

DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地

对于个人开发者或尝鲜者而言&#xff0c;本地想要部署 DeepSeek 有很多种方案&#xff0c;但是一旦涉及到企业级部署&#xff0c;则步骤将会繁琐很多。 比如我们的第一步就需要先根据实际业务场景评估出我们到底需要部署什么规格的模型&#xff0c;以及我们所要部署的模型&…

算法——舞蹈链算法

一&#xff0c;基本概念 算法简介 舞蹈链算法&#xff08;Dancing Links&#xff0c;简称 DLX&#xff09;是一种高效解决精确覆盖问题的算法&#xff0c;实际上是一种数据结构&#xff0c;可以用来实现 X算法&#xff0c;以解决精确覆盖问题。由高德纳&#xff08;Donald E.…

WPF8-常用控件

目录 写在前面&#xff1a;1. 按钮控件1.1. Button 按钮1.2. RepeatButton:长按按钮1.3. RadioButton:单选按钮 2. 数据显示控件2.1. TextBlock&#xff1a;只读文本控件2.2. Lable&#xff1a;标签 显示文本控件2.3. ListBox&#xff1a;显示可选择项的列表2.4. DataGrid&…

代码随想录刷题day24|(字符串篇)151.反转字符串中的单词

一、题目思路 1.快慢指针移除字符串首尾以及单词中的多余空格 类似前面数组篇--移除元素代码随想录刷题day02|&#xff08;数组篇&#xff09;27.移除元素、26.删除有序数组中的重复项_代码随想录网站-CSDN博客 快指针fast遍历整个字符串&#xff0c;慢指针slow指向新字符串…

VMware按照的MacOS升级后无法联网

背景 3年前公司使用Flutter开发了一款app&#xff0c;现在app有微小改动需要重新发布到AppStore 问题 问题是原来的Vmware搭建的开发环境发布App失败了 提示&#xff1a;App需要使用xcode15IOS 17 SDK重新构建&#xff0c;这样的话MacOS至少需要升级到13.5 Xcode - 支持 - Ap…

DeepSeek V3和R1

DeepSeek V3 和 R1 是深度求索&#xff08;DeepSeek&#xff09;推出的两款大模型&#xff0c;基于混合专家架构&#xff08;MoE&#xff09;&#xff0c;但在设计目标、训练方法和应用场景上存在显著差异。以下是两者的详细对比与补充内容&#xff1a; DeepSeek V3和R1 一、模…

【操作系统】深入理解Linux物理内存

物理内存的组织结构 我们平时所称的内存也叫随机访问存储器也叫 RAM 。RAM 分为两类&#xff1a; 一类是静态 RAM&#xff08; SRAM &#xff09;&#xff0c;这类 SRAM 用于 CPU 高速缓存 L1Cache&#xff0c;L2Cache&#xff0c;L3Cache。其特点是访问速度快&#xff0c;访…

记一次一波三折的众测SRC经历

视频教程和更多福利在我主页简介或专栏里 &#xff08;不懂都可以来问我 专栏找我哦&#xff09; 目录&#xff1a; 前言 波折一&#xff1a;RCE漏洞利用失败 波折二&#xff1a;SQL时间盲注 波折三&#xff1a;寻找管理后台 总结 前言 先谈个人SRC心得体会吧&#xff0c;我虽…

POI优化Excel录入

57000单词原始录入时间258S 核心代码: List<Word> wordBookList ExcelUtil.getReader(file.getInputStream()).readAll(Word.class);if (!CollectionUtil.isEmpty(wordBookList)) {for (Word word : wordBookList) {//逐条向数据库中插入单词wordMapper.insert(word);}…

HarmonyOS进程通信及原理

大家好&#xff0c;我是学徒小z&#xff0c;最近在研究鸿蒙中一些偏底层原理的内容&#xff0c;今天分析进程通信给大家&#xff0c;请用餐&#x1f60a; 文章目录 进程间通信1. 通过公共事件&#xff08;ohos.commonEventManager&#xff09;公共事件的底层原理 2. IPC Kit能…

DeepSeek核心算法解析:如何打造比肩ChatGPT的国产大模型

注&#xff1a;此文章内容均节选自充电了么创始人&#xff0c;CEO兼CTO陈敬雷老师的新书《自然语言处理原理与实战》&#xff08;人工智能科学与技术丛书&#xff09;【陈敬雷编著】【清华大学出版社】 文章目录 DeepSeek大模型技术系列一DeepSeek核心算法解析&#xff1a;如何…