Open WebUI

Open WebUI是一个可扩展、功能丰富且用户友好的_自托管人工智能平台_,旨在完全离线运行。

函数就像是Open WebUI的插件。我们可以创建一个自定义的管道函数,在将结果返回给用户之前,通过调用Flowise预测API来处理输入并生成响应。通过这种方式,可以在Open WebUI中使用Flowise。

设置

  1. 首先,请确保Open WebUI已启动并运行,您可以参考快速入门指南。在左下方,点击您的个人资料并选择管理员面板

  1. 打开“函数”选项卡,并添加一个新函数。

  1. 命名该函数,并添加以下代码:

python """ 标题:OpenWebUI的Flowise集成 要求:

  • Flowise API URL(通过FLOWISE_API_URL设置)

  • Flowise API密钥(通过FLOWISE_API_KEY设置) """

从pydantic导入BaseModel和Field from typing import Optional, Dict, Any, List, Union, Generator, Iterator 导入requests库 导入json库 导入操作系统

类 Pipe: 类 Valves(BaseModel): flowise_url: str = Field( default=os.getenv("FLOWISE_API_URL", ""),, description="Flowise URL",, ) flowise_api_key: str = Field( default=os.getenv("FLOWISE_API_KEY", ""),, description="用于身份验证的Flowise API密钥",, )

定义 __init__ 函数(构造器):
    self.type = "manifold"
    self.id = "flowise_chat"
    self.valves = self.Valves()

    # 验证所需设置
    如果 self.valves.flowise_url 不存在:
        打印(
            “⚠️ 请使用FLOWISE_API_URL环境变量设置您的Flowise URL”
        )
    如果 self.valves.flowise_api_key 不存在:
        打印(
            “⚠️ 请使用FLOWISE_API_KEY环境变量设置您的Flowise API密钥”
        )

def pipes(self):
    如果self.valves有flowise_api_key和flowise_url:
        尝试:
            头信息 = {
                "Authorization": f"Bearer {self.valves.flowise_api_key}",,
                "Content-Type": "application/json",,
            }

            r = requests.get(
                f"{self.valves.flowise_url}/api/v1/chatflows?type=AGENTFLOW",,
                headers=headers,,
            )
            模型 = r.json()
            返回 [
                {
                    "id": model["id"],,
                    "name": model["name"],,
                }
                对于模型中的每个模型
            ]

        除了 Exception 异常(用 e 表示):
            返回 [
                {
                    "id": "错误",,
                    "name": str(e),,
                },
            ]
    否则:
        返回 [
            {
                "id": "错误",,
                "name": "未提供API密钥。",,
            },
        ]

def _process_message_content(self, message: dict) -> str:
    “处理消息内容,目前处理文本”
    如果 message.get("content") 是列表类型:
        已处理内容 = []
        对于message["content"]中的每个项目:
            如果 item["type"] 为 "text":
                已处理内容.append(item["text"])
        返回 " ".join(已处理内容)
    返回 message.get("content", "")

def pipe(
    self, body: dict, __user__: Optional[dict] = None, __metadata__: dict = None
):
    尝试:
        stream_enabled = body.get("stream", True)
        会话ID = (__metadata__ 或 {}).get("chat_id") 或 "owui-session"
        # 模型可以是“flowise.<id>”或仅是“<id>”
        model_name = body.get("model", "")
        dot = model_name.find(".")
        如果点号(dot)不为-1,则model_id等于model_name中点号(dot)后的部分;否则,model_id等于model_name

        messages = body.get("messages") or []
        如果没有消息:
            引发异常(Exception)(“请求体中未找到消息”)
        问题 = self._process_message_content(messages[-1])

        数据 = {
            "question": 问题,
            "overrideConfig": {"sessionId": session_id},,
            "streaming": 是否启用流媒体功能,
        }

        headers = {
            "Authorization": f"Bearer {self.valves.flowise_api_key}",,
            "Content-Type": "application/json",,
            "Accept": "text/event-stream"(如果stream_enabled为真)否则为"application/json",
        }

        url = f"{self.valves.flowise_url}/api/v1/prediction/{model_id}"
        使用requests库的post方法
            url, json=data, headers=headers, stream=stream_enabled, timeout=60
        作为r:
            r.raise_for_status()

            如果stream_enabled为真:
                # 确保SSE的正确解码(防止出现’等字符)
                r.encoding = "utf-8"

                对于r.iter_lines(decode_unicode=True)中的raw_line:
                    如果没有原始行:

继续 行 = raw_line.strip()

                    # 跳过保持活动状态或非数据字段
                    如果不是以“data:”开头:

继续

                    有效载荷 = line[5:].strip()
                    如果有效载荷为“[DONE]”或“[DONE]”之一:

打破

                    # Flowise 通常会发送 {"event": "token", "data": "..."}
                    尝试:
                        obj = json.loads(payload)
                    除了json.JSONDecodeError:
                        偶尔会收到纯文本消息——还是照常发送吧
                        如果存在有效载荷:
                            产生有效载荷

继续

                    如果 obj 是一个字典
                        如果对象obj的属性“event”等于“token”:
                            token = obj.get("data") 或者 ""
                            如果存在token:
                                产出代币
                        否则:
                            # 某些版本会发送{"data":{"text":"..."}}
                            数据字段 = 对象.获取("数据")
                            如果数据字段(data_field)是字典(dict)类型:
                                文本 = 数据字段.get("文本")
                                如果文本存在:
                                    产出文本
                返回 # 结束流式传输

            # 非流式回退
            resp = r.json()
            返回(
                resp.get("text") 或者 (resp.get("data") 或者 {}).get("text", "") 或者 ""
            )

    除了requests.HTTPError异常(用http_err表示)之外:
        尝试:
            细节 = http_err.response.text[:500]
        除了 Exception:
            detail = ""
        返回 f"来自Flowise的HTTP错误:{http_err.response.status_code} {detail}"
    除了 Exception 异常(用 e 表示):
        返回 f"Flowise 管道出错:{e}"

4. 保存函数后,启用它,并点击设置按钮,输入您的Flowise URL和Flowise API Key:

<figure><img src="../../.gitbook/assets/image (2) (1) (1) (1).png" alt="" width="563"><figcaption></figcaption></figure>

<figure><img src="../../.gitbook/assets/image (3) (1) (1).png" alt="" width="431"><figcaption></figcaption></figure>

5. 现在,当您刷新并点击“新建聊天”时,您将能够看到流程列表。您可以修改代码以显示:

* 仅限Agentflows V2版本:`f"{self.valves.flowise_url}/api/v1/chatflows?type=AGENTFLOW"`
* 仅限聊天流程:`f"{self.valves.flowise_url}/api/v1/chatflows?type=CHATFLOW"`
* 仅助手:`f"{self.valves.flowise_url}/api/v1/chatflows?type=ASSISTANT"`

<figure><img src="../../.gitbook/assets/image (4) (1) (1).png" alt=""> <figcaption></figcaption></figure>

6. 测试:

<figure><img src="../../.gitbook/assets/image (5) (1).png" alt=""><figcaption></figcaption></figure>

Last updated