dify工作流api上传文件

在使用difyapi调用工作流上传文件的时候,需要上传一个upload_file_id的字段,
在这里插入图片描述
在这里插入图片描述
找了半天也没找到这个文件ID在哪

后来发现 需要先调用这个api来上传文件来获得文件的ID
在这里插入图片描述
获得ID后就可以在工作流里上传文件了

代码如下

def upload_file(local_file_path, api_key):
    """
    上传文件
    """
    # 替换为你的实际文件类型
    file_type =  'application/pdf'# 可以根据实际情况修改为 jpeg、jpg、webp、gif 等
    # 替换为你的实际用户标识
    user = "abc-123"

    # API 端点
    url = 'https://api.dify.ai/v1/files/upload'

    # 设置请求头
    headers = {
        'Authorization': f'Bearer {api_key}'
    }

    # 打开本地文件
    with open(local_file_path, 'rb') as file:
        # 构建表单数据
        files = {
            'file': (local_file_path, file, file_type)
        }
        data = {
            'user': user
        }

        # 发送 POST 请求
        response = requests.post(url, headers=headers, files=files, data=data)

    # 检查响应状态码
    if response.status_code == 201:
        print("文件上传成功")
        print(response.json())
        id = response.json()['id']
        return id
    else:
        print(f"文件上传失败,状态码: {response.status_code}")
        print(response.text)
def run_workflow(file_id,api_key):
    """
    执行工作流

    Args:
        file_id: 文件ID
        api_key: API密钥

    Returns:
        dict: 工作流执行结果
    """
    # 工作流API端点
    workflow_url = "https://api.dify.ai/v1/workflows/run"
    # 请求头
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    # 准备数据
    data = {
            "inputs": {
            "file1": {  # 工作流中定义的文件变量名
                "type": "document",
                "transfer_method": "local_file",
                "upload_file_id": file_id
            }
        },
        "response_mode": "blocking",
        "user": "user-id"
    }
    max_retries = 3
    retry_count = 0
    while retry_count < max_retries:
        try:
            # 发送 POST 请求
            response = requests.post(workflow_url, headers=headers, json=data, stream=True)
            # 检查响应状态码
            response.raise_for_status()
            data = json.loads(response.text)
            return data['data']['outputs']['text']
        except Exception as e:
            print(f"工作流执行失败(第 {retry_count + 1} 次尝试): {str(e)}")
            retry_count += 1
    print("达到最大重试次数,工作流执行失败。")
    return None
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值