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_431600441 小时前
Agent Workflow 学习向:最小拖拽画布,看得见地编排,再一键跑通
后端·学习·ai·dify
FYKJ_20102 小时前
django学习成绩预警系统10905
java·javascript·spring boot·python·spark·django·php
言乐61 天前
Python实现自动拉人脚本示例
开发语言·windows·python·django·pygame
星野云联AIoT技术洞察2 天前
Dify 适合什么 AI 应用项目:Workflow、RAG、Agent 与自研系统的边界
agent·workflow·llmops·dify·rag·ai agent·ai应用开发
践行见远2 天前
django之配置文件加载
django
【赫兹威客】浩哥2 天前
【无标题】
python·spring·django·pyqt
winfredzhang2 天前
从零构建家庭照片管理系统:Django 模块化单体实战,以及我踩到的 4 个真实坑
python·postgresql·django·sqlite·bootsrap
weixin_BYSJ19872 天前
springboot智慧公共交通系统---附源码51123
java·javascript·spring boot·python·django·flask·php
衿心.2 天前
Django TemplateDoesNotExist
数据库·django·sqlite
weixin_BYSJ19873 天前
springboot游戏账号租赁系统---附源码50345
java·spring boot·python·游戏·django·flask·php