python使用django调用deepseek api搭建ai网站

一、deepseek简介

DeepSeek是一家人工智能公司,专注于开发先进的人工智能模型和技术。以下是关于DeepSeek的一些详细介绍:

1.公司背景

DeepSeek由杭州深度求索人工智能基础技术研究有限公司开发,致力于通过创新的技术和算法,推动人工智能领域的发展。

2.技术与模型

  • DeepSeek-V3:这是DeepSeek开发的一个大型语言模型,具有超过600B的参数,在多项性能指标上与国际顶尖模型相当。
  • DeepSeek-R1:这是DeepSeek的第一代推理模型,通过大规模强化学习(RL)进行训练,展示出了在推理任务上的优异性能。
  • DeepSeek-R1-Distill:这些是从DeepSeek-R1中蒸馏出的小模型,具有更好的性能和效率,适合在资源受限的环境中使用。

3.应用领域

  • 自然语言处理:DeepSeek的模型在文本生成、知识问答、推理等任务中表现出色,能够为用户提供高质量的语言交互服务。
  • 智能助手:DeepSeek开发了AI智能助手,可用于搜索、写作、阅读、解题、翻译等多种任务,帮助用户提高效率。

4.优势与特点

  • 成本优势:DeepSeek的模型训练成本低,调用接口成本也较低,具有较高的性价比。
  • 中文处理能力强:对中文语法、成语、文化背景理解更深入,在中文文本生成、摘要、情感分析等任务中表现自然。
  • 开源优势:DeepSeek-R1模型权重和技术报告开源,便于开发者二次开发和创新。

5.产品与服务

  • DeepSeek API:提供与OpenAI兼容的API,方便开发者将DeepSeek的模型集成到自己的应用中。
  • DeepSeek App:提供AI智能助手应用,可在App Store上下载,支持多种功能,如智能对话、搜索、写作等。

二、获取apikey

deepseek官方的api暂时无法充值,我使用的是阿里云的百炼平台的deepseek v1模型,阿里云百炼平台注册送百万token,可以白嫖。打开百炼控制台,开通服务,随便选择一个模型,点击右上角的“查看我的apikey”,获取apikey。

python使用django调用deepseek api搭建ai网站

三、创建django项目,并startapp

使用django创建一个新的项目,python manage.py startapp chat新建app作为主要代码文件夹。

四、编写代码

chat\views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from django.shortcuts import render
from openai import OpenAI
import os
from django.conf import settings
 
 
def get_ai_response(messages):
client = OpenAI(
api_key="xxx",//填写apikey
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
 
 
try:
    completion = client.chat.completions.create(
        model="qwen2.5-14b-instruct-1m",
        messages=messages
    )
    return {
        'content': completion.choices[0].message.content,
        'reasoning': getattr(completion.choices[0].message, 'reasoning_content', '')
    }
except Exception as e:
    return {
        'content': f"发生错误:{str(e)}",
        'reasoning': ''
    }
 
def chat_view(request):
if 'messages' not in request.session:
request.session['messages'] = []
 
 
if request.method == 'POST':
    user_message = request.POST.get('message', '')
    if user_message:
        request.session['messages'].append({'role': 'user', 'content': user_message})
 
        response = get_ai_response(request.session['messages'])
 
        request.session['messages'].append({
            'role': 'assistant',
            'content': response['content'],
            'reasoning': response['reasoning']
        })
 
        request.session.modified = True
 
return render(request, 'chat.html', {
    'messages': request.session['messages']
})

要将api_key=”xxx”中xxx替换为自己的apikey。

urls.py

1
2
3
4
5
6
7
8
from django.contrib import admin
from django.urls import path
from chat import views
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.chat_view, name='chat'),
]

前端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<!DOCTYPE html>
<html>
<head>
    <title>AI对话助手(Markdown支持版)</title>
    <!-- Markdown 渲染依赖 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@5.2.0/github-markdown.min.css" rel="external nofollow" >
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css" rel="external nofollow" >
    <style>
        :root {
            --user-color: #1a73e8;
            --assistant-color: #0b8043;
        }
        body {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background-color: #f8f9fa;
        }
        .chat-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .message {
            margin: 15px 0;
            padding: 12px 16px;
            border-radius: 8px;
        }
        .user-message {
            background-color: #e8f0fe;
            border: 1px solid var(--user-color);
            margin-left: 30px;
        }
        .assistant-message {
            background-color: #e6f4ea;
            border: 1px solid var(--assistant-color);
            margin-right: 30px;
        }
        .role-label {
            font-weight: 500;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .role-label::before {
            content: '';
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
        }
        .user-message .role-label::before {
            background: var(--user-color);
        }
        .assistant-message .role-label::before {
            background: var(--assistant-color);
        }
        form {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        input[type="text"] {
            flex: 1;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }
        button {
            padding: 12px 24px;
            background-color: var(--user-color);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.2s;
        }
        button:hover {
            background-color: #1557b0;
        }
        .markdown-body pre {
            padding: 16px;
            border-radius: 8px;
            overflow-x: auto;
        }
        .reasoning-box {
            margin-top: 12px;
            padding: 12px;
            background: #fff8e5;
            border-left: 4px solid #ffd700;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <h1 style="color: var(--user-color); text-align: center;">AI对话助手</h1>
 
        <div class="messages">
            {% for message in messages %}
                <div class="message {% if message.role == 'user' %}user-message{% else %}assistant-message{% endif %}">
                    <div class="role-label">
                        {% if message.role == 'user' %}
                            👤 用户
                        {% else %}
                            🤖 助手
                        {% endif %}
                    </div>
                    <!-- Markdown 内容容器 -->
                    <div class="markdown-body"
                         data-markdown="{{ message.content|escape }}"
                         data-raw="{{ message.content|escape }}">
                        {{ message.content|safe }}
                    </div>
 
                    {% if message.reasoning %}
                    <div class="reasoning-box">
                        <div class="reasoning-label">💡 思考过程</div>
                        <div class="markdown-body"
                             data-markdown="{{ message.reasoning|escape }}"
                             data-raw="{{ message.reasoning|escape }}">
                            {{ message.reasoning|safe }}
                        </div>
                    </div>
                    {% endif %}
                </div>
            {% endfor %}
        </div>
 
        <form method="post">
            {% csrf_token %}
            <input type="text" name="message" placeholder="请输入您的问题..." required autofocus>
            <button type="submit">发送</button>
        </form>
    </div>
 
    <!-- 依赖库 -->
    <script src="https://cdn.jsdelivr.net/npm/marked@12.0.0/lib/marked.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.5/dist/purify.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
 
    <script>
        // 初始化配置
        marked.setOptions({
            breaks: true,
            highlight: (code, lang) => {
                const language = hljs.getLanguage(lang) ? lang : 'plaintext';
                return hljs.highlight(code, { language }).value;
            }
        });
 
        // Markdown 渲染函数
        const renderMarkdown = () => {
            document.querySelectorAll('.markdown-body').forEach(container => {
                try {
                    // 优先使用 data-markdown 属性
                    const raw = container.dataset.markdown || container.dataset.raw;
                    const clean = DOMPurify.sanitize(raw, {
                        ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'code', 'pre', 'blockquote',
                                     'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'a', 'p', 'br', 'hr'],
                        ALLOWED_ATTR: ['href', 'target']
                    });
                    container.innerHTML = marked.parse(clean);
                } catch (e) {
                    console.error('Markdown渲染失败:', e);
                    container.innerHTML = container.dataset.raw;
                }
            });
 
            // 触发代码高亮
            hljs.highlightAll();
        };
 
        // 确保依赖加载完成后执行
        const checkDependencies = () => {
            if (window.marked && window.DOMPurify && window.hljs) {
                renderMarkdown();
            } else {
                setTimeout(checkDependencies, 100);
            }
        };
 
        // 启动渲染流程
        document.addEventListener('DOMContentLoaded', checkDependencies);
    </script>
</body>
</html>

迁移数据库

python manage.py makemigrations
python manage.py migrate

五、效果展示

python使用django调用deepseek api搭建ai网站

六、将模型切换为deepseek

切换模型只要修改model=”qwen2.5-14b-instruct-1m”为deepseek.

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

使用支付宝扫码打赏,您的支持是我们持续努力的动力!
点赞 (0)

文章内容仅供参考,专业问题请咨询专业人士! 文章内观点、立场为作者个人行为,不代表本站立场! 未经书面许可请勿转载本站内容,否则您将承担侵权责任!

潇湘云服 电脑知识 python使用django调用deepseek api搭建ai网站 http://www.xxhunan.com/archives/668

常见问题
  • 对于站内付费内容,您需要支付相关费用才能查看,您可以购买单次查看服务,也可以通过升级VIP会员来获取批量查看服务,我们建议您通过升级VIP服务来获得查看权限。
查看详情
  • 您可以通过会员中心的商城功能直接升级VIP会员,VIP会员可以享受更多优惠服务!
查看详情

相关文章

评论
暂无评论
python使用django调用deepseek api搭建ai网站-海报

分享本文封面