支持私有云部署
AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


Dify工作流的使用(四)API调用

发布日期:2025-03-17 18:58:15 浏览次数: 1655 来源:冒泡的肥皂
推荐语

掌握Dify工作流,高效调用API,打造智能小工具。

核心内容:
1. Dify工作流的API调用介绍
2. API调用的参数格式和注意事项
3. 使用Java实现API调用的示例代码

杨芳贤
53A创始人/腾讯云(TVP)最具价值专家

通过前面的文章,我们基本可以了解到知识库的建立和大模型使用的一些基本流程。分享到此基本用demo涵盖了知识库的建立、工作流的一些使用、代码插入调用、和视觉模型的使用。

今天再分享API调用的demo,然后基本上有想用dify+大模型(DeepSeek把价格搞下来了或者本地部署开源的)做些小工具的可以试着尝试整个流程了!

  • Dify工作流的使用(三)表格OCR
  • DeepSeek+Dify工作流的使用(二)
  • DeepSeek+Dify工作流的使用(一)插入代码
  • DeepSeek+Dify打造数据库查询专家修正(一)
  • DeepSeek+Dify打造数据库查询专家
  • Dify个人助理本地搭建快速入门

Dify的API简要说明

  • 协议http/https
  • 参数格式是JSON
  • 注意点每个应用一个key
  • 每个不通类型的应用可能API地址有点不一样
  • 分享的Demo采用的是用java的okhttp3写的(调用之前的demo,一个有插入代码的工作流)
  • 对原有文件上传的示例代码加了点注释和一些说明

查看你想调用工具一些信息

  • 1.发布那里点访问API,那里有访问的路径和参数的JSON格式

  • 2.文档调用的明细内容。这里包含了请求的参数和返回的内容

  • 3.API密钥的一个管理

参数的一些讲解

  /**
     * curl -X POST 'http://127.0.0.1/v1/workflows/run' \
     * --header 'Authorization: Bearer {api_key}' \
     * --header 'Content-Type: application/json' \
     * --data-raw '{
     *     "inputs": {},
     *     "response_mode": "streaming",
     *     "user": "abc-123"
     * }'

     */
  • 0.这部分内容基本是文档上的
  • 1.地址是请求的路径,请求方式POST
  • 2.header部分是请求的认证
  • 3.inputs是输入的参数内容
  • 4.user部分可以随便写
  • 5.注意response_mode的模式(blocking:阻塞模式 streaming:流的模式;demo采用的是阻塞模式
  • 6.response部分是返回的内容

测试前面分享的那个代码插入的那个工作流

效果

测试代码

    //参数定义是用的枚举:KEY+API地址
    public void difyFlow(DifyReqType reqType) {
        OkHttpClient client= new OkHttpClient();
        Response response = null;
        try {
            //请求参数的封装
            DifyReqBody form= new DifyReqBody();
            ObjectMapper objectMapper = new ObjectMapper();
            //json
            String json = objectMapper.writeValueAsString(form);
            System.out.println(json);
            RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
            Request.Builder builder = new Request.Builder()
                    .url(reqType.getReq_url())
                    //认证部分
                    .addHeader("Authorization""Bearer " + reqType.getApi_key())
                    .addHeader("Content-Type""application/json");
            Request request = builder.post(body).build();
            Call call = client.newCall(request);
            response = call.execute();

            int code = response.code();
            /**
             * .toString() :这将以字符串格式返回您的对象。
             * .string() :这将返回您的回复。
             */
            String responseBodyString = response.body().string();
            System.out.println(code+" 返回内容:"+responseBodyString);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            response.close();
        }
    }

有文件上传部分的原demo加了注释解释

  • 文件那里API demo是有代码的
  • 包含两个部分一个文件上传的使用和上传文件的使用
  • 直接再给的示例里面写点注释吧
  • 注意点:1.文件的类型一定要设置成你工具对应的类型,不然有些不通过的
  • 注意点:2.还有个注意点返回的数据可能有unicode编码的内容直接用json转就可以了
import requests
import json

#文件上传 主要得到上传后的ID(后面可以复用
def upload_file(file_path, user):
    #这个是文件上传的API地址:http://127.0.0.1/v1/files/upload
    upload_url = "https://api.dify.ai/v1/files/upload"
    #认证信息再头文件里面
    headers = {
        "Authorization""Bearer app-xxxxxxxx",
    }
    try:
        print("上传文件中...")
        with open(file_path, 'rb') as file:
            //文件参数的key要对应你的输入参数名
            files = {
                'file': (file_path, file, 'text/plain')  # 确保文件以适当的MIME类型上传
            }
            #文件的一些信息
            data = {
                "user": user,
                "type""TXT"# 设置文件类型为TXT
            }
            
            response = requests.post(upload_url, headers=headers, files=files, data=data)
            if response.status_code == 201:  # 201 表示创建成功
                print("文件上传成功")
                return response.json().get("id")  # 获取上传的文件 ID
            else:
                print(f"文件上传失败,状态码: {response.status_code}")
                return None
    except Exception as e:
        print(f"发生错误: {str(e)}")
        return None

# 把上传的文件ID作为参数
def run_workflow(file_id, user, response_mode="blocking"):
    # API地址
    workflow_url = "https://api.dify.ai/v1/workflows/run"
    # 认证
    headers = {
        "Authorization""Bearer app-xxxxxxxxx",
        "Content-Type""application/json"
    }

    #第一个调用的demo里面有提到 参数再ipputs里面
    #type很重要
    #这里面其实也可以是网络图片transfer_method:remote_url
    data = {
        "inputs": {
            "orig_mail": {
                "transfer_method""local_file",#本地还是网络
                "upload_file_id": file_id, #文件ID
                "type""document"#类型
            }
        },
        "response_mode": response_mode,
        "user": user
    }

    try:
        print("运行工作流...")
        response = requests.post(workflow_url, headers=headers, json=data)
        if response.status_code == 200:
            print("工作流执行成功")
            return response.json()
        else:
            print(f"工作流执行失败,状态码: {response.status_code}")
            return {"status""error""message": f"Failed to execute workflow, status code: {response.status_code}"}
    except Exception as e:
        print(f"发生错误: {str(e)}")
        return {"status""error""message": str(e)}

# 使用示例
file_path = "{your_file_path}"
user = "difyuser"

# 上传文件
file_id = upload_file(file_path, user)
if file_id:
    # 文件上传成功,继续运行工作流
    result = run_workflow(file_id, user)
    print(result)
else:
    print("文件上传失败,无法执行工作流")


53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询