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}"})
相关推荐
向上的车轮10 分钟前
NestJS、Spring Cloud、FastAPI、Django 深度对比分析报告
spring cloud·django·fastapi
IT策士2 天前
Django 从 0 到 1 打造完整电商平台:Admin 后台管理与数据初始化
数据库·django·sqlite
IT策士2 天前
Django 从 0 到 1 打造完整电商平台:Django 模型进阶与数据迁移
python·django·sqlite
Angel2 天前
Dify系列课程 - 4.Dify实战(本地部署-源码下载与部署)
ai·dify·dify实战·dify实战指南·dify docker 部署·ai实战 应用
IT策士3 天前
Django 从 0 到 1 打造完整电商平台:为什么用 Django 做电商?
后端·python·django
zzzzzz3103 天前
VGGT-Ω 深度解读:用 30% 显存训练 15 倍数据,牛津&Meta 的 3D 视觉大一统之路
django
Muyuan19983 天前
31.Cursor 初体验:用 AI Agent 给 PaperPilot 做一次最小工程重构
人工智能·python·重构·django·fastapi·faiss
IT策士3 天前
Django 从 0 到 1 打造完整电商平台:电商项目需求分析与数据库设计
数据库·django·需求分析
海市公约3 天前
从 CRUD 到 AI 工程:基于 FastAPI + Dify 的 AI 面试模拟系统实践
prompt·fastapi·项目实战·dify·ai工作流·后端架构
creaDelight3 天前
Django 中间件钩子函数 & CBV vs FBV 实战验证
python·中间件·django