This commit is contained in:
老高 2025-01-24 10:42:30 +08:00
parent 91db015688
commit d05fd60438
6 changed files with 852 additions and 0 deletions

99
pom.xml Normal file
View File

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>sincon.laogao</groupId>
<artifactId>EasyDeepSeek</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>aiDemoApi</name>
<description>aiDemoApi</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 打包格式 -->
<packaging>jar</packaging>
<!-- 打包插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.7.4</version>
<configuration>
<executable>true</executable>
<layout>JAR</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<attach>false</attach>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,13 @@
package sincon.laogao.deepseek;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EasyDeepSeekApplication {
public static void main(String[] args) {
SpringApplication.run(EasyDeepSeekApplication.class, args);
}
}

View File

@ -0,0 +1,18 @@
package sincon.laogao.deepseek.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*") // 允许所有来源生产环境建议指定具体域名
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(3600);
}
}

View File

@ -0,0 +1,85 @@
package sincon.laogao.deepseek.controller;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/ai")
public class easyAiController {
private static final String API_KEY = "sk-2d525ebc32ba41cd8e57064332480226";
private static final String BASE_URL = "https://api.deepseek.com";
private static final OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
@PostMapping("/msg")
public String createEvent(@RequestBody String req) {
String response = "";
try {
response = createChatCompletion(false,req);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
private static String createChatCompletion(boolean streamFlag, String next) throws Exception {
String url = BASE_URL + "/v1/chat/completions";
JSONArray messages = new JSONArray()
.put(new JSONObject().put("role", "system").put("content", ",你是一名我的世界资深技术,你参与过mojang我的世界开发," +
"也自己搭建过我的世界java服务器,同时熟悉所有MineCraft的插件,并能准确的识别报错和提供指导,希望你准确无误的回答我的问题," +
"并且不能回复超过500字"))
// .put(new JSONObject().put("role", "user").put("content", "Hello! How can I assist you today? \uD83D\uDE0A"));
.put(new JSONObject().put("role", "user").put("content", next));
JSONObject jsonBody = new JSONObject()
.put("model", "deepseek-chat")
.put("messages", messages)
.put("stream", streamFlag);
okhttp3.RequestBody body = okhttp3.RequestBody.create(
jsonBody.toString(),
MediaType.get("application/json; charset=utf-8")
);
Request request = new Request.Builder()
.url(url)
.header("Authorization", "Bearer " + API_KEY)
.post(body)
.build();
Response response = client.newCall(request).execute();
if(!streamFlag) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
ResponseBody responseBody = response.body();
if (responseBody != null) {
JSONObject jsonResponse = new JSONObject(responseBody.string());
return jsonResponse.getJSONArray("choices")
.getJSONObject(0)
.getJSONObject("message")
.getString("content");
}
}else{
}
return null;
}
}

View File

@ -0,0 +1,13 @@
package sincon.laogao.deepseek;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class EasyDeepSeekApplicationTests {
@Test
void contextLoads() {
}
}

624
static/index.html Normal file
View File

@ -0,0 +1,624 @@
<!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>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
min-height: 100vh;
background: linear-gradient(45deg, #4158D0, #C850C0, #FFCC70);
background-attachment: fixed;
}
.chat-container {
max-width: 1200px;
margin: 20px auto;
height: calc(100vh - 40px);
display: grid;
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header"
"sidebar main"
"sidebar input";
background: #F5F5F5;
border-radius: 16px;
box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.1);
}
.chat-header {
grid-area: header;
padding: 16px 20px;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
background: #FFFFFF;
border-top-left-radius: 16px;
border-top-right-radius: 16px;
}
.chat-logo {
height: 40px;
width: auto;
}
.chat-sidebar {
grid-area: sidebar;
padding: 20px;
border-right: 1px solid rgba(0, 0, 0, 0.1);
background: #FFFFFF;
overflow-y: auto;
}
.hot-topic {
padding: 12px 16px;
margin-bottom: 12px;
background: #F8F9FA;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
}
.hot-topic:hover {
background: #E9ECEF;
transform: translateX(5px);
}
.hot-topic-title {
font-size: 14px;
color: #333;
margin-bottom: 4px;
font-weight: 500;
}
.hot-topic-desc {
font-size: 12px;
color: #666;
}
.chat-messages {
grid-area: main;
padding: 20px;
overflow-y: auto;
background: #F5F5F5;
}
/* 自定义滚动条样式 */
.chat-messages::-webkit-scrollbar {
width: 6px;
}
.chat-messages::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.1);
}
.chat-messages::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 3px;
}
.message {
display: flex;
margin-bottom: 20px;
padding: 0 20px;
}
/* 用户消息容器 */
.user-message {
flex-direction: row-reverse;
}
/* 头像样式 */
.message-avatar {
width: 40px;
height: 40px;
flex-shrink: 0;
border-radius: 4px;
overflow: hidden;
}
.message-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
/* 消息内容容器 */
.message-content {
position: relative;
padding: 10px 16px;
margin: 0 12px;
font-size: 14px;
line-height: 1.5;
display: inline-block;
max-width: 70%;
word-break: break-word;
}
/* 用户消息样式 */
.user-message .message-content {
background-color: #95EC69;
border-radius: 10px 0 10px 10px;
margin-right: 0;
color: #000;
float: right;
}
/* AI消息样式 */
.ai-message .message-content {
background-color: #fff;
border-radius: 0 10px 10px 10px;
margin-left: 0;
color: #000;
float: left;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}
/* 消息文本样式 */
.message-content p {
margin: 0;
}
.message-content ul {
margin: 8px 0 0 20px;
padding: 0;
}
.message-content li {
margin: 4px 0;
}
/* 清除浮动 */
.message::after {
content: '';
display: table;
clear: both;
}
/* 动画效果 */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.message {
animation: fadeIn 0.3s ease;
}
.chat-input-container {
grid-area: input;
padding: 16px 20px;
background: #FFFFFF;
border-top: 1px solid rgba(0, 0, 0, 0.1);
display: flex;
gap: 12px;
}
.chat-input {
flex: 1;
padding: 12px;
border: 1px solid #E0E0E0;
border-radius: 8px;
resize: none;
min-height: 24px;
max-height: 120px;
font-size: 14px;
background: #FFFFFF;
color: #333;
}
.chat-input::placeholder {
color: rgba(255, 255, 255, 0.6);
}
.chat-input:focus {
outline: none;
border-color: #1890ff;
}
.send-button {
padding: 0 24px;
background: #1890ff;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-size: 14px;
}
.send-button:hover {
background: #40a9ff;
}
@media (max-width: 768px) {
.chat-container {
margin: 0;
height: 100vh;
border-radius: 0;
}
}
/* 加载动画容器 */
.loading-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, 0.9);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
/* 加载动画 */
.loading-spinner {
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid #1890ff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* 淡出动画 */
.fade-out {
animation: fadeOut 0.5s ease forwards;
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; visibility: hidden; }
}
/* 修改输入框提示文字颜色 */
.chat-input::placeholder {
color: #999;
}
/* 添加名称样式 */
.message-name {
font-size: 12px;
margin-bottom: 4px;
color: #666;
}
.ai-message .message-name {
margin-left: 12px;
}
.user-message .message-name {
margin-right: 12px;
text-align: right;
}
/* 登录遮罩层样式 */
.login-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(45deg, #4158D0, #C850C0, #FFCC70);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 2000;
}
.login-container {
background: rgba(255, 255, 255, 0.95);
padding: 30px;
border-radius: 16px;
box-shadow: 0 8px 32px rgba(31, 38, 135, 0.2);
text-align: center;
max-width: 400px;
width: 90%;
}
.login-logo {
width: 200px;
height: auto;
margin-bottom: 30px;
}
.login-input {
width: 100%;
padding: 12px;
margin: 20px 0;
border: 2px solid #E0E0E0;
border-radius: 8px;
font-size: 16px;
outline: none;
transition: border-color 0.3s;
}
.login-input:focus {
border-color: #1890ff;
}
.login-button {
background: #1890ff;
color: white;
border: none;
padding: 12px 30px;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: background 0.3s;
}
.login-button:hover {
background: #40a9ff;
}
.login-error {
color: #ff4d4f;
margin-top: 10px;
font-size: 14px;
display: none;
}
/* 添加淡出动画 */
.fade-out {
animation: fadeOut 0.5s ease forwards;
}
</style>
</head>
<body>
<!-- 登录遮罩层 -->
<div class="login-overlay" id="loginOverlay">
<div class="login-container">
<img src="http://tc.mcshare.cn/LightPicture/2025/01/dfcd0cc85c45a6af.png" alt="Logo" class="login-logo">
<input type="password" class="login-input" id="passwordInput" placeholder="请输入访问密码" autocomplete="off">
<button class="login-button" id="loginButton">进入系统</button>
<div class="login-error" id="loginError">密码错误,请重试</div>
</div>
</div>
<div class="loading-container" id="loadingContainer">
<div class="loading-spinner"></div>
</div>
<div class="chat-container">
<div class="chat-header">
<img src="http://tc.mcshare.cn/LightPicture/2025/01/dfcd0cc85c45a6af.png" alt="Logo" class="chat-logo">
</div>
<div class="chat-sidebar">
<div class="hot-topic">
<div class="hot-topic-title">🔥 cmi插件如何使用</div>
<div class="hot-topic-desc">AI助手教你cmi插件如何使用</div>
</div>
<div class="hot-topic">
<div class="hot-topic-title">📚 ess插件如何使用?</div>
<div class="hot-topic-desc">将教会您如何使用ess插件</div>
</div>
<div class="hot-topic">
<div class="hot-topic-title">💡 什么是VPS</div>
<div class="hot-topic-desc">对VPS进行详解</div>
</div>
<div class="hot-topic">
<div class="hot-topic-title">🌟 如何搭建一个基础服务端?</div>
<div class="hot-topic-desc">告诉你最终结果</div>
</div>
<div class="hot-topic">
<div class="hot-topic-title">🔍 我的世界宝可梦模组攻略?</div>
<div class="hot-topic-desc">我的世界宝可梦科普解读</div>
</div>
</div>
<div class="chat-messages" id="chatMessages">
<div class="message ai-message">
<div class="message-avatar">
<img src="http://tc.mcshare.cn/LightPicture/2025/01/b9243274f819f28b.jpg" alt="AI" style="width: 100%; height: 100%; border-radius: 50%;">
</div>
<div>
<div class="message-name">恭喜智能AI - 征途下士</div>
<div class="message-content">
<p> 您好我是华欣云AI助手。</p>
<p style="margin-top: 8px;">我可以帮您:</p>
<ul style="margin: 8px 0 0 20px;">
<li>解决简单报错</li>
<li>寻找插件资源</li>
<li>提供编程帮助</li>
<li>甚至您可以让我给您进行插件的基础问题解答.</li>
</ul>
<p style="margin-top: 8px;">感谢您对华欣云的支持,祝您生活愉快!</p>
</div>
</div>
</div>
</div>
<form class="chat-input-container" id="chatForm">
<textarea
class="chat-input"
placeholder="请输入您要询问的内容,按回车发送..."
id="messageInput"
></textarea>
<button type="submit" class="send-button">发送</button>
</form>
</div>
<script>
const chatMessages = document.getElementById('chatMessages');
const chatForm = document.getElementById('chatForm');
const messageInput = document.getElementById('messageInput');
// 添加消息到聊天界面
function addMessage(content, isUser = true) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
messageDiv.innerHTML = `
<div class="message-avatar">
${isUser ?
'<img src="https://api.dicebear.com/7.x/avataaars/svg?seed=user" alt="用户" style="width: 100%; height: 100%; border-radius: 50%;">' :
'<img src="http://tc.mcshare.cn/LightPicture/2025/01/b9243274f819f28b.jpg" alt="AI" style="width: 100%; height: 100%; border-radius: 50%;">'
}
</div>
<div>
<div class="message-name">
${isUser ? '恭喜娱乐客户' : '恭喜智能AI - 征途下士'}
</div>
<div class="message-content">
${content}
</div>
</div>
`;
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// 处理表单提交
chatForm.addEventListener('submit', async function(e) {
e.preventDefault();
const message = messageInput.value.trim();
if (!message) return;
// 添加用户消息
addMessage(message, true);
messageInput.value = '';
try {
// 显示加载状态
const loadingMessage = document.createElement('div');
loadingMessage.className = 'message ai-message';
loadingMessage.innerHTML = `
<div class="message-avatar">
<img src="http://tc.mcshare.cn/LightPicture/2025/01/b9243274f819f28b.jpg" alt="AI" style="width: 100%; height: 100%; border-radius: 50%;">
</div>
<div>
<div class="message-name">恭喜智能AI - 征途下士</div>
<div class="message-content">
<p>索引中..</p>
<p>请稍等..</p>
</div>
</div>
`;
chatMessages.appendChild(loadingMessage);
chatMessages.scrollTop = chatMessages.scrollHeight;
// 发起POST请求
const response = await fetch('http://localhost:8080/ai/msg', {
method: 'POST',
headers: {
'Content-Type': 'text/plain', // 设置为纯文本
},
body: message // 直接发送消息文本
});
if (!response.ok) {
throw new Error('网络请求失败');
}
const aiResponse = await response.text();
// 移除加载消息
chatMessages.removeChild(loadingMessage);
// 添加AI回复
addMessage(aiResponse, false);
} catch (error) {
console.error('请求失败:', error);
// 显示错误消息
addMessage('抱歉,我遇到了一些问题,请稍后再试。', false);
}
});
// 处理回车发送
messageInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
chatForm.dispatchEvent(new Event('submit'));
}
});
// 添加热点话题点击事件
document.querySelectorAll('.hot-topic').forEach(topic => {
topic.addEventListener('click', function() {
const title = this.querySelector('.hot-topic-title').textContent;
messageInput.value = title;
// 自动触发表单提交
chatForm.dispatchEvent(new Event('submit'));
});
});
// 添加页面加载完成后移除加载动画的代码
window.addEventListener('load', function() {
const loadingContainer = document.getElementById('loadingContainer');
loadingContainer.classList.add('fade-out');
setTimeout(() => {
loadingContainer.style.display = 'none';
}, 500);
});
// 添加输入框自动增高功能
messageInput.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
// 限制最大高度
if (this.scrollHeight > 120) {
this.style.height = '120px';
this.style.overflowY = 'auto';
}
});
// 添加登录验证逻辑
const loginOverlay = document.getElementById('loginOverlay');
const passwordInput = document.getElementById('passwordInput');
const loginButton = document.getElementById('loginButton');
const loginError = document.getElementById('loginError');
const correctPassword = '123'; // 设置正确密码
// 检查是否已登录
if (sessionStorage.getItem('isLoggedIn')) {
loginOverlay.style.display = 'none';
}
// 处理登录
function handleLogin() {
if (passwordInput.value === correctPassword) {
loginOverlay.classList.add('fade-out');
setTimeout(() => {
loginOverlay.style.display = 'none';
}, 500);
sessionStorage.setItem('isLoggedIn', 'true');
loginError.style.display = 'none';
} else {
loginError.style.display = 'block';
passwordInput.value = '';
passwordInput.focus();
}
}
// 登录按钮点击事件
loginButton.addEventListener('click', handleLogin);
// 回车键登录
passwordInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
handleLogin();
}
});
</script>
</body>
</html>