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}"})
相关推荐
YJlio1 小时前
Registry Usage (RU) 学习笔记(15.5):注册表内存占用体检与 Hive 体量分析
服务器·windows·笔记·python·学习·tcp/ip·django
Psycho_MrZhang2 小时前
Django/Flask/FastAPI简要对比分析
django·flask·fastapi
xj7573065332 小时前
精通django 第二章 视图和URL
数据库·django·sqlite
YJlio1 天前
RAMMap 学习笔记(15.2):Processes / Priority / Summary——从“谁在用”和“谁更重要”看物理内存
开发语言·笔记·python·学习·django·pdf·硬件架构
xj7573065331 天前
《精通Django》第一章 入门
数据库·django·sqlite
哈里谢顿1 天前
验证 list() 会调用 `__len__` 方法的深度解析
python·django
luoluoal2 天前
基于python的语音和背景音乐分离算法及系统(源码+文档)
python·mysql·django·毕业设计·源码
luoluoal2 天前
基于python的英汉电子词典软件(源码+文档)
python·mysql·django·毕业设计·源码
luoluoal2 天前
基于python的旅游景点方面级别情感分析语料库与模型(源码+文档)
python·mysql·django·毕业设计·源码
YJlio2 天前
Sysinternals 学习笔记(15.0):系统信息工具总览——RAMMap、RU、CoreInfo 等一网打尽
开发语言·笔记·python·学习·django·pdf·硬件架构