当前位置: 首页 > news >正文

博客网站(springboot)整合deepseek实现在线调用

🎉🎉🎉🎉🎉🎉
欢迎访问的个人博客:https://swzbk.site/,加好友,拉你入福利群
🎉🎉🎉🎉🎉🎉

1、deepseek介绍

DeepSeek(深度求索)是一家成立于2023年7月的中国人工智能公司,由量化资管巨头幻方量化创立,专注于开发高性能大语言模型(LLM)及相关技术。今年年初以其模型高性能能力而备受关注,目前国内企业正在广泛接入使用。

2、vue前端界面

  • 加了一个nav页签:深度探索
    在这里插入图片描述

  • 页面代码如下:

<template>
  <div class="chat-wrapper">
    <div class="chat-container">
      <div class="chat-header">
        <h2>DeepSeek 对话</h2>
      </div>
      <div class="chat-messages" ref="chatMessages">
        <div v-for="(message, index) in chatMessages" :key="index" :class="['message', message.includes('你:') ? 'user-message' : 'bot-message']">
          <span>{{ message }}</span>
        </div>
      </div>
      <div class="input-container">
        <input v-model="userInput" type="text" placeholder="输入你的问题" @keydown.enter="sendMessage">
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userInput: '',
      chatMessages: []
    };
  },
  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '') return;

      // 显示用户消息
      this.chatMessages.push(`你: ${this.userInput}`);

      try {
       //这里后面换成服务器ip
        const response = await fetch('http://localhost:8090/deepseek', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ prompt: this.userInput })
        });

        const data = await response.json();
        const answer = data.answer;

        // 显示 DeepSeek 的回答
        this.chatMessages.push(`DeepSeek: ${answer}`);
      } catch (error) {
        console.error('请求出错:', error);
        this.chatMessages.push('请求出错,请稍后再试');
      }

      // 清空输入框
      this.userInput = '';
      this.$nextTick(() => {
        this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
      });
    }
  }
};
</script>

<style scoped>
.chat-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f4f4f9;
}

.chat-container {
  width: 80%;
  height: 80vh;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.chat-header {
  background-color: #007bff;
  color: #fff;
  padding: 15px 20px;
  text-align: center;
  flex-shrink: 0;
}

.chat-header h2 {
  margin: 0;
  font-size: 1.3rem;
}

.chat-messages {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.message {
  padding: 10px 15px;
  border-radius: 8px;
  margin-bottom: 10px;
  max-width: 80%;
  word-wrap: break-word;
}

.user-message {
  background-color: #e0f7fa;
  align-self: flex-end;
  color: #212121;
}

.bot-message {
  background-color: #f1f8e9;
  align-self: flex-start;
  color: #212121;
}

.input-container {
  display: flex;
  padding: 15px 20px;
  border-top: 1px solid #e0e0e0;
  flex-shrink: 0;
}

.input-container input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 6px;
  margin-right: 10px;
  font-size: 1rem;
}

.input-container button {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s ease;
}

.input-container button:hover {
  background-color: #0056b3;
}
</style>

3、deepseek api申请

deepseek api
申请完之后,需要充值使用,有的新人会有免费使用次数,我这里充值了5米,测试用够了。

4、springboot接口增加

  • DeepSeekController接口
package top.naccl.controller;
import com.fasterxml.jackson.databind.JsonNode;
import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import top.naccl.model.dto.DeepSeekRequest;
import top.naccl.model.dto.DeepSeekResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@RestController
public class DeepseekController {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    //换成自己的deepseek api
    private static final String DEEPSEEK_API_KEY = "sk-xxxx";
    private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions";

    @PostMapping("/deepseek")
    public DeepSeekResponse handleDeepSeekRequest(@RequestBody DeepSeekRequest request) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(100, TimeUnit.SECONDS)  // 增加读取超时时间
                .build();

        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        String json = "{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"user\", \"content\": \"" + request.getPrompt() + "\"}]}";

        // 使用 okhttp3.RequestBody 创建请求体
        okhttp3.RequestBody body = okhttp3.RequestBody.create(JSON, json.getBytes());

        Request apiRequest = new Request.Builder()
                .url(DEEPSEEK_API_URL)
                .post(body)
                .addHeader("Authorization", "Bearer " + DEEPSEEK_API_KEY)
                .addHeader("Content-Type", "application/json")
                .build();

        try (Response response = client.newCall(apiRequest).execute()) {
            if (!response.isSuccessful()) {
                return new DeepSeekResponse("请求失败:" + response.code());
            }

            return handleNormalResponse(response);

        } catch (IOException e) {
            return new DeepSeekResponse("请求异常:" + e.getMessage());
        }
    }

    private DeepSeekResponse handleNormalResponse(Response response) throws IOException {
        try (ResponseBody body = response.body()) {
            if (body == null) {
                return new DeepSeekResponse("空响应");
            }

            String responseData = body.string();
            JsonNode jsonNode = objectMapper.readTree(responseData);
            if (jsonNode.has("choices") && !jsonNode.get("choices").isEmpty()) {
                JsonNode messageNode = jsonNode.get("choices").get(0).get("message");
                if (messageNode != null && messageNode.has("content")) {
                    return new DeepSeekResponse(messageNode.get("content").asText());
                }
            }
            return new DeepSeekResponse("未找到有效回答");
        }
    }


}
  • DeepSeekRequest请求类
package top.naccl.model.dto;

import com.fasterxml.jackson.annotation.JsonProperty;

// 请求类,用于接收前端传来的用户问题
public class DeepSeekRequest {
    @JsonProperty("prompt")
    private String prompt;

    public String getPrompt() {
        return prompt;
    }

    public void setPrompt(String prompt) {
        this.prompt = prompt;
    }
}


  • DeepSeekResponse响应类
package top.naccl.model.dto;

// 响应类,用于返回 DeepSeek 的回答给前端
public class DeepSeekResponse {
    private String answer;

    public DeepSeekResponse(String answer) {
        this.answer = answer;
    }

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }
}

5、pom.xml引入

    <!-- deepseek -->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.11.0</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

6、问题总结

  • 调用比较慢,上面的读取时间需要设置长点
  • 目前不支持记忆问答,每次刷新之前的问答就会清空
  • 目前使用的是非流式响应,具体后面在研究流式响应,据说比较快,所以推荐
  • 测试使用调用api 30次左右,花费0.05
  • 界面还需待优化

🎉🎉🎉🎉🎉🎉
欢迎访问的个人博客:https://swzbk.site/,加好友,拉你入福利群
🎉🎉🎉🎉🎉🎉

相关文章:

  • keil引入头文件报错的问题
  • 代码随想录算法训练营第31天 | 56. 合并区间 738.单调递增的数字 968.监控二叉树
  • 玩转python:通俗易懂掌握高级数据结构-collections模块之ChainMap
  • SpringMVC(四)Restful软件架构风格
  • 吴恩达机器学习笔记复盘(五)均方误差函数
  • 基恩士PLC编程小技巧八:脚本过长如何实现换行及替换
  • 并发编程2
  • 【java】网络编程——IP
  • Vue 中 this 使用指南与注意事项
  • 音视频入门基础:RTP专题(19)——FFmpeg源码中,获取RTP的音频信息的实现(下)
  • 约瑟夫环(1+2)
  • 【JVM】GC 常见问题
  • Python Cookbook-4.3 若列表中某元素存在则返回之
  • 机器学习之特征工程
  • 珠算与珠心算发展简介
  • c语言zixue
  • 并发编程面试题二
  • 从 root 一滴水看 Spring Data JPA 的汪洋大海
  • 前端面试笔试
  • 使用 Nginx 进行前端灰度发布的策略与实践
  • “即买即退”扩容提质,上海静安推出离境退税2.0版新政
  • 人社部:将制定提前领取个人养老金相关办法
  • 阿里千问3系列发布并开源:称成本大幅下降,性能超越DeepSeek-R1
  • 武汉一季度GDP为4759.41亿元,同比增长5.4%
  • 北京动物园:大熊猫“萌兰”没有参加日本大阪世博会的计划
  • 广东雷州农商行董事长、原行长同日被查