Dify使用上传的文件进行对话功能的实现

一、dify的配置

正常的工作流或chatflow,主要注意三点:

1.需要有文档提取器节点

2.在大模型处理中需要引入文档提取器输出内容变量text

3.需要在右上角功能里面打开文件上传,并选择合适的文件类型

Dify使用上传的文件进行对话功能的实现_第1张图片

Dify使用上传的文件进行对话功能的实现_第2张图片 

二、代码调用

实现上传文件,并追加对话问题。文件格式为 csv

"""
版本号:1.0
日期:2025/6/10
描述:
"""
import json
import os

import requests

# 应用的api key
api_key = 'app-jRjvdIasUZAsDpDTEjf889NG'
# 用户id
user_id = 'abc-12345'


def get_file_id():
    url = 'http://192.168.110.14/v1/files/upload'
    file_path = 'data.csv'  # 替换为实际的CSV文件路径
    headers = {
        'Authorization': f'Bearer {api_key}',
        'user': user_id
    }
    try:
        with open(file_path, 'rb') as f:
            files = {
                'file': (os.path.basename(file_path), f, 'text/csv'),  # CSV 文件的 MIME 类型是 text/csv
            }
            data = {
                'user': user_id
            }

            response = requests.post(
                url,
                headers=headers,
                files=files,
                data=data
            )

            return response.json()['id']
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")


def chat_with_bot(id):
    question = f'小明多少岁了'
    url = 'http://192.168.110.14/v1/chat-messages'
    data = {
        "inputs": {},
        "query": f"{question}",
        "response_mode": 'streaming',
        "user": user_id,
        "files": [{"type": 'document', "transfer_method": 'local_file', "upload_file_id": id}]
    }
    headers = {
        'Authorization': f'Bearer {api_key}'
    }
    res = requests.post(url, headers=headers, json=data)
    for line in res.iter_lines():
        if line:
            line = line.decode('utf-8')
            if line.startswith('data: '):
                line = json.loads(line[6:])
                if line.get('event') == 'message':
                    print(line.get('answer'), end='', flush=True)


if __name__ == '__main__':
    file_id = get_file_id()
    chat_with_bot(file_id)

你可能感兴趣的:(Python,Dify,python,dify)