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}"})
相关推荐
weixin_BYSJ198712 小时前
springboot3家政平台小程序--附源码00904
java·javascript·spring boot·python·django·flask·php
米码收割机1 天前
【Python】Django 电子设备商城系统(源码+说明文档)[独一无二]
开发语言·python·django
dNGUZ7UGj2 天前
10分钟完成第一个Python小游戏
python·django
想你依然心痛3 天前
电力能耗系统怎么搭,Django 加 PostgreSQL 入门指南
postgresql·django·电力能耗系统,后端开发
weixin_BYSJ19873 天前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php
码上解惑4 天前
从 Dify 工作流说起:常用节点怎么选、怎样组合?
java·人工智能·ai·agent·dify·智能体·spring ai
程序员羽痕5 天前
基于 Django + PyTorch 的中文字体识别系统
pytorch·python·django
johnny2336 天前
Django生态:Django-admin、Django-Compressor、Django-grappelli、django-rules
django
独码侠7 天前
Dify 开源深度实践:从企业部署到二次开发的全景拆解
知识库·dify·rag·ai工作流
weixin_BYSJ19878 天前
django在线图书销售平台---附源码16192
java·javascript·spring boot·python·django·flask·php