完善机器人:让 DeepSeek 生成 API 接口,并在网页上调用

news/2025/3/15 17:54:17/

在上一篇文章中,我们使用 DeepSeek 生成了一个 Java 版的 AI 问答机器人,并在终端与 AI 进行交互。但如果想要让更多人使用它,我们需要 搭建一个 API 接口,让网页也能调用 AI 机器人。今天,我们就来学习如何用 AI 生成 Spring Boot API,并在网页中调用它!


一、用 DeepSeek 生成 Spring Boot API

💬 示例指令

“请用 Java + Spring Boot 编写一个简单的 API,它可以接收用户输入的问题,并调用 DeepSeek API 返回 AI 生成的回答。”

DeepSeek 可能会返回如下代码:

import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;
import java.util.List;@RestController
@RequestMapping("/api/chat")
public class ChatController {private static final String API_URL = "http://localhost:11434/v1/chat/completions";private static final OkHttpClient client = new OkHttpClient();@PostMappingpublic String chat(@org.springframework.web.bind.annotation.RequestBody ChatRequest request) {return getAIResponse(request.getMessage());}// 调用 DeepSeek APIpublic static String getAIResponse(String question) {// 构造 JSON 请求体String json = String.format("{"+ "\"model\": \"deepseek-r1:1.5b\","+ "\"messages\": [{\"role\": \"user\", \"content\": \"%s\"}]"+ "}", question);// 创建请求体RequestBody body = RequestBody.create(json, MediaType.parse("application/json"));// 构建 HTTP 请求Request request = new Request.Builder().url(API_URL).post(body).build();// 发送请求并获取响应try (Response response = client.newCall(request).execute()) {if (response.isSuccessful() && response.body() != null) {Gson gson = new Gson();ChatBotDeepSeek.DeepSeekResponse deepSeekResponse = gson.fromJson(response.body().string(), ChatBotDeepSeek.DeepSeekResponse.class);return deepSeekResponse.getChoices().get(0).getMessage().getContent();}return "AI 机器人出错了,请稍后再试!";} catch (IOException e) {return "AI 机器人出错了,请稍后再试!";}}@Data@NoArgsConstructor@AllArgsConstructorpublic static class DeepSeekResponse {private String id;private String object;private long created;private String model;private String systemFingerprint;private List<ChatBotDeepSeek.DeepSeekResponse.Choice> choices;private ChatBotDeepSeek.DeepSeekResponse.Usage usage;@Data@NoArgsConstructor@AllArgsConstructorpublic static class Choice {private int index;private ChatBotDeepSeek.DeepSeekResponse.Message message;private String finishReason;}@Data@NoArgsConstructor@AllArgsConstructorpublic static class Message {private String role;private String content;}@Data@NoArgsConstructor@AllArgsConstructorpublic static class Usage {private int promptTokens;private int completionTokens;private int totalTokens;}}
}// 数据传输对象(DTO)
class ChatRequest {private String message;public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}
}

🔹 代码解析: 
@RestController 创建一个 API 控制器
@RequestMapping("/api/chat") 定义 API 访问路径
@PostMapping 处理 POST 请求,接收用户输入
OkHttp 发送 HTTP 请求到 DeepSeek API ,获取 AI 生成的回答


二、运行 Spring Boot 并测试 API

1️⃣ 添加 Maven 依赖

<!-- 如果你没加 OkHttp -->
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.12.0</version>
</dependency><!-- 如果你没加 web-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

2️⃣ 运行 Spring Boot 项目
在 IDE 里启动 ChatController,或者在命令行执行:

mvn spring-boot:run

3️⃣ 测试 API(用 Postman 或 curl):

curl -X POST http://localhost:8080/api/chat -H "Content-Type: application/json" -d '{"message":"你好,AI"}'

如果一切正常,你会看到 AI 返回的回答。🎉


三、前端调用 API,实现网页对话

我们已经有了后端 API,接下来创建一个 简单的 HTML + JavaScript 网页,让用户能在网页上和 AI 机器人聊天!

1. 让 DeepSeek 生成 HTML 页面

💬 示例指令

“请用 HTML + JavaScript 创建一个简单的聊天页面,它可以调用后端 API(http://localhost:8080/api/chat),并显示 AI 生成的回答。”

DeepSeek 可能会返回如下代码:

<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>AI 机器人聊天</title><style>body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }#chatBox { width: 80%; height: 300px; border: 1px solid #ddd; overflow-y: auto; padding: 10px; }#userInput { width: 70%; padding: 10px; }button { padding: 10px 20px; margin-left: 10px; }</style>
</head>
<body><h2>AI 机器人聊天</h2><div id="chatBox"></div><input type="text" id="userInput" placeholder="输入你的问题..." /><button onclick="sendMessage()">发送</button><script>async function sendMessage() {let userInput = document.getElementById("userInput").value;if (!userInput) return;let chatBox = document.getElementById("chatBox");chatBox.innerHTML += "<p><strong>你:</strong> " + userInput + "</p>";let response = await fetch("http://localhost:8080/api/chat", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ message: userInput })});let result = await response.text();chatBox.innerHTML += "<p><strong>AI:</strong> " + result + "</p>";document.getElementById("userInput").value = "";}</script></body>
</html>

🔹 代码解析
input 输入框,用户输入问题
button 发送按钮,触发 sendMessage()
fetch() 发送 API 请求到后端
chatBox 显示 AI 机器人回复


四、本地运行完整 AI 问答网站

1. 启动后端

  • 确保 Spring Boot APIhttp://localhost:8080/api/chat 运行

2. 启动前端

  • 保存 HTML 代码为 index.html
  • 在浏览器打开 index.html
  • 你就可以 像 DeepSeek 一样和 AI 机器人对话了! 🚀


五、下一步:使用 Vue + Element UI 提升交互体验

目前,我们的网页虽然能用,但 交互体验很基础。下一篇文章,我们将用 Vue + Element UI 搭建 更美观的 AI 交互页面,让你的 AI 机器人更炫酷!💡


http://www.ppmy.cn/news/1579364.html

相关文章

win10 win+shift+s 无法立即连续截图 第二次截图需要等很久

意外的win10做了一次更新&#xff0c;然后系统的截图工具就出现了这个问题。 windows的截图功能&#xff0c;是由 Microsoft Text Input Application 来维护的&#xff0c;是 Windows 系统内置的输入法管理程序&#xff0c;负责协调输入法与系统之间的交互‌ ScreenClippingHo…

探索HTML5 Canvas:创造动态与交互性网页内容的强大工具

探索HTML5 Canvas&#xff1a;创造动态与交互性网页内容的强大工具 引言 在HTML5的众多新特性中&#xff0c;Canvas无疑是最引人注目的元素之一。它为网页设计师和开发者提供了一个通过JavaScript和HTML直接在网页上绘制图形、图像以及进行动画处理的画布。Canvas的灵活性和强…

【JavaScript 】1. 什么是 Node.js?(JavaScript 服务器环境)

1. 什么是 Node.js&#xff1f;&#xff08;JavaScript 服务器环境&#xff09; 1.1 Node.js 定义 Node.js 是一个 基于 Chrome V8 引擎的 JavaScript 运行环境&#xff0c;用于运行 JavaScript 代码&#xff0c;特别适合 服务器端开发。 特点&#xff1a; ✅ 非阻塞&#x…

安卓编译问题

看下这个是gradle里面配置的minsdk 版本有问题&#xff0c;需要从34改成30&#xff0c;这里面特意还指出了是哪个lib 能引用到&#xff0c;但是一直有红线说依赖有问题&#xff0c;是因为a用的implementation 一来的b, b又依赖了c 这个类在c里面&#xff0c;a模块引用不到 因为…

AI数字人源码开发---SaaS化源码部署+PC+小程序一体化

#数字人#数字人分身#123数字人#数字人分身源码部署搭建 AI数字人源码开发步骤 确定功能需求&#xff1a;首先确定需要实现的功能和特性&#xff0c;包括语音识别、自然语言处理、人脸识别等功能。这些功能将构成AI数字人的核心功能。 开发AI数字人源码&#xff1a;使用合适的…

STM32U575RIT6单片机(三)

作业1&#xff1a;使用中断控制光电开关打开蜂鸣器 volatile int flag0; //重写中断回调函数 void HAL_GPIO_EXTI_Rising_Callback(uint16_t GPIO_Pin) //void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin) {if(GPIO_PinPhotoElectric_Pin){flag1;} } void HAL_GPIO_EXTI_Fall…

【贪心算法4】

力扣452.用最少数量的剪引爆气球 链接: link 思路 这道题的第一想法就是如果气球重叠得越多那么用箭越少&#xff0c;所以先将气球按照开始坐标从小到大排序&#xff0c;遇到有重叠的气球&#xff0c;在重叠区域右边界最小值之前的区域一定需要一支箭&#xff0c;这道题有两…

Docker配置代理,以保证可以快速拉取镜像

序言 本来不想写了&#xff0c;然后记笔记了&#xff0c;但是今天遇到这个问题了再一次&#xff0c;还是写一写吧&#xff0c;加深一下印象 因为Docker被墙了&#xff0c;所以拉取Docker镜像的时候&#xff0c;需要通过代理的方式 xxxxxxxxxx,此处省略十几个字&#xff0c;然…