Django连接Dify、ChatGPT4o并计算tokens数量方法

复制代码
通过Dify可以连接很多模型国内、国外的都可以进行选择



可以到Dify里创建一个空白应用,然后点击进入就可以看到API了
python 复制代码
api_url = "http://192.168.15.131/v1/chat-messages"
api_key = "app-UtzTpVNwpTLUcGvRNnnK9QNY"
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}
speak = request.GET.get('speak')
data = {
    "inputs": {},
    "query": speak,
    "response_mode": "streaming",
    "conversation_id": "",
    "user": "abc-123"
}
response = requests.post(api_url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
    for line in response.text.splitlines():
        if line.startswith("data: "):
            try:
                json_data = json.loads(line[6:])
                if json_data.get('event') == 'workflow_finished':
                    # 获取每次答案
                    answer = json_data['data']['outputs']['answer']
                    # 获取每次回答的total_tokens数量
                    total_tokens = json_data['data']['total_tokens']
                    today = datetime.now().date()
                    # 保存到数据库
                    save = Ai_info.objects.create(all_names=b_names, b_times=today, speak=speak, answer=answer, total_tokens=total_tokens, company=company_name)
                    return render(request, 'dify_DifyAI.html',
                                  {'speak': speak, 'answer': answer, 'b_head': b_head})
            except json.JSONDecodeError as e:
                print(f"JSON语法错误: {e}")
                # 处理JSON语法错误的情况
            except UnicodeDecodeError as e:
                print(f"编码错误: {e}")
else:
    return render(request, 'error.html', {'error_message': f"Error: {response.status_code}, {response.text}"})
相关推荐
IT毕设实战小研3 小时前
基于大数据的国内主要农作物产量趋势分析与可视化
android·java·大数据·django·课程设计
新时代牛马1 天前
镜像为什么越来越大?从Dockerfile、layer 到content-addressable store 讲透
django
专业程序开发源1 天前
springbootLivehouse票务系统-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·django·课程设计·pygame
李高钢1 天前
Python Django 框架入门:从零搭建你的第一个 Web 应用
前端·python·django
troy1282 天前
分布式系统框架选型指南:主流框架优缺点深度对比
python·django·pygame
IT毕设实战小研2 天前
基于大数据的跨国外派人员适应满意度与留存影响因素可视化分析
android·java·大数据·python·django·课程设计
xixingzhe22 天前
spring boot对接Dify
java·spring boot·dify
烂蜻蜓3 天前
Django入门教程(三):django-admin与manage.py命令完全指南
数据库·django·sqlite
2601_962283884 天前
Django数据库配置(一)
mysql·postgresql·django·sqlite·数据库配置
qq_22589174666 天前
基于Python+Django的LangGraph智能旅游规划系统
python·django·旅游