简单 AI 聊天机器人前端原型
·
一、准备
-
环境依赖:
- Node.js + npm/yarn
- Vue CLI(用于创建 Vue 项目)
- DeepSeek API 访问权限(需注册获取 API Key)
-
工具安装:
# 创建 Vue 项目 vue create chat-robot cd chat-robot # 安装依赖 npm install --save axios ws
二、项目结构
src/
├── assets/ # 静态资源(CSS/图片)
├── components/ # 组件
│ └── ChatBox.vue # 聊天组件
├── services/ # API 服务
│ └── websocket.js # WebSocket 通信模块
└── App.vue # 主组件
三、代码实现
1. WebSocket 服务封装 (services/websocket.js)
import { Injectable } from '@vue/runtime-core';
import { w3cwebsocket as WSC } from 'websocket';
@Injectable()
export class WebSocketService {
private socket: WSC | null = null;
private url = 'wss://your-deepseek-api-endpoint/ws'; // 替换为 DeepSeek 的 WebSocket API 地址
connect() {
this.socket = new WSC(this.url, {
headers: {
'Authorization': `Bearer ${process.env.VUE_APP_DEEPSEEK_API_KEY}` // 添加你的 API Key
}
});
this.socket.onopen = () => console.log('WebSocket 连接成功');
this.socket.onerror = (error) => console.error('WebSocket 错误:', error);
this.socket.onmessage = (event) => this.handleMessage(event.data);
}
sendMessage(message) {
if (this.socket && this.socket.readyState === WSC.OPEN) {
this.socket.send(JSON.stringify({ type: 'chat', content: message }));
}
}
private handleMessage(data) {
console.log('收到消息:', data);
// 这里可以直接触发全局事件或通过 Vuex 管理状态
this.$emit('message-received', JSON.parse(data));
}
}
2. 聊天组件 (components/ChatBox.vue)
<template>
<div class="chat-container">
<div class="messages">
<div
v-for="(msg, index) in messages"
:key="index"
:class="['message', { 'me': msg.sender === 'user' }]"
>
<div class="content">{{ msg.content }}</div>
</div>
</div>
<input
type="text"
v-model="newMessage"
@keyup.enter="sendMessage"
placeholder="输入消息..."
/>
<button @click="sendMessage">发送</button>
</div>
</template>
<script>
import { defineComponent, ref, inject } from 'vue';
import { WebSocketService } from '@/services/websocket';
export default defineComponent({
name: 'ChatBox',
setup() {
const wsService = inject(WebSocketService);
const messages = ref([]);
const newMessage = ref('');
// 初始化连接
wsService.connect();
// 监听消息事件
wsService.$on('message-received', (response) => {
messages.value.push({
sender: 'assistant',
content: response.answer
});
});
function sendMessage() {
if (newMessage.value.trim() === '') return;
messages.value.push({
sender: 'user',
content: newMessage.value
});
newMessage.value = '';
// 发送消息到 DeepSeek API
wsService.sendMessage(newMessage.value);
}
return {
messages,
newMessage,
sendMessage
};
}
});
</script>
<style scoped>
.chat-container {
width: 400px;
max-width: 100%;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.messages {
height: 300px;
overflow-y: scroll;
margin-bottom: 20px;
}
.message {
margin-bottom: 15px;
padding: 10px;
border-radius: 4px;
}
.message.me {
background-color: #f0f4ff;
}
.content {
white-space: pre-wrap;
}
</style>
3. 主应用 (App.vue)
<template>
<div id="app">
<ChatBox />
</div>
</template>
<script>
import { defineComponent } from 'vue';
import ChatBox from './components/ChatBox.vue';
import { WebSocketService } from './services/websocket';
export default defineComponent({
name: 'App',
components: {
ChatBox
},
setup() {
const wsService = new WebSocketService();
provide(WebSocketService, wsService); // 注入 WebSocket 服务
}
});
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
四、配置说明
-
环境变量:
- 在项目根目录创建
.env文件,添加 DeepSeek API 密钥:VUE_APP_DEEPSEEK_API_KEY=your_api_key_here
- 在项目根目录创建
-
WebSocket API 端点:
- 根据 DeepSeek 官方文档替换
wss://your-deepseek-api-endpoint/ws为实际 WebSocket 地址。
- 根据 DeepSeek 官方文档替换
五、运行效果
- 启动项目:
npm run serve - 打开浏览器访问
http://localhost:8080,即可看到聊天界面。 - 输入消息后,通过 WebSocket 发送到 DeepSeek API 并显示回复。
更多推荐
所有评论(0)