在使用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