跟着网上的教程,自己实际操作了下,搞一个聊天机器人挺简单的,如何把ai用到自己的工作和生活中呀。。。
1、获取api_key
2、前端html
获取图标的网站,可以随意修改图标:
https://fontawesome.com/search?q=chat
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>智能聊天助手</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background: linear-gradient(135deg, #6e8efb, #a777e3);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.chat-container {
width: 100%;
max-width: 800px;
height: 90vh;
background: rgba(255, 255, 255, 0.92);
border-radius: 20px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
display: flex;
flex-direction: column;
overflow: hidden;
}
.chat-header {
background: linear-gradient(to right, #6e8efb, #a777e3);
color: white;
padding: 20px;
text-align: center;
position: relative;
}
.chat-header h1 {
font-size: 1.8rem;
font-weight: 600;
}
.chat-header p {
font-size: 0.9rem;
opacity: 0.9;
margin-top: 5px;
}
.chat-box {
flex: 1;
padding: 20px;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 15px;
}
.message {
max-width: 80%;
padding: 15px;
border-radius: 18px;
line-height: 1.5;
position: relative;
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.user-message {
background: #6e8efb;
color: white;
align-self: flex-end;
border-bottom-right-radius: 5px;
}
.ai-message {
background: #f0f4ff;
color: #333;
align-self: flex-start;
border-bottom-left-radius: 5px;
}
.message-header {
display: flex;
align-items: center;
margin-bottom: 8px;
font-weight: bold;
}
.user-message .message-header {
justify-content: flex-end;
}
.avatar {
width: 30px;
height: 30px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin-right: 10px;
font-size: 14px;
}
.user-avatar {
background: #4a6cf7;
}
.ai-avatar {
background: #a777e3;
}
.input-area {
padding: 15px;
background: white;
display: flex;
border-top: 1px solid #eee;
}
#user-input {
flex: 1;
padding: 14px 20px;
border: 2px solid #e0e4ff;
border-radius: 30px;
font-size: 1rem;
outline: none;
transition: border-color 0.3s;
}
#user-input:focus {
border-color: #6e8efb;
}
button {
background: linear-gradient(to right, #6e8efb, #a777e3);
color: white;
border: none;
border-radius: 30px;
padding: 14px 25px;
margin-left: 10px;
cursor: pointer;
font-weight: 600;
transition: transform 0.2s, box-shadow 0.2s;
box-shadow: 0 4px 15px rgba(107, 142, 251, 0.4);
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(107, 142, 251, 0.6);
}
button:active {
transform: translateY(0);
}
.typing-indicator {
display: none;
align-self: flex-start;
background: #f0f4ff;
color: #666;
padding: 15px;
border-radius: 18px;
font-style: italic;
}
.timestamp {
font-size: 0.7rem;
opacity: 0.7;
margin-top: 5px;
text-align: right;
}
/* 滚动条样式 */
.chat-box::-webkit-scrollbar {
width: 8px;
}
.chat-box::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 10px;
}
.chat-box::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 10px;
}
.chat-box::-webkit-scrollbar-thumb:hover {
background: #a777e3;
}
@media (max-width: 600px) {
.chat-container {
height: 95vh;
border-radius: 15px;
}
.message {
max-width: 90%;
}
button {
padding: 14px 20px;
}
}
</style>
</head>
<body>
<div class="chat-container">
<div class="chat-header">
<h1><i class="fas fa-robot"></i> 智能聊天助手</h1>
<p>随时为您提供帮助</p>
</div>
<div class="chat-box" id="chat-box">
<div class="ai-message">
<div class="message-header">
<div class="avatar ai-avatar"><i class="fas fa-robot"></i></div>
<span>AI助手</span>
</div>
您好!我是您的AI助手,有什么可以帮您的吗?
</div>
</div>
<div class="input-area">
<input type="text" id="user-input" placeholder="输入消息..." autocomplete="off">
<button onclick="sendMessage()"><i class="fas fa-paper-plane"></i> 发送</button>
</div>
</div>
<script>
// 页面加载时获取历史聊天记录
document.addEventListener('DOMContentLoaded', () => {
fetchHistory();
});
// 回车发送消息
const input = document.getElementById('user-input');
input.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
// async function fetchHistory() {
// try {
// const response = await fetch('http://localhost:5000/history');
// const history = await response.json();
// const chatBox = document.getElementById('chat-box');
// // 保留初始的AI欢迎消息
// chatBox.innerHTML = chatBox.innerHTML;
// history.forEach(msg => {
// addMessageToChat(msg.user_message, 'user');
// addMessageToChat(msg.ai_reply, 'ai');
// });
// scrollToBottom();
// } catch (error) {
// console.error('获取历史记录失败:', error);
// }
// }
async function sendMessage() {
const input = document.getElementById('user-input');
const userMsg = input.value.trim();
if (!userMsg) return;
// 显示用户消息
addMessageToChat(userMsg, 'user');
input.value = '';
// 显示"正在输入"指示器
showTypingIndicator();
try {
// 调用后端接口
const response = await fetch('http://localhost:5000/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: userMsg })
});
const data = await response.json();
// 隐藏"正在输入"指示器
hideTypingIndicator();
// 显示AI回复
if (data.reply) {
addMessageToChat(data.reply, 'ai');
} else if (data.error) {
addMessageToChat(`错误:${data.error}`, 'ai');
}
} catch (error) {
hideTypingIndicator();
addMessageToChat(`网络错误:${error.message}`, 'ai');
}
}
function addMessageToChat(message, sender) {
const chatBox = document.getElementById('chat-box');
const typingIndicator = document.getElementById('typing-indicator');
if (typingIndicator) {
chatBox.removeChild(typingIndicator);
}
const messageDiv = document.createElement('div');
messageDiv.classList.add('message');
const now = new Date();
const timestamp = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
if (sender === 'user') {
messageDiv.classList.add('user-message');
messageDiv.innerHTML = `
<div class="message-header">
<span>您</span>
<div class="avatar user-avatar"><i class="fas fa-user"></i></div>
</div>
${message}
<div class="timestamp">${timestamp}</div>
`;
} else {
messageDiv.classList.add('ai-message');
messageDiv.innerHTML = `
<div class="message-header">
<div class="avatar ai-avatar"><i class="fas fa-robot"></i></div>
<span>AI助手</span>
</div>
${message}
<div class="timestamp">${timestamp}</div>
`;
}
chatBox.appendChild(messageDiv);
scrollToBottom();
}
function showTypingIndicator() {
const chatBox = document.getElementById('chat-box');
const typingDiv = document.createElement('div');
typingDiv.classList.add('typing-indicator');
typingDiv.id = 'typing-indicator';
typingDiv.innerHTML = `
<div class="message-header">
<div class="avatar ai-avatar"><i class="fas fa-robot"></i></div>
<span>AI助手</span>
</div>
<span class="typing-dots">
<i class="fas fa-circle"></i>
<i class="fas fa-circle"></i>
<i class="fas fa-circle"></i>
</span>
`;
chatBox.appendChild(typingDiv);
scrollToBottom();
}
function hideTypingIndicator() {
const typingIndicator = document.getElementById('typing-indicator');
if (typingIndicator) {
typingIndicator.remove();
}
}
function scrollToBottom() {
const chatBox = document.getElementById('chat-box');
chatBox.scrollTop = chatBox.scrollHeight;
}
</script>
</body>
</html>
3、后端python,调用千问接口
python
import dashscope
from flask import Flask,request,jsonify
from flask_cors import CORS
from datetime import datetime
dashscope.api_key = "your api key"
app=Flask(__name__)
CORS(app)
@app.route('/chat',methods=['POST'])
def chat():
user_input = request.json.get('message')
if not user_input:
return jsonify({"error": "请输入消息"})
try:
# 调用千问API
response = dashscope.Generation.call(
model='qwen-turbo',
prompt=user_input,
result_format='text'
)
if response.status_code == 200:
ai_reply = response.output.text
return jsonify({"reply": ai_reply})
else:
return jsonify({"error": f"AI服务错误: {response.message}"})
except Exception as e:
return jsonify({"error": str(e)}), 500
# @app.route('/history',methods=['GET'])
# def chat_history():
# user_input = request.json.get('message')
# if not user_input:
# return jsonify({"error": "请输入消息"})
# try:
# # 调用千问API
# response = dashscope.Generation.call(
# model='qwen-turbo',
# prompt=user_input,
# result_format='text'
# )
# if response.status_code == 200:
# ai_reply = response.output.text
# return jsonify({"reply": ai_reply})
# else:
# return jsonify({"error": f"AI服务错误: {response.message}"})
# except Exception as e:
# return jsonify({"error": str(e)}), 500
if __name__=="__main__":
app.run(host='0.0.0.0', port=5000, debug=True)
4、启动python服务后,直接双击html就可以聊天了