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

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

在上一篇文章中,我们使用 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();

    @PostMapping
    public String chat(@org.springframework.web.bind.annotation.RequestBody ChatRequest request) {
        return getAIResponse(request.getMessage());
    }

    // 调用 DeepSeek API
    public 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
    @AllArgsConstructor
    public 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
        @AllArgsConstructor
        public static class Choice {
            private int index;
            private ChatBotDeepSeek.DeepSeekResponse.Message message;
            private String finishReason;
        }

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        public static class Message {
            private String role;
            private String content;
        }

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        public 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.kler.cn/a/585735.html

相关文章:

  • MySQL 的 innodb_buffer_pool_size 参数配置指南
  • [AI QA] strace | 探索 a.out
  • 正则表达式 - 修饰符
  • 书籍品读:我的世界(陈州)
  • C语言实现括号匹配检查及栈的应用详解
  • 【综述】An Introduction to Vision-Language Modeling【二】
  • 【linux驱动开发】创建proc文件系统中的目录和文件实现
  • Python 中 lambda 表达式、推导式和其他函数用法对比
  • QT中读取QSetting文件
  • Ubuntu 访问 Windows 共享文件夹
  • vue2升级Vue3--native、对inheritAttrs作用做以解释、声明的prop属性和未声明prop的属性
  • C语言内容
  • jupyter无法转换为PDF,HTMLnbconvert failed: Pandoc wasn‘t found.
  • 【sql靶场】第11、12关-post提交注入
  • 使用GitHub Actions实现Git推送自动部署到服务器
  • Python实现邮件发送功能,邮箱验证码发送(详细功能实现及环境搭建)
  • 【学习笔记】LLM技术基础
  • C++相关基础概念之入门讲解(上)
  • Qt QML实现弹球消砖块小游戏
  • WPF中查看PDF文件之MoonPdfLib类库