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}"})
相关推荐
叫我王富贵i21 小时前
0基础学Django
后端·python·django
2401_868534782 天前
综合脚本实战!自动备份、清日志、服务器巡检
python·django
鱼日先生3 天前
Dify 中级实验(13):多 Agent 协作——如何编排多个智能体分工干活?
工作流·dify·ai agent·大模型应用·ai 训练
weixin_BYSJ19873 天前
springboot酒店管理系统--附源码27436
java·spring boot·python·随机森林·贪心算法·eclipse·django
鱼日先生3 天前
Dify 中级实验(14):对话变量与状态管理——如何让工作流记住多轮对话的状态?
工作流·dify·ai agent·大模型应用·ai 训练
vx-程序开发3 天前
django医院预约挂号系统---附源码23353
java·javascript·spring boot·python·eclipse·django·php
weixin_BYSJ19873 天前
springboot医疗信息管理系统---附源码17465
java·javascript·spring boot·python·django·flask·php
vx-程序开发3 天前
springboot农产品运输服务平台---附源码75498
java·javascript·spring boot·python·eclipse·django·php
John jj4 天前
拆解 Telegram 群组频道收录市场:三类方案,一个可运行的评分模型,目前TG中文人工评分加模型评分机制——LetsTG收录“快速”、“无门槛”
大数据·后端·python·深度学习·搜索引擎·django·全文检索
2401_868534784 天前
论信息系统安全保障规划与设计
python·django