forked from langgenius/dify-plugin-sdks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
409 lines (353 loc) · 12.2 KB
/
Copy path__init__.py
File metadata and controls
409 lines (353 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
from decimal import Decimal
from enum import Enum
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, model_validator
from dify_plugin.core.documentation.schema_doc import docs
from dify_plugin.entities import I18nObject
@docs(
description="The default parameter name",
)
class DefaultParameterName(Enum):
"""
Enum class for parameter template variable.
"""
TEMPERATURE = "temperature"
TOP_P = "top_p"
TOP_K = "top_k"
PRESENCE_PENALTY = "presence_penalty"
FREQUENCY_PENALTY = "frequency_penalty"
MAX_TOKENS = "max_tokens"
MAX_COMPLETION_TOKENS = "max_completion_tokens"
RESPONSE_FORMAT = "response_format"
JSON_SCHEMA = "json_schema"
@classmethod
def value_of(cls, value: Any) -> "DefaultParameterName":
"""
Get parameter name from value.
:param value: parameter value
:return: parameter name
"""
for name in cls:
if name.value == value:
return name
raise ValueError(f"invalid parameter name {value}")
PARAMETER_RULE_TEMPLATE: dict[DefaultParameterName, dict] = {
DefaultParameterName.TEMPERATURE: {
"label": {
"en_US": "Temperature",
"zh_Hans": "温度",
},
"type": "float",
"help": {
"en_US": "Controls randomness. Lower temperature results in less random completions. As the temperature approaches zero, the model will become deterministic and repetitive. Higher temperature results in more random completions.", # noqa: E501
"zh_Hans": "温度控制随机性。较低的温度会导致较少的随机完成。随着温度接近零,模型将变得确定性和重复性。"
"较高的温度会导致更多的随机完成。",
},
"required": False,
"default": 0.0,
"min": 0.0,
"max": 1.0,
"precision": 2,
},
DefaultParameterName.TOP_P: {
"label": {
"en_US": "Top P",
"zh_Hans": "Top P",
},
"type": "float",
"help": {
"en_US": "Controls diversity via nucleus sampling: "
"0.5 means half of all likelihood-weighted options are considered.",
"zh_Hans": "通过核心采样控制多样性:0.5表示考虑了一半的所有可能性加权选项。",
},
"required": False,
"default": 1.0,
"min": 0.0,
"max": 1.0,
"precision": 2,
},
DefaultParameterName.TOP_K: {
"label": {
"en_US": "Top K",
"zh_Hans": "Top K",
},
"type": "int",
"help": {
"en_US": "Limits the number of tokens to consider for each step by keeping only the k most likely tokens.",
"zh_Hans": "通过只保留每一步中最可能的 k 个标记来限制要考虑的标记数量。",
},
"required": False,
"default": 50,
"min": 1,
"max": 100,
"precision": 0,
},
DefaultParameterName.PRESENCE_PENALTY: {
"label": {
"en_US": "Presence Penalty",
"zh_Hans": "存在惩罚",
},
"type": "float",
"help": {
"en_US": "Applies a penalty to the log-probability of tokens already in the text.",
"zh_Hans": "对文本中已有的标记的对数概率施加惩罚。",
},
"required": False,
"default": 0.0,
"min": 0.0,
"max": 1.0,
"precision": 2,
},
DefaultParameterName.FREQUENCY_PENALTY: {
"label": {
"en_US": "Frequency Penalty",
"zh_Hans": "频率惩罚",
},
"type": "float",
"help": {
"en_US": "Applies a penalty to the log-probability of tokens that appear in the text.",
"zh_Hans": "对文本中出现的标记的对数概率施加惩罚。",
},
"required": False,
"default": 0.0,
"min": 0.0,
"max": 1.0,
"precision": 2,
},
DefaultParameterName.MAX_TOKENS: {
"label": {
"en_US": "Max Tokens",
"zh_Hans": "最大标记",
},
"type": "int",
"help": {
"en_US": "Specifies the upper limit on the length of generated results. "
"If the generated results are truncated, you can increase this parameter.",
"zh_Hans": "指定生成结果长度的上限。如果生成结果截断,可以调大该参数。",
},
"required": False,
"default": 64,
"min": 1,
"max": 2048,
"precision": 0,
},
DefaultParameterName.MAX_COMPLETION_TOKENS: {
"label": {
"en_US": "Max Completion Tokens",
"zh_Hans": "最大完成标记",
},
"type": "int",
"help": {
"en_US": "Specifies the upper limit on the length of generated results. "
"If the generated results are truncated, you can increase this parameter.",
"zh_Hans": "指定生成结果长度的上限。如果生成结果截断,可以调大该参数。",
},
"required": False,
"default": 64,
"min": 1,
"max": 2048,
"precision": 0,
},
DefaultParameterName.RESPONSE_FORMAT: {
"label": {
"en_US": "Response Format",
"zh_Hans": "回复格式",
},
"type": "string",
"help": {
"en_US": "Set a response format, ensure the output from llm is a valid code block as possible, "
"such as JSON, XML, etc.",
"zh_Hans": "设置一个返回格式,确保llm的输出尽可能是有效的代码块,如JSON、XML等",
},
"required": False,
"options": ["JSON", "XML"],
},
DefaultParameterName.JSON_SCHEMA: {
"label": {
"en_US": "JSON Schema",
},
"type": "text",
"help": {
"en_US": "Set a response json schema will ensure LLM to adhere it.",
"zh_Hans": "设置返回的json schema,llm将按照它返回",
},
"required": False,
},
}
@docs(
description="The model type",
)
class ModelType(Enum):
"""
Enum class for model type.
"""
LLM = "llm"
TEXT_EMBEDDING = "text-embedding"
RERANK = "rerank"
SPEECH2TEXT = "speech2text"
MODERATION = "moderation"
TTS = "tts"
TEXT2IMG = "text2img"
@docs(
description="The fetch from",
)
class FetchFrom(Enum):
"""
Enum class for fetch from.
"""
PREDEFINED_MODEL = "predefined-model"
CUSTOMIZABLE_MODEL = "customizable-model"
@docs(
description="The model feature",
)
class ModelFeature(Enum):
"""
Enum class for llm feature.
"""
TOOL_CALL = "tool-call"
MULTI_TOOL_CALL = "multi-tool-call"
AGENT_THOUGHT = "agent-thought"
VISION = "vision"
STREAM_TOOL_CALL = "stream-tool-call"
DOCUMENT = "document"
VIDEO = "video"
AUDIO = "audio"
STRUCTURED_OUTPUT = "structured-output"
@docs(
description="The parameter type",
)
class ParameterType(Enum):
"""
Enum class for parameter type.
"""
FLOAT = "float"
INT = "int"
STRING = "string"
BOOLEAN = "boolean"
TEXT = "text"
@docs(
description="The model property key",
)
class ModelPropertyKey(Enum):
"""
Enum class for model property key.
"""
MODE = "mode"
CONTEXT_SIZE = "context_size"
MAX_CHUNKS = "max_chunks"
FILE_UPLOAD_LIMIT = "file_upload_limit"
SUPPORTED_FILE_EXTENSIONS = "supported_file_extensions"
MAX_CHARACTERS_PER_CHUNK = "max_characters_per_chunk"
DEFAULT_VOICE = "default_voice"
VOICES = "voices"
WORD_LIMIT = "word_limit"
AUDIO_TYPE = "audio_type"
MAX_WORKERS = "max_workers"
@docs(
description="The provider model",
)
class ProviderModel(BaseModel):
"""
Model class for provider model.
"""
model: str = Field(..., description="The model name")
label: I18nObject = Field(..., description="The label of the model")
model_type: ModelType = Field(..., description="The model type")
features: list[ModelFeature] | None = Field(default=None, description="The features of the model")
fetch_from: FetchFrom = Field(default=FetchFrom.PREDEFINED_MODEL, description="The fetch from")
model_properties: dict[ModelPropertyKey, Any] = Field(..., description="The model properties")
deprecated: bool = Field(default=False, description="Whether the model is deprecated")
model_config = ConfigDict(protected_namespaces=())
"""
use model as label
"""
@model_validator(mode="before")
@classmethod
def validate_label(cls, data: dict) -> dict:
if isinstance(data, dict) and not data.get("label"):
data["label"] = I18nObject(en_US=data["model"])
return data
@docs(
description="The parameter rule of the model",
)
class ParameterRule(BaseModel):
"""
Model class for parameter rule.
"""
name: str = Field(..., description="The name of the parameter")
use_template: str | None = Field(default=None, description="The template of the parameter")
label: I18nObject = Field(..., description="The label of the parameter")
type: ParameterType = Field(..., description="The type of the parameter")
help: I18nObject | None = Field(default=None, description="The help of the parameter")
required: bool = Field(default=False, description="Whether the parameter is required")
default: Any | None = Field(default=None, description="The default value of the parameter")
min: float | None = Field(default=None, description="The minimum value of the parameter")
max: float | None = Field(default=None, description="The maximum value of the parameter")
precision: int | None = Field(default=None, description="The precision of the parameter")
options: list[str] = Field(default=[], description="The options of the parameter")
@model_validator(mode="before")
@classmethod
def validate_label(cls, data: dict) -> dict:
if isinstance(data, dict):
# check if there is a template
if "use_template" in data:
try:
default_parameter_name = DefaultParameterName.value_of(data["use_template"])
default_parameter_rule = PARAMETER_RULE_TEMPLATE.get(default_parameter_name)
if not default_parameter_rule:
raise Exception(f"Invalid model parameter rule name {default_parameter_name}")
copy_default_parameter_rule = default_parameter_rule.copy()
copy_default_parameter_rule.update(data)
data = copy_default_parameter_rule
except ValueError:
pass
if not data.get("label"):
data["label"] = I18nObject(en_US=data["name"])
return data
@docs(
description="The price config",
)
class PriceConfig(BaseModel):
"""
Model class for pricing info.
"""
input: Decimal = Field(..., description="Input price")
output: Decimal | None = Field(default=None, description="Output price")
unit: Decimal = Field(..., description="Unit, e.g. 0.0001 -> per 10000 tokens")
currency: str = Field(..., description="Currency, e.g. USD")
@docs(
description="AI model entity",
)
class AIModelEntity(ProviderModel):
"""
Model class for AI model.
"""
parameter_rules: list[ParameterRule] = []
pricing: PriceConfig | None = None
class ModelUsage(BaseModel):
pass
class PriceType(Enum):
"""
Enum class for price type.
"""
INPUT = "input"
OUTPUT = "output"
class PriceInfo(BaseModel):
"""
Model class for price info.
"""
unit_price: Decimal = Field(..., description="The unit price, e.g. 0.000001")
unit: Decimal = Field(..., description="The unit, e.g. 1000")
total_amount: Decimal = Field(..., description="The total amount")
currency: str = Field(..., description="The currency, e.g. USD")
class BaseModelConfig(BaseModel):
provider: str
model: str
model_type: ModelType
model_config = ConfigDict(protected_namespaces=())
class EmbeddingInputType(Enum):
"""
Enum for embedding input type.
"""
DOCUMENT = "document"
QUERY = "query"