250810-OpenWebUI集成Dify應用

A. 最終效果

在這里插入圖片描述

B. 環境配置

配置并啟動Open-WebUI

  • 隨后瀏覽器訪問:http://localhost:8080
pip install open-webui
open-webui serve

配置并啟動Pipelines

  • Pipelines默認占用80端口
  • 相比于Docker的啟動方式,可以在相同的命令行中,查看pipelines 的日志
git clone https://github.com/open-webui/pipelines.git
cd pipelines
pip install -r requirements.txt
sh ./start.sh

配置并啟動Dify

  • dify/docker/docker-compose.yaml文件會包含很多image資源,默認只啟動其中的幾個
cd dify
cd docker
cp .env.example .env
docker compose up -d
  • 3min配置一個ChatFlow應用
  • 點擊LLM大模型模塊自定義System中的提示詞
  • 點擊預覽測試對話
  • 首次對外使用要點擊發布,再次應用更新要點擊發布

在這里插入圖片描述

  • API調用的測試代碼:
import requests
import jsonAPI_KEY = "app-w1pVOdGHpJ81OmqsZ2YIXyT8"  # 你的真實 API Keyurl = "http://localhost/v1/chat-messages"
headers = {"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json"
}payload = {"inputs": {},"query": "你的名字是什么?","response_mode": "streaming","conversation_id": "","user": "abc-123","files": [{"type": "image","transfer_method": "remote_url","url": "https://cloud.dify.ai/logo/logo-site.png"}]
}with requests.post(url, headers=headers, data=json.dumps(payload), stream=True) as r:for raw in r.iter_lines():if not raw:continueif not raw.startswith(b"data:"):continuedata_str = raw[len(b"data:"):].strip().decode("utf-8", errors="ignore")if data_str in ("[DONE]", ""):continuetry:event = json.loads(data_str)except json.JSONDecodeError:continueetype = event.get("event")if etype == "message":chunk = event.get("answer", "")if chunk:print(chunk, end="", flush=True)if etype in ("message_end", "workflow_finished"):print()break

C. 測試案例

  • 案例1: pipelines官方代碼
from typing import List, Union, Generator, Iterator
from schemas import OpenAIChatMessage
import subprocessclass Pipeline:def __init__(self):# Optionally, you can set the id and name of the pipeline.# Best practice is to not specify the id so that it can be automatically inferred from the filename, so that users can install multiple versions of the same pipeline.# The identifier must be unique across all pipelines.# The identifier must be an alphanumeric string that can include underscores or hyphens. It cannot contain spaces, special characters, slashes, or backslashes.# self.id = "python_code_pipeline"self.name = "Python Code Pipeline"passasync def on_startup(self):# This function is called when the server is started.print(">>>" * 80)print(f"on_startup:{__name__}")passasync def on_shutdown(self):# This function is called when the server is stopped.print("<<<" * 80)print(f"on_shutdown:{__name__}")passdef execute_python_code(self, code):try:result = subprocess.run(["python", "-c", code], capture_output=True, text=True, check=True)stdout = result.stdout.strip()return stdout, result.returncodeexcept subprocess.CalledProcessError as e:return e.output.strip(), e.returncodedef pipe(self, user_message: str, model_id: str, messages: List[dict], body: dict) -> Union[str, Generator, Iterator]:# This is where you can add your custom pipelines like RAG.print(f"pipe:{__name__}")print(messages)print(user_message)if body.get("title", False):print("Title Generation")return "Python Code Pipeline"else:# stdout, return_code = self.execute_python_code(user_message)stdout = "This is a test"return stdout
  • 案例2: dify自定義chatflow
# pipelines/python_code_pipeline/__init__.py
from typing import List, Union, Generator, Iterator
import os
import json
import requests
from requests.exceptions import RequestException, Timeout# 可選:Open-WebUI 的消息類型(不是必須)
# from schemas import OpenAIChatMessageclass Pipeline:def __init__(self):self.name = "Dify_ChatFlow"# 優先走環境變量,便于 Docker 與本地雙環境切換# 本機直接跑 ./start.sh 時,Dify 通常可用 http://localhost# 若 pipelines 用 Docker 跑,而 Dify 也在 Docker,則一般用 http://host.docker.internalself.DIFY_BASE_URL = "http://localhost"self.DIFY_API_KEY  = "app-w1pVOdGHpJ81OmqsZ2YIXyT8"   # !!! 改成你的 app key# Dify “對話機器人”的接口路徑(保持默認即可)self.DIFY_CHAT_MESSAGES_PATH = os.getenv("DIFY_CHAT_MESSAGES_PATH", "/v1/chat-messages")# 超時(秒)self.CONNECT_TIMEOUT = float(os.getenv("DIFY_CONNECT_TIMEOUT", "10"))self.READ_TIMEOUT    = float(os.getenv("DIFY_READ_TIMEOUT", "120"))async def on_startup(self):print(">>> Dify bridge ready:", self.DIFY_BASE_URL)async def on_shutdown(self):print("Dify bridge shutdown")# ------ 內部:把請求打到 Dify 并以生成器流式返回 ------def _dify_stream(self, query: str, conversation_id: str | None, user_id: str = "openwebui-user") -> Iterator[str]:url = f"{self.DIFY_BASE_URL.rstrip('/')}{self.DIFY_CHAT_MESSAGES_PATH}"headers = {"Authorization": f"Bearer {self.DIFY_API_KEY}","Content-Type": "application/json"}payload = {"inputs": {},"query": query,"response_mode": "streaming","conversation_id": conversation_id or "","user": user_id,# 如需帶圖:按需傳 files# "files": [{"type": "image","transfer_method": "remote_url","url": "https://cloud.dify.ai/logo/logo-site.png"}]}try:with requests.post(url,headers=headers,data=json.dumps(payload),stream=True,timeout=(self.CONNECT_TIMEOUT, self.READ_TIMEOUT),) as r:r.raise_for_status()for raw in r.iter_lines():if not raw:continueif not raw.startswith(b"data:"):continuedata_str = raw[len(b"data:"):].strip().decode("utf-8", errors="ignore")if data_str in ("[DONE]", ""):continuetry:event = json.loads(data_str)except json.JSONDecodeError:continueetype = event.get("event")if etype == "message":chunk = event.get("answer", "")if chunk:yield chunkelif etype in ("message_end", "workflow_finished"):breakexcept Timeout:yield "\n[Pipeline] Dify request timed out."except RequestException as e:yield f"\n[Pipeline] Dify request error: {e}"# ------ Open-WebUI 調用的主入口 ------def pipe(self, user_message: str, model_id: str, messages: List[dict], body: dict) -> Union[str, Generator, Iterator]:print("pipe:python_code_pipeline")# 忽略 Open-WebUI 的標題/標簽探測任務(它們會帶一大段“### Task:”提示詞)if body.get("title", False) or user_message.strip().startswith("### Task:"):# 返回一個簡單標題或空串即可,避免把系統提示詞發給 Difyreturn "" if not body.get("title") else "Python Code Pipeline"# 你也可以從 body 中取會話 id(如果前端傳了)conversation_id = body.get("conversation_id") or ""# 把用戶問題轉發到 Dify,并以流式返回return self._dify_stream(query=user_message, conversation_id=conversation_id)

D. 界面設置

如下操作即可

在這里插入圖片描述

E. 在主界面中使用

  • 看到左邊的對話記錄,就知道我測試多少次,不太懂,不太熟,但是坑又太多
  • 點贊、留言、轉發:謝謝

在這里插入圖片描述

References

  • open-webui/pipelines: Pipelines: Versatile, UI-Agnostic OpenAI-Compatible Plugin Framework
  • 哎…要會員,要收費、有點難:將Dify平臺開發的工作流集成到Open WebUI中_dify接入openwebui-CSDN博客
  • 雖熱官網實例代碼沒有跑通,但是還是要給開放的博主點贊:OpenWebUI通過pipeline對接dify的workflow-CSDN博客
  • The link between the workflow and open-webUI · langgenius/dify · Discussion #20982
  • The link between the workflow and open-webUI · langgenius/dify · Discussion #20982
  • [Feature]: Integrate with AI Workflow platforms such as Flowise & dify · open-webui/open-webui · Discussion #2023
  • langgenius/dify: Production-ready platform for agentic workflow development.

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/92524.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/92524.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/92524.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

day22|學習前端ts語言

抽象類&#xff0c;繼承。不能創造實例class類&#xff1a;屬性聲明&#xff0c;構造器&#xff0c;方法&#xff0c;實例繼承super&#xff08;&#xff09;override重寫父類繼承的方法聲明提升&#xff08;hoisting&#xff09;同一個js作用域內部&#xff0c;編譯階段把函數…

【網絡安全】CTF——[網鼎杯2018]Unfinish-SQL注入-二次注入

目錄 一、前言 二、環境 三、復現 3.1尋找注入點 3.2嘗試盲注 3.3正則限制 3.4腳本注入獲取flag 四、總結 一、前言 前兩天復現了一道CTF題目[網鼎杯 2018]Comment&#xff0c;今天繼續來學習一下SQL二次注入。 二、環境 BUUCTF在線評測 三、…

【langchain】如何給langchain提issue和提pull request?

什么是issue? 可以這么理解&#xff0c;bug是issue的子集。issue可以包含bug\feature\sercurity and others. https://github.com/langchain-ai/langchain/issues/32484 什么是pull request? 其實我真不是很理解&#xff0c;但不妨我來提pr https://github.com/langchain-ai/…

MySQL的存儲引擎:

目錄 InooDB引擎&#xff1a; MyISAM引擎&#xff1a; InooDB引擎與MyISAM存儲引擎的區別&#xff1a; Archive引擎&#xff1a; Blackhole引擎&#xff1a; CSV引擎&#xff1a; Memory引擎&#xff1a; Federated引擎&#xff1a; Merge引擎&#xff1a; NDB引擎&a…

Mock與Stub

一、核心概念與差異對比特性MockStub核心目的驗證對象間的交互行為提供預定義的固定響應驗證重點方法調用次數、參數、順序不關注調用過程&#xff0c;只關注結果行為模擬可編程的智能模擬靜態的簡單響應適用場景驗證協作關系隔離依賴、提供固定數據復雜性較高&#xff08;需要…

香港服務器容器網絡插件的多節點通信性能基準測試

香港服務器容器網絡插件的多節點通信性能基準測試在云計算和容器化技術快速發展的今天&#xff0c;香港服務器因其優越的地理位置和網絡環境&#xff0c;成為眾多企業部署容器服務的首選。本文將深入探討香港服務器環境下容器網絡插件的多節點通信性能&#xff0c;通過詳實的基…

Vue3 學習教程,從入門到精通,Vue 3 全局 API 語法知識點及案例詳解(32)

Vue 3 全局 API 語法知識點及案例詳解 Vue 3 提供了豐富的全局 API&#xff0c;用于創建應用實例、注冊全局組件、指令、插件等。以下將詳細介紹 Vue 3 的主要全局 API&#xff0c;并結合詳細的案例代碼進行說明。每個案例代碼都包含中文注釋&#xff0c;幫助初學者更好地理解…

UE5多人MOBA+GAS 41、制作一個飛彈,添加準心索敵

文章目錄添加新角色&#xff08;不寫了&#xff09;創建一個發射技能創建一個飛彈類添加擊中特效添加準星UI獲取瞄準目標添加新角色&#xff08;不寫了&#xff09; 將原本的機器人藍圖改為BP_PlayerCharacter&#xff0c;以此創建子藍圖 創建動畫藍圖模板&#xff08;具體就…

解決渲染抖動與滾動錨點定位不準確問題的方法與經驗分享

場景描述&#xff1a;React 虛擬列表&#xff08;Virtualized List&#xff09;是當我們在處理大列表時&#xff0c;為了提升性能而采用的一種技術。然而在實現過程中&#xff0c;可能會遇到渲染抖動問題以及滾動錨點定位不準確的問題。??解決方案&#xff1a;React虛擬列表實…

OpenAI 時隔多年再開源!GPT-OSS 120B/20B 發布,支持本地部署,消費級 GPU 即可運行

OpenAI 近期做出了一項令人矚目的戰略轉變&#xff1a;宣布推出兩款開放權重&#xff08;Open Weight&#xff09; 語言模型 GPT-OSS-120B 和 GPT-OSS-20B。這不僅是其自 GPT-2 之后首次開源模型&#xff0c;更關鍵的是&#xff0c;這兩款模型特別針對消費級硬件進行了深度優化…

MySQL高可用方案之MySQL Group Replication高可用架構搭建完全指南

MySQL Group Replication高可用架構搭建完全指南 前言 在當今互聯網應用中,數據庫高可用性已成為系統設計的核心需求。MySQL作為最流行的開源關系型數據庫之一,其高可用解決方案備受關注。MySQL Group Replication是MySQL官方推出的原生高可用解決方案,它基于Paxos協議實現…

網站SSL證書到期如何更換?簡單完整操作指南

----------------------------------------------------------------------------------------------- 這是我在我的網站中截取的文章&#xff0c;有更多的文章歡迎來訪問我自己的博客網站rn.berlinlian.cn&#xff0c;這里還有很多有關計算機的知識&#xff0c;歡迎進行留言或…

Spring Boot 開發三板斧:POM 依賴、注解與配置管理

引言 Spring Boot 是一個功能強大且廣受歡迎的框架&#xff0c;用于快速構建基于 Spring 的應用。它通過簡化配置和自動化管理&#xff0c;幫助開發者專注于業務邏輯的實現。然而&#xff0c;要想高效地開發 Spring Boot 應用&#xff0c;掌握以下三個關鍵點至關重要&#xff1…

kubernetes安裝搭建

個人博客站—運維鹿:http://www.kervin24.top/ CSDN博客—做個超努力的小奚&#xff1a; https://blog.csdn.net/qq_52914969?typeblog 一、kubernetes介紹 Kubernetes本質是一組服務器集群&#xff0c;它可以在集群的每個節點上運行特定的程序&#xff0c;來對節點中的容…

MySQL高可用方案之MySQL InnoDB Cluster高可用架構實戰指南:從零搭建到生產部署

MySQL InnoDB Cluster高可用架構實戰指南:從零搭建到生產部署 一、引言:為什么選擇MySQL InnoDB Cluster 在當今數據驅動的商業環境中,數據庫高可用性已成為企業IT基礎設施的核心需求。MySQL作為全球最受歡迎的開源關系型數據庫,其高可用解決方案備受關注。而MySQL InnoD…

祝融號無線電工作頻段

前面深入查證了旅行者1號的無線電工作頻段&#xff1a; 旅行者1號無線電工作頻段-CSDN博客 下面嘗試查證我國祝融號無線電工作頻段。 一、百度百科 來自百度百科&#xff1a; 我注意到一條關鍵信息&#xff1a; 這說明祝融號在國際上是有合作的&#xff0c;而不是我們國家單…

Kafka生產者相關原理

前言前面已經介紹了Kafka的架構知識并引出了Kafka的相關專業名稱進行解釋這次分享一下Kafka對生產者發送消息進行處理的運行機制和原理生產者發送消息兩種方式同步發送消息程序中線程執行完消息發送操作之后會等待Kafka的消息回應ack默認等待30秒沒有回應就會拋出異常等待時間和…

Python 獲取對象信息的所有方法

在 Python 里&#xff0c;我們經常需要檢查一個對象的類型、屬性、方法&#xff0c;甚至它的源碼。這對調試、學習和動態編程特別有用。今天我們就來聊聊獲取對象信息的常見方法&#xff0c;按由淺入深的順序來學習。 參考文章&#xff1a;Python 獲取對象信息 | 簡單一點學習…

vuhub Beelzebub靶場攻略

靶場下載&#xff1a; 下載地址&#xff1a;https://download.vulnhub.com/beelzebub/Beelzebub.zip 靶場攻略&#xff1a; 主機發現&#xff1a; nmap 192.168.163.1/24 端口掃描&#xff1a; nmap -p-65535 -A 192.168.163.152 發現沒有額外端口。 頁面掃描&#xff1…

開啟單片機

前言&#xff1a;為未來拼搏的第n天&#xff0c;從單片機開始。為什么要學習單片機呢&#xff0c;單片機的工作涉及范圍及其廣如&#xff1a;消費電子&#xff0c;游戲機音響&#xff1b;工業控制&#xff1a;機器人控制&#xff1b;醫療設備&#xff0c;通信設備&#xff0c;物…