当前位置: 首页 > article >正文

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">
                            &nbsp;{{ response }}&nbsp;
                        </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 }}&nbsp;
                        </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>


http://www.kler.cn/a/327557.html

相关文章:

  • 群控系统服务端开发模式-应用开发-前端级别功能开发
  • 鸿蒙动画开发07——粒子动画
  • springboot上传下载文件
  • PHP 表单 - 必需字段
  • AIGC----生成对抗网络(GAN)如何推动AIGC的发展
  • Linux下编译MFEM
  • PHP程序如何实现限制一台电脑登录?
  • maven parent: 指定了项目的父 POM packaging: 指定打包类型为 POM。 modules: 列出了该项目包含的子模块,
  • 【开源免费】基于SpringBoot+Vue.JS校园资料分享平台(JAVA毕业设计)
  • opus基础简介(github)
  • 使用rsync+jenkins实现服务自动部署全流程
  • React 生命周期 - useEffect 介绍
  • WebGIS包括哪些技术栈?怎么学习?
  • 足球青训俱乐部后台:Spring Boot开发策略
  • 滚雪球学MySQL[11.1讲]:总结与展望
  • Spring Boot 点餐系统:简化您的订餐流程
  • 一个服务器可以搭建几个网站
  • vue结合element-ui实现列表拖拽变化位置,点击拖动图标拖动整个列表元素,使用tsx格式编写
  • SpringBootTest Mockito 虚实结合编写测试
  • LPDDR4芯片学习(二)——Functional Description
  • 解锁高效开发的秘密武器
  • <Rust>egui学习之部件(十三):如何为文本添加链接Link和超链接HyperLink功能?
  • 基于J2EE技术的高校社团综合服务系统
  • 设计模式---代理模式
  • webpack使用
  • 【Spring Boot 入门一】构建你的第一个Spring Boot应用