目录
前言
一句话定义:
DeepSeek 是一款面向[数据挖掘/机器学习/AI开发]的高效开源工具(根据实际用途描述),支持[分布式计算/自动化模型训练/数据可视化]等功能,旨在帮助开发者快速处理复杂任务。为什么选择DeepSeek:
✅ 高性能:基于[技术架构,如TensorFlow/PyTorch/Spark],优化计算效率。
✅ 易用性:提供简洁API和可视化界面,降低学习门槛。
✅ 社区支持:活跃的开源社区持续更新,解决用户痛点。
后面代码在本地运行的样子:
调用deepseek的API接口前置条件
依赖工具:Python环境(建议使用Anaconda管理)
获取自己的apikeys:
进入DeepSeek官网->DeepSeek | 深度求索
点击右上角API开放平台进入API后台
登录后便可查看到自己的余额和使用情况的信息啦
点击API keys,创建API keys。API keys只能在创建成功时查看一次,后面只能再新建,不可查看已经创建好的keys,注意保存!!
调用API及其代码
获取到API keys后便可以调用啦,下面代码是有前端代码和后端代码的,运行后直接在输入框填入提问的问题便可。
文件创建
- deepseek (主文件夹)
- templates (放前端代码的文件夹)
- index.html
- static (放网页图标的文件夹)
- favicon.ico (可以直接在百度上搜一个ico复制粘贴进去就行)
- app.py (主运行程序)
- config.py (配置文件,apikeys放在其中)
- requirements.txt (引入的环境配置及依赖)
- templates (放前端代码的文件夹)
- deepseek (主文件夹)
配置依赖--requirements.txt
pytest==7.4.0
python-dateutil==2.8.2
openai>=1.0.0
flask>=2.0.0
配置完成后,在终端运行 pip install -r requirements.txt 安装依赖
配置文件--config.py
# 配置参数
APP_NAME = "我的Python程序"
VERSION = "1.0.0"
# 数据库配置 -- 这个不写也没事
DB_CONFIG = {
"host": "localhost",
"port": 5432,
"database": "myapp"
}
# API配置
API_CONFIG = {
"api_key": "自己API keys",
"base_url": "https://api.deepseek.com"
}
# 服务器配置
SERVER_CONFIG = {
"host": "0.0.0.0", # 监听所有网络接口
"port": 8080, # 使用8080端口
"debug": False # 生产环境关闭调试模式
}
前端代码--index.html
<!DOCTYPE html>
<html>
<head>
<title>AI聊天界面</title>
<meta charset="UTF-8">
<link rel="shortcut icon" href="{
{ url_for('static', filename='favicon.ico') }}">
<style>
body {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: Arial, sans-serif;
}
#chat-container {
height: 400px;
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
overflow-y: auto;
}
#input-container {
display: flex;
gap: 10px;
}
#message-input {
flex-grow: 1;
padding: 8px;
}
button {
padding: 8px 20px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}
.message {
margin: 10px 0;
padding: 8px;
border-radius: 5px;
white-space: pre-wrap;
}
.user-message {
background-color: #e3f2fd;
margin-left: 20%;
}
.ai-message {
background-color: #f5f5f5;
margin-right: 20%;
}
/* 添加Markdown样式 */
.bold {
font-weight: bold;
}
.heading {
margin-top: 10px;
margin-bottom: 5px;
padding-left: 20px;
}
</style>
</head>
<body>
<h1>AI聊天界面</h1>
<div id="chat-container"></div>
<div id="input-container">
<input type="text" id="message-input" placeholder="输入消息...">
<button onclick="sendMessage()">发送</button>
</div>
<script>
function formatMessage(message) {
// 处理粗体
message = message.replace(/\*\*(.*?)\*\*/g, '<span class="bold">$1</span>');
// 处理标题和缩进
message = message.split('\n').map(line => {
if (line.startsWith('##')) {
return '\n<div class="heading">' + line.substring(2).trim() + '</div>';
}
return line;
}).join('\n');
return message;
}
function addMessage(message, isUser) {
const chatContainer = document.getElementById('chat-container');
const messageDiv = document.createElement('div');
messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
messageDiv.innerHTML = isUser ? message : formatMessage(message);
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
async function sendMessage() {
const input = document.getElementById('message-input');
const message = input.value.trim();
if (!message) return;
addMessage(message, true);
input.value = '';
try {
const response = await fetch('/chat', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ message: message })
});
// 创建 EventSource 来处理流式响应
const messageDiv = document.createElement('div');
messageDiv.className = 'message ai-message';
document.getElementById('chat-container').appendChild(messageDiv);
const reader = new ReadableStreamDefaultReader(response.body);
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const {value, done} = await reader.read();
if (done) break;
buffer += decoder.decode(value, {stream: true});
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
messageDiv.innerHTML = formatMessage(messageDiv.innerHTML + data.content);
const chatContainer = document.getElementById('chat-container');
chatContainer.scrollTop = chatContainer.scrollHeight;
} catch (e) {
console.error('解析错误:', e);
}
}
}
}
} catch (error) {
addMessage('发生错误: ' + error, false);
}
}
document.getElementById('message-input').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
主运行代码--app.py
注意事项:model=''为想调用的模型,具体模型model在官网的api文档中有,这里调用的是DeepSeek-R1 推理模型
api文档链接:首次调用 API | DeepSeek API Docs
from flask import Flask, request, render_template, jsonify, Response, send_from_directory
from openai import OpenAI
from config import API_CONFIG
import json
import os
app = Flask(__name__)
client = OpenAI(
api_key=API_CONFIG["api_key"],
base_url=API_CONFIG["base_url"]
)
# 添加favicon路由
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
# 添加基本的安全头
@app.after_request
def add_security_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['X-XSS-Protection'] = '1; mode=block'
return response
@app.route('/')
def home():
return render_template('index.html')
def get_api_response(user_message, max_retries=3):
"""获取API响应,支持重试机制"""
for attempt in range(max_retries):
try:
print(f"\n第{attempt + 1}次尝试获取回答")
response = client.chat.completions.create(
model='deepseek-reasoner',
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message},
],
stream=True
)
full_response = ""
for chunk in response:
if chunk.choices[0].delta.content is not None:
content = chunk.choices[0].delta.content
full_response += content
yield content
if full_response.strip(): # 如果有实际内容就返回
print(f"\n完整回答: {full_response}\n")
return
else:
print(f"\n第{attempt + 1}次尝试返回为空")
except Exception as e:
print(f"\n第{attempt + 1}次尝试发生错误: {str(e)}")
if attempt == max_retries - 1: # 最后一次尝试
raise Exception("API多次调用失败")
raise Exception("API返回数据为空")
@app.route('/chat', methods=['POST'])
def chat():
try:
user_message = request.json['message']
print(f"\n用户问题: {user_message}")
def generate():
for attempt in range(3): # 最多尝试3次
try:
print(f"\n第{attempt + 1}次尝试获取回答")
response = client.chat.completions.create(
model='deepseek-reasoner',
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": user_message},
],
stream=True
)
full_response = ""
for chunk in response:
if chunk.choices[0].delta.content is not None:
content = chunk.choices[0].delta.content
full_response += content
print(content, end='', flush=True)
yield f"data: {json.dumps({'content': content})}\n\n"
if full_response.strip(): # 如果响应不为空,则返回
print(f"\n完整回答: {full_response}")
return
else:
print(f"\n第{attempt + 1}次尝试返回为空")
except Exception as e:
print(f"\n第{attempt + 1}次尝试发生错误: {str(e)}")
if attempt == 2: # 最后一次尝试失败
yield f"data: {json.dumps({'content': '**API返回数据为空**'})}\n\n"
# 如果所有尝试都失败
if not full_response.strip():
yield f"data: {json.dumps({'content': '**API返回数据为空**'})}\n\n"
return Response(generate(), mimetype='text/event-stream')
except Exception as e:
error_msg = f"发生错误: {str(e)}"
print(error_msg)
return jsonify({"error": error_msg}), 500
if __name__ == '__main__':
# 修改为监听所有网络接口,设置端口为8080
app.run(host='0.0.0.0', port=8080, debug=False)
运行代码
所有文件创建好就可以运行啦🎉🎉👏👏
python app.py
最后结语
但是这个api免费使用的人数过多,会导致返回的数据为空,而且返回的速度也慢,还不如使用第三方平台部署的(现在第三方使用也会出现宕机。。)。等deepseek那边完善算法,返回速度快一点(费用多点都没事),就可以很完美的调用啦,期待期待。