跳到主要内容

🔄 Valves 与 UserValves

Valves 与 UserValves

Valves 和 UserValves 用于允许用户提供动态详细信息,例如 API 密钥或配置选项。它们将在给定功能的 GUI 菜单中创建可填充字段或布尔开关。它们总是可选的,但强烈建议使用。

因此,Valves 和 UserValves 类可以在 PipePipelineFilterTools 类中定义。

Valves 仅由管理员通过工具或函数菜单进行配置。另一方面,UserValves 可以由任何用户直接从聊天会话中配置。

注释示例

from pydantic import BaseModel, Field
from typing import Literal

# Define and Valves
class Filter:
# Notice the current indentation: Valves and UserValves must be declared as
# attributes of a Tools, Filter or Pipe class. Here we take the
# example of a Filter.
class Valves(BaseModel):
# Valves and UserValves inherit from pydantic's BaseModel. This
# enables complex use cases like model validators etc.
test_valve: int = Field( # Notice the type hint: it is used to
# choose the kind of UI element to show the user (buttons,
# texts, etc).
default=4,
description="A valve controlling a numberical value"
# required=False, # you can enforce fields using True
)
# To give the user the choice between multiple strings, you can use Literal from typing:
choice_option: Literal["choiceA", "choiceB"] = Field(
default="choiceA",
description="An example of a multi choice valve",
)
priority: int = Field(
default=0,
description="Priority level for the filter operations. Lower values are passed through first"
)
# The priority field is optional but if present will be used to
# order the Filters.
pass
# Note that this 'pass' helps for parsing and is recommended.

# UserValves are defined the same way.
class UserValves(BaseModel):
test_user_valve: bool = Field(
default=False, description="A user valve controlling a True/False (on/off) switch"
)
pass

def __init__(self):
self.valves = self.Valves()
# Because they are set by the admin, they are accessible directly
# upon code execution.
pass

# The inlet method is only used for Filter but the __user__ handling is the same
def inlet(self, body: dict, __user__: dict):
# Because UserValves are defined per user they are only available
# on use.
# Note that although __user__ is a dict, __user__["valves"] is a
# UserValves object. Hence you can access values like that:
test_user_valve = __user__["valves"].test_user_valve
# Or:
test_user_valve = dict(__user__["valves"])["test_user_valve"]
# But this will return the default value instead of the actual value:
# test_user_valve = __user__["valves"]["test_user_valve"] # Do not do that!