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}"})
相关推荐
2501_948122632 小时前
Qs 跨端三方库仓颉适配全流程
python·react native·django·tornado
CS创新实验室6 小时前
改了模型,数据库为什么能自动跟上?——Django 迁移(migrations)的底层
数据库·django·sqlite
weixin_BYSJ19871 天前
电竞先锋网站---附源码02032
java·vue.js·spring boot·python·django·tomcat·php
2601_949847751 天前
Cookie 跨端三方库仓颉适配全流程
python·django·flask
一级新生2 天前
提示词工程:跟 AI 打交道的手艺
人工智能·大模型·dify·1024程序员节·提示词工程
情 九3 天前
Dify SSE 流式调用实战:执行进度、运行 ID 与断线核实
dify
一级新生3 天前
Dify 接入大模型:本地还是云端?实战与选型
人工智能·大模型·dify·ollama
ycydynq3 天前
django利用不涉及数据库form自定义表单 表单元素验证
数据库·django·sqlite
一级新生4 天前
Ollama 是什么、干什么用、怎么用
人工智能·dify·ollama·本地大模型
一级新生4 天前
Dify 日常使用手册(小白版)
人工智能·docker·云原生·eureka·dify·ai工具