卜笑 发表于 2025-6-1 18:16:49

Dify使用事项

安装部署


[*]内网环境下以docker形式部署

[*]需在外网环境下通过docker部署完成,具体参考:https://docs.dify.ai/zh-hans/getting-started/install-self-hosted/docker-compose
安装完成后通过docker ps能看到有以下容器:


[*]9个容器逐个打包
# 举例
docker save -o docker-db-1.tar postgres:15-alpine
[*]9个压缩包和源码文件迁移到内网机器,需确保docker和docker compose均已安装
# 举例
docker load -i docker-db-1.tar
[*]执行docker images查看镜像,若名称有变化,则需要在docker/docker-compose.yaml中修改
[*]在源码docker文件夹下执行docker compose up -d启动服务


[*]源码部署
源码部署可能会出现跨域问题

[*]docker部署,如何修改前端?
在源码部署中修改前端代码,npm run build编译后,生成.next文件,将其打包更新到docker-web-1容器中,重启容器即可
docker cp /path/on/host my_container:/path/in/container
docker restart docker-web-1

[*]源码部署时,前端代码编译时可能会出错,需要重新下载依赖
rm -rf node_modules
rm -f package-lock.json
npm cache clean --force
npm installAPI调用工作流


[*]字符串输出
【开始】输入中字段类型为文本或段落时:

'''
python
'''

import requests
import json

API_KEY = "******"
text_input = '''
A: 嗨,亲爱的!今天过得怎么样?
B: 嗨,亲爱的!今天过得还不错,谢谢关心。你今天工作忙吗?
'''

# 确保变量名与 workflow 中定义的变量一致
data = {
    "inputs": {
      "input": text_input# 假设 workflow 中定义的变量名为 "input"
    },
    "response_mode": "blocking",        # 这里是块模式输出
    "user": "abc-123"
}

url = "https://api.dify.ai/v1/workflows/run"
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

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

if response.status_code == 200:
    print("workflow 执行成功")
    print("响应内容:", response.json()['data']['outputs']['output'])
else:
    print(f"workflow 执行失败,状态码: {response.status_code}")
    print("错误信息:", response.text)

[*]文件上传
【开始】输入中字段类型为单文件时:

'''
python
'''
import requests,json

class DifyAPI:
    def __init__(self, api_key):
      self.api_key = api_key
      self.upload_url = "https://api.dify.ai/v1/files/upload"
      self.workflow_url = "https://api.dify.ai/v1/workflows/run"

    def upload_file(self, local_file_path, user):
      """
      上传文件
      """
      # 替换为你的实际文件类型
      file_type = 'application/txt'# 可以根据实际情况修改为 jpeg、jpg、webp、gif 等

      # 设置请求头
      headers = {
            'Authorization': f'Bearer {self.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(self.upload_url, headers=headers, files=files, data=data)

      # 检查响应状态码
      if response.status_code == 201:
            print("文件上传成功")
            print(json.dumps(response.json(),indent=4))
            file_id = response.json()['id']
            return file_id
      else:
            print(f"文件上传失败,状态码: {response.status_code}")
            print(response.text)
            return None

    def run_workflow(self, file_id, user, response_mode="blocking"):
      """
      运行工作流
      """
      # 认证
      headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
      }

      # 构建请求数据
      data = {
            "inputs": {
                "file": {
                  "transfer_method": "local_file",# 本地还是网络
                  "upload_file_id": file_id,# 文件ID
                  "type": "document"# 类型
                }
            },
            "response_mode": response_mode,
            "user": user
      }

      try:
            print("\n运行工作流...")
            response = requests.post(self.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)}

# 使用示例
if __name__ == "__main__":
    api_key = "*******"
    file_path = "1.txt"        # 这里上传的是text文件
    user = "difyuser"

    dify_api = DifyAPI(api_key)

    # 上传文件
    file_id = dify_api.upload_file(file_path, user)
    if file_id:
      # 文件上传成功,继续运行工作流
      result = dify_api.run_workflow(file_id, user)
      print(json.dumps(result, indent=4, ensure_ascii=False))
      # print(result)
    else:
      print("文件上传失败,无法执行工作流")参考学习


[*]https://personel-zhouxinle888-a66353926f9185cff28f2bd374a5c3a9dd89d5206.gitlab.io/dify/dify-1.html
[*]https://docs.dify.ai/zh-hans

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Dify使用事项