Dify to OpenAI API 适配器

450 阅读2分钟

最近体验了 Dify 和 Open-WebUI,发现它们各有优点。如果能把 Dify 的 API 转换为 OpenAI API,就可以让 Open-WebUI 等前端工具无缝对接 Dify,扩展使用场景。经过网上查找,没有发现拿来即用的,所以我用 AI 写一个项目,核心原理是将 Dify 的接口协议转为兼容 OpenAI 的 API 格式。在 Dify 中,每个 App 会分配一个专用的 API Key,因此可以把 OpenAI 的模型接口和 Dify 后端进行一一映射,从而实现在 Open-WebUI 上调用 Dify 的能力。

Dify to OpenAI API 适配器

将 Dify 应用转换为 OpenAI 兼容的 API 接口,支持模型映射、流式响应、图片、会话。

功能特性

  • ✅ 支持基于模型的映射机制
  • ✅ 兼容 OpenAI ChatGPT API 格式
  • ✅ 支持流式和阻塞响应模式
  • ✅ 自动检测 Dify 应用类型(Chatbot/Agent/Workflow)
  • ✅ 支持多个 Dify 应用映射
  • 智能会话管理:支持多轮对话上下文记忆
  • 多模型会话隔离:不同模型间的对话相互独立
  • 自动会话清理:防止内存泄漏

编辑 config.json,添加你的 Dify 应用配置:

{
  "model_mappings": {
    "example-chatbot": {
      "dify_api_key": "app-YOUR_CHATBOT_API_KEY",
      "dify_base_url": "http://your-dify-server:port",
      "app_name": "智能聊天助手",
      "description": "标准聊天应用,支持阻塞和流式模式",
      "app_type": "chatbot",
      "supports_streaming": true,
      "supports_blocking": true,
      "default_mode": "blocking"
    },
    "example-agent": {
      "dify_api_key": "app-YOUR_AGENT_API_KEY",
      "dify_base_url": "http://your-dify-server:port",
      "app_name": "智能代理助手",
      "description": "Agent 应用,仅支持流式模式",
      "app_type": "agent",
      "supports_streaming": true,
      "supports_blocking": false,
      "default_mode": "streaming"
    }
  },
  "settings": {
    "port": 3000,
    "host": "0.0.0.0",
    "default_model": "example-chatbot",
    "enable_streaming": true,
    "max_concurrent_requests": 10,
    "request_timeout": 30000,
    "retry_attempts": 3
  }
}

Docker 启动

# 运行容器
docker run -d -p 3000:3000 -v $(pwd)/config.json:/app/config.json chengmq/dify-to-openai-adapter:latest

API地址:http://localhost:3000/v1

源码运行

参考GitHub仓库:github.com/quming398/d…