Django连接Azure服务器里的gpt-4o并实现聊天功能
View.py
# 配置OpenAI API
api_key = ""
# 配置OpenAI APIURL
endpoint = ""
# 配置模型名称
deployment_name = "gpt-4o-0312"
# 配置API版本
api_version = "2023-03-15-preview"
# 初始化 tiktoken 编码器,计算详细token值
encoding = tiktoken.encoding_for_model("gpt-4o")
# 计算token数量
def count_tokens(text):
return len(encoding.encode(text))
# 连接Openai并发送请求传递到页面
def dify_Azure(request):
b_token = request.COOKIES.get('b_token')
if b_token is None:
return redirect("B_Login:b_login")
else:
b_token = request.COOKIES.get('b_token')
A = B_user.objects.using('default').filter(b_power="1").filter(b_token=b_token).values_list('b_user',
flat=True).first()
B = B_usertwo.objects.using('default').filter(b_power="2").filter(b_token=b_token).values_list('b_user',
flat=True).first()
if A or B:
# 发送请求到OpenAI API
headers = {
"Content-Type": "application/json",
"api-key": api_key
}
speak = request.GET.get('speak')
data = {
# 与OpenAI对话
"messages": [
{"role": "user", "content": speak}
],
# 限制max_tokens的合理值
"max_tokens": 10000
}
try:
url = f"{endpoint}openai/deployments/{deployment_name}/chat/completions?api-version={api_version}"
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
response_data = response.json()
content = response_data['choices'][0]['message']['content']
# 计算token数量
user_tokens = count_tokens(data['messages'][0]['content'])
response_tokens = count_tokens(content)
# 计算总token数量并输出页面
total_tokens = user_tokens + response_tokens
return render(request, 'dify_AzureAI.html', {'response': content, 'speak': speak, 'A': A, 'B': B})
else:
# 捕获连接、请求失败、账户资金缺少错误信息
errorcontent = f"Error: {response.status_code} - {response.text}"
return render(request, 'dify_AzureAI.html')
# 捕获其他异常错误
except requests.exceptions.RequestException as e:
errorcontent = f"Request failed: {str(e)}"
return render(request, 'dify_AzureAI.html', {'response': errorcontent})
else:
return redirect("Error_Page:authority_warn")
dify_AzureAI.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no" name="viewport">
<meta name="robots" content="noindex, nofollow">
<link href="{% static 'plugin/assets/lib/perfect-scrollbar/css/perfect-scrollbar.css' %}" rel="stylesheet">
<link href="{% static 'plugin/assets/lib/metismenu/css/metisMenu.min.css' %}" rel="stylesheet">
<link href="{% static 'plugin/assets/lib/bootstrap/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'plugin/assets/css/main.css' %}" rel="stylesheet">
<style>
html, body {
margin: 0;
padding: 0;
overflow: hidden;
}
.chat-container {
height: 80vh;
overflow-y: auto;
border: 1px solid #dee2e6;
border-radius: .375rem;
background-color: #ffffff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
margin-bottom: 20px;
}
.message {
margin-bottom: 1rem;
display: flex;
align-items: flex-end;
}
.message.user {
flex-direction: row-reverse;
}
.message-content {
padding: 10px 15px;
border-radius: .375rem;
position: relative;
max-width: 75%;
word-wrap: break-word;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.message.user .message-content {
background-color: #39BAF5;
color: white;
border-top-right-radius: 0;
word-wrap: break-word;
}
.message .message-content {
background-color: #f1f1f1;
color: #212529;
border-top-left-radius: 0;
word-wrap: break-word;
}
.typing-indicator {
font-style: italic;
color: #6c757d;
margin-top: 5px;
text-align: right;
}
.rr {
display: flex;
justify-content: center;
}
</style>
</head>
<body>
<div class="page-content">
<div class="card">
<div class="card-body">
<div class="chat-container" id="chat-container">
{% if response == None %}
{% else %}
<div class="message">
<img src="{% static 'AI_head.jpg' %}" width="48" height="48" class="rounded-circle">
<div class="message-content">
{{ response }}
</div>
</div>
{% endif %}
{% if response == None %}
{% else %}
<div class="message user">
<img src="{% static A.b_head %}" width="48" height="48" class="rounded-circle">
<div class="message-content">
{{ speak }}
</div>
</div>
<div id="typing-indicator" class="typing-indicator" style="display:none;">AI正在输入...</div>
{% endif %}
</div>
</div>
<div class="card-footer" style="margin-top: -30px;">
<form method="get" id="chat-form" class="form-inline"
action="{% url 'Core_dify:dify_Azure' %}">{% csrf_token %}
<div class="row rr">
<div class="col-auto col-sm-10">
<input type="text" class="form-control" name="speak" placeholder="请输入你与AI对话的消息...">
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary form-control"><i class="fas fa-sign-in-alt"></i>发送对话
</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="{% static 'plugin/assets/lib/metismenu/js/metisMenu.min.js' %}"></script>
<script src="{% static 'plugin/assets/lib/perfect-scrollbar/js/perfect-scrollbar.js' %}"></script>
<script src="{% static 'plugin/assets/js/main.js' %}"></script>
<script>
$(document).ready(function () {
$('#chat-form').on('submit', function (e) {
e.preventDefault();
const message = $(this).find('input').val();
if (message) {
$('.chat-container').append(`
<div class="message user">
<img src="https://via.placeholder.com/40" class="avatar">
<div class="message-content">
${message}
</div>
</div>
`);
$(this).find('input').val('');
$('.chat-container').scrollTop($('.chat-container')[0].scrollHeight);
showTypingIndicator();
}
});
function showTypingIndicator() {
$('#typing-indicator').show();
setTimeout(() => {
$('#typing-indicator').hide();
const botMessage = "这是AI的自动回复。";
$('.chat-container').append(`
<div class="message">
<img src="{% static 'AI_head.jpg' %}" width="48" height="48" class="rounded-circle">
<div class="message-content">
${botMessage}
</div>
</div>
`);
$('.chat-container').scrollTop($('.chat-container')[0].scrollHeight);
}, 2000);
}
});
</script>
</body>
</html>