model_declaration.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863
  1. package plugin_entities
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/go-playground/locales/en"
  6. ut "github.com/go-playground/universal-translator"
  7. "github.com/go-playground/validator/v10"
  8. en_translations "github.com/go-playground/validator/v10/translations/en"
  9. "github.com/langgenius/dify-plugin-daemon/internal/utils/log"
  10. "github.com/langgenius/dify-plugin-daemon/internal/utils/mapping"
  11. "github.com/langgenius/dify-plugin-daemon/internal/utils/parser"
  12. "github.com/langgenius/dify-plugin-daemon/pkg/validators"
  13. "github.com/shopspring/decimal"
  14. "gopkg.in/yaml.v3"
  15. )
  16. type ModelType string
  17. const (
  18. MODEL_TYPE_LLM ModelType = "llm"
  19. MODEL_TYPE_TEXT_EMBEDDING ModelType = "text-embedding"
  20. MODEL_TYPE_RERANKING ModelType = "rerank"
  21. MODEL_TYPE_SPEECH2TEXT ModelType = "speech2text"
  22. MODEL_TYPE_MODERATION ModelType = "moderation"
  23. MODEL_TYPE_TTS ModelType = "tts"
  24. MODEL_TYPE_TEXT2IMG ModelType = "text2img"
  25. )
  26. func isModelType(fl validator.FieldLevel) bool {
  27. value := fl.Field().String()
  28. switch value {
  29. case string(MODEL_TYPE_LLM),
  30. string(MODEL_TYPE_TEXT_EMBEDDING),
  31. string(MODEL_TYPE_RERANKING),
  32. string(MODEL_TYPE_SPEECH2TEXT),
  33. string(MODEL_TYPE_MODERATION),
  34. string(MODEL_TYPE_TTS),
  35. string(MODEL_TYPE_TEXT2IMG):
  36. return true
  37. }
  38. return false
  39. }
  40. type ModelProviderConfigurateMethod string
  41. const (
  42. CONFIGURATE_METHOD_PREDEFINED_MODEL ModelProviderConfigurateMethod = "predefined-model"
  43. CONFIGURATE_METHOD_CUSTOMIZABLE_MODEL ModelProviderConfigurateMethod = "customizable-model"
  44. )
  45. func isModelProviderConfigurateMethod(fl validator.FieldLevel) bool {
  46. value := fl.Field().String()
  47. switch value {
  48. case string(CONFIGURATE_METHOD_PREDEFINED_MODEL),
  49. string(CONFIGURATE_METHOD_CUSTOMIZABLE_MODEL):
  50. return true
  51. }
  52. return false
  53. }
  54. type ModelParameterType string
  55. const (
  56. PARAMETER_TYPE_FLOAT ModelParameterType = "float"
  57. PARAMETER_TYPE_INT ModelParameterType = "int"
  58. PARAMETER_TYPE_STRING ModelParameterType = "string"
  59. PARAMETER_TYPE_BOOLEAN ModelParameterType = "boolean"
  60. PARAMETER_TYPE_TEXT ModelParameterType = "text"
  61. )
  62. func isModelParameterType(fl validator.FieldLevel) bool {
  63. value := fl.Field().String()
  64. switch value {
  65. case string(PARAMETER_TYPE_FLOAT),
  66. string(PARAMETER_TYPE_INT),
  67. string(PARAMETER_TYPE_STRING),
  68. string(PARAMETER_TYPE_BOOLEAN),
  69. string(PARAMETER_TYPE_TEXT):
  70. return true
  71. }
  72. return false
  73. }
  74. type ModelParameterRule struct {
  75. Name string `json:"name" yaml:"name" validate:"required,lt=256"`
  76. UseTemplate *string `json:"use_template" yaml:"use_template" validate:"omitempty,lt=256"`
  77. Label *I18nObject `json:"label" yaml:"label" validate:"omitempty"`
  78. Type *ModelParameterType `json:"type" yaml:"type" validate:"omitempty,model_parameter_type"`
  79. Help *I18nObject `json:"help" yaml:"help" validate:"omitempty"`
  80. Required bool `json:"required" yaml:"required"`
  81. Default *any `json:"default" yaml:"default" validate:"omitempty,is_basic_type"`
  82. Min *float64 `json:"min" yaml:"min" validate:"omitempty"`
  83. Max *float64 `json:"max" yaml:"max" validate:"omitempty"`
  84. Precision *int `json:"precision" yaml:"precision" validate:"omitempty"`
  85. Options []string `json:"options" yaml:"options" validate:"omitempty,dive,lt=256"`
  86. }
  87. type DefaultParameterName string
  88. const (
  89. TEMPERATURE DefaultParameterName = "temperature"
  90. TOP_P DefaultParameterName = "top_p"
  91. TOP_K DefaultParameterName = "top_k"
  92. PRESENCE_PENALTY DefaultParameterName = "presence_penalty"
  93. FREQUENCY_PENALTY DefaultParameterName = "frequency_penalty"
  94. MAX_TOKENS DefaultParameterName = "max_tokens"
  95. RESPONSE_FORMAT DefaultParameterName = "response_format"
  96. JSON_SCHEMA DefaultParameterName = "json_schema"
  97. )
  98. var PARAMETER_RULE_TEMPLATE = map[DefaultParameterName]ModelParameterRule{
  99. TEMPERATURE: {
  100. Label: &I18nObject{
  101. EnUS: "Temperature",
  102. ZhHans: "温度",
  103. JaJp: "温度",
  104. PtBr: "Temperatura",
  105. },
  106. Type: parser.ToPtr(PARAMETER_TYPE_FLOAT),
  107. Help: &I18nObject{
  108. EnUS: "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.",
  109. ZhHans: "温度控制随机性。较低的温度会导致较少的随机完成。随着温度接近零,模型将变得确定性和重复性。较高的温度会导致更多的随机完成。",
  110. JaJp: "温度はランダム性を制御します。温度が低いほどランダムな完成が少なくなります。温度がゼロに近づくと、モデルは決定論的で繰り返しになります。温度が高いほどランダムな完成が多くなります。",
  111. PtBr: "A temperatura controla a aleatoriedade. Menores temperaturas resultam em menos conclusões aleatórias. À medida que a temperatura se aproxima de zero, o modelo se tornará determinístico e repetitivo. Temperaturas mais altas resultam em mais conclusões aleatórias.",
  112. },
  113. Required: false,
  114. Default: parser.ToPtr(any(0.0)),
  115. Min: parser.ToPtr(0.0),
  116. Max: parser.ToPtr(1.0),
  117. Precision: parser.ToPtr(2),
  118. },
  119. TOP_P: {
  120. Label: &I18nObject{
  121. EnUS: "Top P",
  122. ZhHans: "Top P",
  123. JaJp: "Top P",
  124. PtBr: "Top P",
  125. },
  126. Type: parser.ToPtr(PARAMETER_TYPE_FLOAT),
  127. Help: &I18nObject{
  128. EnUS: "Controls diversity via nucleus sampling: 0.5 means half of all likelihood-weighted options are considered.",
  129. ZhHans: "通过核心采样控制多样性:0.5表示考虑了一半的所有可能性加权选项。",
  130. JaJp: "核サンプリングを通じて多様性を制御します:0.5は、すべての可能性加权オプションの半分を考慮します。",
  131. PtBr: "Controla a diversidade via amostragem de núcleo: 0.5 significa que metade das opções com maior probabilidade são consideradas.",
  132. },
  133. Required: false,
  134. Default: parser.ToPtr(any(1.0)),
  135. Min: parser.ToPtr(0.0),
  136. Max: parser.ToPtr(1.0),
  137. Precision: parser.ToPtr(2),
  138. },
  139. TOP_K: {
  140. Label: &I18nObject{
  141. EnUS: "Top K",
  142. ZhHans: "Top K",
  143. },
  144. Type: parser.ToPtr(PARAMETER_TYPE_INT),
  145. Help: &I18nObject{
  146. EnUS: "Limits the number of tokens to consider for each step by keeping only the k most likely tokens.",
  147. ZhHans: "通过只保留每一步中最可能的 k 个标记来限制要考虑的标记数量。",
  148. },
  149. Required: false,
  150. Default: parser.ToPtr(any(50)),
  151. Min: parser.ToPtr(1.0),
  152. Max: parser.ToPtr(100.0),
  153. Precision: parser.ToPtr(0),
  154. },
  155. PRESENCE_PENALTY: {
  156. Label: &I18nObject{
  157. EnUS: "Presence Penalty",
  158. ZhHans: "存在惩罚",
  159. JaJp: "存在ペナルティ",
  160. PtBr: "Penalidade de presença",
  161. },
  162. Type: parser.ToPtr(PARAMETER_TYPE_FLOAT),
  163. Help: &I18nObject{
  164. EnUS: "Applies a penalty to the log-probability of tokens already in the text.",
  165. ZhHans: "对文本中已有的标记的对数概率施加惩罚。",
  166. JaJp: "テキストに既に存在するトークンの対数確率にペナルティを適用します。",
  167. PtBr: "Aplica uma penalidade à probabilidade logarítmica de tokens já presentes no texto.",
  168. },
  169. Required: false,
  170. Default: parser.ToPtr(any(0.0)),
  171. Min: parser.ToPtr(0.0),
  172. Max: parser.ToPtr(1.0),
  173. Precision: parser.ToPtr(2),
  174. },
  175. FREQUENCY_PENALTY: {
  176. Label: &I18nObject{
  177. EnUS: "Frequency Penalty",
  178. ZhHans: "频率惩罚",
  179. JaJp: "頻度ペナルティ",
  180. PtBr: "Penalidade de frequência",
  181. },
  182. Type: parser.ToPtr(PARAMETER_TYPE_FLOAT),
  183. Help: &I18nObject{
  184. EnUS: "Applies a penalty to the log-probability of tokens that appear in the text.",
  185. ZhHans: "对文本中出现的标记的对数概率施加惩罚。",
  186. JaJp: "テキストに出現するトークンの対数確率にペナルティを適用します。",
  187. PtBr: "Aplica uma penalidade à probabilidade logarítmica de tokens que aparecem no texto.",
  188. },
  189. Required: false,
  190. Default: parser.ToPtr(any(0.0)),
  191. Min: parser.ToPtr(0.0),
  192. Max: parser.ToPtr(1.0),
  193. Precision: parser.ToPtr(2),
  194. },
  195. MAX_TOKENS: {
  196. Label: &I18nObject{
  197. EnUS: "Max Tokens",
  198. ZhHans: "最大标记",
  199. JaJp: "最大トークン",
  200. PtBr: "Máximo de tokens",
  201. },
  202. Type: parser.ToPtr(PARAMETER_TYPE_INT),
  203. Help: &I18nObject{
  204. EnUS: "Specifies the upper limit on the length of generated results. If the generated results are truncated, you can increase this parameter.",
  205. ZhHans: "指定生成结果长度的上限。如果生成结果截断,可以调大该参数。",
  206. JaJp: "生成結果の長さの上限を指定します。生成結果が切り捨てられた場合は、このパラメータを大きくすることができます。",
  207. PtBr: "Especifica o limite superior para o comprimento dos resultados gerados. Se os resultados gerados forem truncados, você pode aumentar este parâmetro.",
  208. },
  209. Required: false,
  210. Default: parser.ToPtr(any(64)),
  211. Min: parser.ToPtr(1.0),
  212. Max: parser.ToPtr(2048.0),
  213. Precision: parser.ToPtr(0),
  214. },
  215. RESPONSE_FORMAT: {
  216. Label: &I18nObject{
  217. EnUS: "Response Format",
  218. ZhHans: "回复格式",
  219. JaJp: "応答形式",
  220. PtBr: "Formato de resposta",
  221. },
  222. Type: parser.ToPtr(PARAMETER_TYPE_STRING),
  223. Help: &I18nObject{
  224. EnUS: "Set a response format, ensure the output from llm is a valid code block as possible, such as JSON, XML, etc.",
  225. ZhHans: "设置一个返回格式,确保llm的输出尽可能是有效的代码块,如JSON、XML等",
  226. JaJp: "応答形式を設定します。llmの出力が可能な限り有効なコードブロックであることを確認します。",
  227. PtBr: "Defina um formato de resposta para garantir que a saída do llm seja um bloco de código válido o mais possível, como JSON, XML, etc.",
  228. },
  229. Required: false,
  230. Options: []string{"JSON", "XML"},
  231. },
  232. JSON_SCHEMA: {
  233. Label: &I18nObject{
  234. EnUS: "JSON Schema",
  235. },
  236. Type: parser.ToPtr(PARAMETER_TYPE_STRING),
  237. Help: &I18nObject{
  238. EnUS: "Set a response json schema will ensure LLM to adhere it.",
  239. ZhHans: "设置返回的json schema,llm将按照它返回",
  240. },
  241. Required: false,
  242. },
  243. }
  244. func (m *ModelParameterRule) TransformTemplate() error {
  245. if m.Label == nil || m.Label.EnUS == "" {
  246. m.Label = &I18nObject{
  247. EnUS: m.Name,
  248. }
  249. }
  250. // if use_template is not empty, transform to use default value
  251. if m.UseTemplate != nil && *m.UseTemplate != "" {
  252. // get the value of use_template
  253. useTemplateValue := m.UseTemplate
  254. // get the template
  255. template, ok := PARAMETER_RULE_TEMPLATE[DefaultParameterName(*useTemplateValue)]
  256. if !ok {
  257. return fmt.Errorf("use_template %s not found", *useTemplateValue)
  258. }
  259. // transform to default value
  260. if m.Label == nil {
  261. m.Label = template.Label
  262. }
  263. if m.Type == nil {
  264. m.Type = template.Type
  265. }
  266. if m.Help == nil {
  267. m.Help = template.Help
  268. }
  269. if m.Default == nil {
  270. m.Default = template.Default
  271. }
  272. if m.Min == nil {
  273. m.Min = template.Min
  274. }
  275. if m.Max == nil {
  276. m.Max = template.Max
  277. }
  278. if m.Precision == nil {
  279. m.Precision = template.Precision
  280. }
  281. if m.Options == nil {
  282. m.Options = template.Options
  283. }
  284. }
  285. if m.Options == nil {
  286. m.Options = []string{}
  287. }
  288. return nil
  289. }
  290. func (m *ModelParameterRule) UnmarshalJSON(data []byte) error {
  291. type alias ModelParameterRule
  292. temp := &struct {
  293. *alias
  294. }{
  295. alias: (*alias)(m),
  296. }
  297. if err := json.Unmarshal(data, &temp); err != nil {
  298. return err
  299. }
  300. if err := m.TransformTemplate(); err != nil {
  301. return err
  302. }
  303. return nil
  304. }
  305. func (m *ModelParameterRule) UnmarshalYAML(value *yaml.Node) error {
  306. type alias ModelParameterRule
  307. temp := &struct {
  308. *alias `yaml:",inline"`
  309. }{
  310. alias: (*alias)(m),
  311. }
  312. if err := value.Decode(&temp); err != nil {
  313. return err
  314. }
  315. if err := m.TransformTemplate(); err != nil {
  316. return err
  317. }
  318. return nil
  319. }
  320. func isParameterRule(fl validator.FieldLevel) bool {
  321. // if use_template is empty, then label, type should be required
  322. // try get the value of use_template
  323. useTemplateHandle := fl.Field().FieldByName("UseTemplate")
  324. // check if use_template is null pointer
  325. if useTemplateHandle.IsNil() {
  326. // label and type should be required
  327. // try get the value of label
  328. if fl.Field().FieldByName("Label").IsNil() {
  329. return false
  330. }
  331. // try get the value of type
  332. if fl.Field().FieldByName("Type").IsNil() {
  333. return false
  334. }
  335. }
  336. return true
  337. }
  338. type ModelPriceConfig struct {
  339. Input decimal.Decimal `json:"input" yaml:"input" validate:"required"`
  340. Output *decimal.Decimal `json:"output" yaml:"output" validate:"omitempty"`
  341. Unit decimal.Decimal `json:"unit" yaml:"unit" validate:"required"`
  342. Currency string `json:"currency" yaml:"currency" validate:"required"`
  343. }
  344. type ModelDeclaration struct {
  345. Model string `json:"model" yaml:"model" validate:"required,lt=256"`
  346. Label I18nObject `json:"label" yaml:"label" validate:"required"`
  347. ModelType ModelType `json:"model_type" yaml:"model_type" validate:"required,model_type"`
  348. Features []string `json:"features" yaml:"features" validate:"omitempty,lte=256,dive,lt=256"`
  349. FetchFrom ModelProviderConfigurateMethod `json:"fetch_from" yaml:"fetch_from" validate:"omitempty,model_provider_configurate_method"`
  350. ModelProperties map[string]any `json:"model_properties" yaml:"model_properties" validate:"omitempty"`
  351. Deprecated bool `json:"deprecated" yaml:"deprecated"`
  352. ParameterRules []ModelParameterRule `json:"parameter_rules" yaml:"parameter_rules" validate:"omitempty,lte=128,dive,parameter_rule"`
  353. PriceConfig *ModelPriceConfig `json:"pricing" yaml:"pricing" validate:"omitempty"`
  354. }
  355. func (m *ModelDeclaration) UnmarshalJSON(data []byte) error {
  356. type alias ModelDeclaration
  357. temp := &struct {
  358. *alias
  359. }{
  360. alias: (*alias)(m),
  361. }
  362. if err := json.Unmarshal(data, &temp); err != nil {
  363. return err
  364. }
  365. if m.FetchFrom == "" {
  366. m.FetchFrom = CONFIGURATE_METHOD_PREDEFINED_MODEL
  367. }
  368. if m.ParameterRules == nil {
  369. m.ParameterRules = []ModelParameterRule{}
  370. }
  371. return nil
  372. }
  373. func (m ModelDeclaration) MarshalJSON() ([]byte, error) {
  374. type alias ModelDeclaration
  375. temp := &struct {
  376. alias `json:",inline"`
  377. }{
  378. alias: (alias)(m),
  379. }
  380. if temp.Label.EnUS == "" {
  381. temp.Label.EnUS = temp.Model
  382. }
  383. // to avoid ModelProperties not serializable, we need to convert all the keys to string
  384. // includes inner map and slice
  385. if temp.ModelProperties != nil {
  386. result, ok := mapping.ConvertAnyMap(temp.ModelProperties).(map[string]any)
  387. if !ok {
  388. log.Error("ModelProperties is not a map[string]any", "model_properties", temp.ModelProperties)
  389. } else {
  390. temp.ModelProperties = result
  391. }
  392. }
  393. return json.Marshal(temp)
  394. }
  395. func (m *ModelDeclaration) UnmarshalYAML(value *yaml.Node) error {
  396. type alias ModelDeclaration
  397. temp := &struct {
  398. *alias `yaml:",inline"`
  399. }{
  400. alias: (*alias)(m),
  401. }
  402. if err := value.Decode(&temp); err != nil {
  403. return err
  404. }
  405. if m.FetchFrom == "" {
  406. m.FetchFrom = CONFIGURATE_METHOD_PREDEFINED_MODEL
  407. }
  408. if m.ParameterRules == nil {
  409. m.ParameterRules = []ModelParameterRule{}
  410. }
  411. return nil
  412. }
  413. type ModelProviderFormType string
  414. const (
  415. FORM_TYPE_TEXT_INPUT ModelProviderFormType = "text-input"
  416. FORM_TYPE_SECRET_INPUT ModelProviderFormType = "secret-input"
  417. FORM_TYPE_SELECT ModelProviderFormType = "select"
  418. FORM_TYPE_RADIO ModelProviderFormType = "radio"
  419. FORM_TYPE_SWITCH ModelProviderFormType = "switch"
  420. )
  421. func isModelProviderFormType(fl validator.FieldLevel) bool {
  422. value := fl.Field().String()
  423. switch value {
  424. case string(FORM_TYPE_TEXT_INPUT),
  425. string(FORM_TYPE_SECRET_INPUT),
  426. string(FORM_TYPE_SELECT),
  427. string(FORM_TYPE_RADIO),
  428. string(FORM_TYPE_SWITCH):
  429. return true
  430. }
  431. return false
  432. }
  433. type ModelProviderFormShowOnObject struct {
  434. Variable string `json:"variable" yaml:"variable" validate:"required,lt=256"`
  435. Value string `json:"value" yaml:"value" validate:"required,lt=256"`
  436. }
  437. type ModelProviderFormOption struct {
  438. Label I18nObject `json:"label" yaml:"label" validate:"required"`
  439. Value string `json:"value" yaml:"value" validate:"required,lt=256"`
  440. ShowOn []ModelProviderFormShowOnObject `json:"show_on" yaml:"show_on" validate:"omitempty,lte=16,dive"`
  441. }
  442. func (m *ModelProviderFormOption) UnmarshalJSON(data []byte) error {
  443. // avoid show_on to be nil
  444. type Alias ModelProviderFormOption
  445. aux := &struct {
  446. *Alias
  447. }{
  448. Alias: (*Alias)(m),
  449. }
  450. if err := json.Unmarshal(data, aux); err != nil {
  451. return err
  452. }
  453. if m.ShowOn == nil {
  454. m.ShowOn = []ModelProviderFormShowOnObject{}
  455. }
  456. return nil
  457. }
  458. func (m *ModelProviderFormOption) UnmarshalYAML(value *yaml.Node) error {
  459. // avoid show_on to be nil
  460. type Alias ModelProviderFormOption
  461. aux := &struct {
  462. *Alias `yaml:",inline"`
  463. }{
  464. Alias: (*Alias)(m),
  465. }
  466. if err := value.Decode(&aux); err != nil {
  467. return err
  468. }
  469. if m.ShowOn == nil {
  470. m.ShowOn = []ModelProviderFormShowOnObject{}
  471. }
  472. return nil
  473. }
  474. type ModelProviderCredentialFormSchema struct {
  475. Variable string `json:"variable" yaml:"variable" validate:"required,lt=256"`
  476. Label I18nObject `json:"label" yaml:"label" validate:"required"`
  477. Type ModelProviderFormType `json:"type" yaml:"type" validate:"required,model_provider_form_type"`
  478. Required bool `json:"required" yaml:"required"`
  479. Default *string `json:"default" yaml:"default" validate:"omitempty,lt=256"`
  480. Options []ModelProviderFormOption `json:"options" yaml:"options" validate:"omitempty,lte=128,dive"`
  481. Placeholder *I18nObject `json:"placeholder" yaml:"placeholder" validate:"omitempty"`
  482. MaxLength int `json:"max_length" yaml:"max_length"`
  483. ShowOn []ModelProviderFormShowOnObject `json:"show_on" yaml:"show_on" validate:"omitempty,lte=16,dive"`
  484. }
  485. func (m *ModelProviderCredentialFormSchema) UnmarshalJSON(data []byte) error {
  486. type Alias ModelProviderCredentialFormSchema
  487. temp := &struct {
  488. *Alias
  489. }{
  490. Alias: (*Alias)(m),
  491. }
  492. if err := json.Unmarshal(data, &temp); err != nil {
  493. return err
  494. }
  495. if m.ShowOn == nil {
  496. m.ShowOn = []ModelProviderFormShowOnObject{}
  497. }
  498. if m.Options == nil {
  499. m.Options = []ModelProviderFormOption{}
  500. }
  501. return nil
  502. }
  503. func (m *ModelProviderCredentialFormSchema) UnmarshalYAML(value *yaml.Node) error {
  504. type Alias ModelProviderCredentialFormSchema
  505. temp := &struct {
  506. *Alias `yaml:",inline"`
  507. }{
  508. Alias: (*Alias)(m),
  509. }
  510. if err := value.Decode(&temp); err != nil {
  511. return err
  512. }
  513. if m.ShowOn == nil {
  514. m.ShowOn = []ModelProviderFormShowOnObject{}
  515. }
  516. if m.Options == nil {
  517. m.Options = []ModelProviderFormOption{}
  518. }
  519. return nil
  520. }
  521. type ModelProviderCredentialSchema struct {
  522. CredentialFormSchemas []ModelProviderCredentialFormSchema `json:"credential_form_schemas" yaml:"credential_form_schemas" validate:"omitempty,lte=32,dive"`
  523. }
  524. type FieldModelSchema struct {
  525. Label I18nObject `json:"label" yaml:"label" validate:"required"`
  526. Placeholder *I18nObject `json:"placeholder" yaml:"placeholder" validate:"omitempty"`
  527. }
  528. type ModelCredentialSchema struct {
  529. Model FieldModelSchema `json:"model" yaml:"model" validate:"required"`
  530. CredentialFormSchemas []ModelProviderCredentialFormSchema `json:"credential_form_schemas" yaml:"credential_form_schemas" validate:"omitempty,lte=32,dive"`
  531. }
  532. type ModelProviderHelpEntity struct {
  533. Title I18nObject `json:"title" yaml:"title" validate:"required"`
  534. URL I18nObject `json:"url" yaml:"url" validate:"required"`
  535. }
  536. type ModelPosition struct {
  537. LLM *[]string `json:"llm,omitempty" yaml:"llm,omitempty"`
  538. TextEmbedding *[]string `json:"text_embedding,omitempty" yaml:"text_embedding,omitempty"`
  539. Rerank *[]string `json:"rerank,omitempty" yaml:"rerank,omitempty"`
  540. TTS *[]string `json:"tts,omitempty" yaml:"tts,omitempty"`
  541. Speech2text *[]string `json:"speech2text,omitempty" yaml:"speech2text,omitempty"`
  542. Moderation *[]string `json:"moderation,omitempty" yaml:"moderation,omitempty"`
  543. }
  544. type ModelProviderDeclaration struct {
  545. Provider string `json:"provider" yaml:"provider" validate:"required,lt=256"`
  546. Label I18nObject `json:"label" yaml:"label" validate:"required"`
  547. Description *I18nObject `json:"description" yaml:"description,omitempty" validate:"omitempty"`
  548. IconSmall *I18nObject `json:"icon_small" yaml:"icon_small,omitempty" validate:"omitempty"`
  549. IconLarge *I18nObject `json:"icon_large" yaml:"icon_large,omitempty" validate:"omitempty"`
  550. Background *string `json:"background" yaml:"background,omitempty" validate:"omitempty"`
  551. Help *ModelProviderHelpEntity `json:"help" yaml:"help,omitempty" validate:"omitempty"`
  552. SupportedModelTypes []ModelType `json:"supported_model_types" yaml:"supported_model_types" validate:"required,lte=16,dive,model_type"`
  553. ConfigurateMethods []ModelProviderConfigurateMethod `json:"configurate_methods" yaml:"configurate_methods" validate:"required,lte=16,dive,model_provider_configurate_method"`
  554. ProviderCredentialSchema *ModelProviderCredentialSchema `json:"provider_credential_schema" yaml:"provider_credential_schema,omitempty" validate:"omitempty"`
  555. ModelCredentialSchema *ModelCredentialSchema `json:"model_credential_schema" yaml:"model_credential_schema,omitempty" validate:"omitempty"`
  556. Position *ModelPosition `json:"position,omitempty" yaml:"position,omitempty"`
  557. Models []ModelDeclaration `json:"models" yaml:"model_declarations,omitempty"`
  558. ModelFiles []string `json:"-" yaml:"-"`
  559. PositionFiles map[string]string `json:"-" yaml:"-"`
  560. }
  561. func (m *ModelProviderDeclaration) UnmarshalJSON(data []byte) error {
  562. type alias ModelProviderDeclaration
  563. var temp struct {
  564. alias
  565. Models json.RawMessage `json:"models"`
  566. }
  567. if err := json.Unmarshal(data, &temp); err != nil {
  568. return err
  569. }
  570. *m = ModelProviderDeclaration(temp.alias)
  571. if m.ModelCredentialSchema != nil && m.ModelCredentialSchema.CredentialFormSchemas == nil {
  572. m.ModelCredentialSchema.CredentialFormSchemas = []ModelProviderCredentialFormSchema{}
  573. }
  574. if m.ProviderCredentialSchema != nil && m.ProviderCredentialSchema.CredentialFormSchemas == nil {
  575. m.ProviderCredentialSchema.CredentialFormSchemas = []ModelProviderCredentialFormSchema{}
  576. }
  577. // unmarshal models into map[string]any
  578. var models map[string]any
  579. if err := json.Unmarshal(temp.Models, &models); err != nil {
  580. // can not unmarshal it into map, so it's a list
  581. if err := json.Unmarshal(temp.Models, &m.Models); err != nil {
  582. return err
  583. }
  584. return nil
  585. }
  586. m.PositionFiles = make(map[string]string)
  587. types := []string{
  588. "llm",
  589. "text_embedding",
  590. "tts",
  591. "speech2text",
  592. "moderation",
  593. "rerank",
  594. }
  595. for _, model_type := range types {
  596. modelTypeMap, ok := models[model_type].(map[string]any)
  597. if ok {
  598. modelTypePositionFile, ok := modelTypeMap["position"]
  599. if ok {
  600. modelTypePositionFilePath, ok := modelTypePositionFile.(string)
  601. if ok {
  602. m.PositionFiles[model_type] = modelTypePositionFilePath
  603. }
  604. }
  605. modelTypePredefinedFiles, ok := modelTypeMap["predefined"].([]string)
  606. if ok {
  607. m.ModelFiles = append(m.ModelFiles, modelTypePredefinedFiles...)
  608. }
  609. }
  610. }
  611. if m.Models == nil {
  612. m.Models = []ModelDeclaration{}
  613. }
  614. return nil
  615. }
  616. func (m *ModelProviderDeclaration) MarshalJSON() ([]byte, error) {
  617. type alias ModelProviderDeclaration
  618. temp := &struct {
  619. *alias `json:",inline"`
  620. }{
  621. alias: (*alias)(m),
  622. }
  623. if temp.Models == nil {
  624. temp.Models = []ModelDeclaration{}
  625. }
  626. return json.Marshal(temp)
  627. }
  628. func (m *ModelProviderDeclaration) UnmarshalYAML(value *yaml.Node) error {
  629. type alias ModelProviderDeclaration
  630. var temp struct {
  631. alias `yaml:",inline"`
  632. Models yaml.Node `yaml:"models"`
  633. }
  634. if err := value.Decode(&temp); err != nil {
  635. return err
  636. }
  637. *m = ModelProviderDeclaration(temp.alias)
  638. if m.ModelCredentialSchema != nil && m.ModelCredentialSchema.CredentialFormSchemas == nil {
  639. m.ModelCredentialSchema.CredentialFormSchemas = []ModelProviderCredentialFormSchema{}
  640. }
  641. if m.ProviderCredentialSchema != nil && m.ProviderCredentialSchema.CredentialFormSchemas == nil {
  642. m.ProviderCredentialSchema.CredentialFormSchemas = []ModelProviderCredentialFormSchema{}
  643. }
  644. // Check if Models is a mapping node
  645. if temp.Models.Kind == yaml.MappingNode {
  646. m.PositionFiles = make(map[string]string)
  647. types := []string{
  648. "llm",
  649. "text_embedding",
  650. "tts",
  651. "speech2text",
  652. "moderation",
  653. "rerank",
  654. }
  655. for i := 0; i < len(temp.Models.Content); i += 2 {
  656. key := temp.Models.Content[i].Value
  657. value := temp.Models.Content[i+1]
  658. for _, model_type := range types {
  659. if key == model_type {
  660. if value.Kind == yaml.MappingNode {
  661. for j := 0; j < len(value.Content); j += 2 {
  662. if value.Content[j].Value == "position" {
  663. m.PositionFiles[model_type] = value.Content[j+1].Value
  664. } else if value.Content[j].Value == "predefined" {
  665. // get content of predefined
  666. if value.Content[j+1].Kind == yaml.SequenceNode {
  667. for _, file := range value.Content[j+1].Content {
  668. m.ModelFiles = append(m.ModelFiles, file.Value)
  669. }
  670. }
  671. }
  672. }
  673. }
  674. }
  675. }
  676. }
  677. } else if temp.Models.Kind == yaml.SequenceNode {
  678. if err := temp.Models.Decode(&m.Models); err != nil {
  679. return err
  680. }
  681. }
  682. if m.Models == nil {
  683. m.Models = []ModelDeclaration{}
  684. }
  685. return nil
  686. }
  687. func init() {
  688. // init validator
  689. en := en.New()
  690. uni := ut.New(en, en)
  691. translator, _ := uni.GetTranslator("en")
  692. // register translations for default validators
  693. en_translations.RegisterDefaultTranslations(validators.GlobalEntitiesValidator, translator)
  694. validators.GlobalEntitiesValidator.RegisterValidation("model_type", isModelType)
  695. validators.GlobalEntitiesValidator.RegisterTranslation(
  696. "model_type",
  697. translator,
  698. func(ut ut.Translator) error {
  699. return ut.Add("model_type", "{0} is not a valid model type", true)
  700. },
  701. func(ut ut.Translator, fe validator.FieldError) string {
  702. t, _ := ut.T("model_type", fe.Field())
  703. return t
  704. },
  705. )
  706. validators.GlobalEntitiesValidator.RegisterValidation("model_provider_configurate_method", isModelProviderConfigurateMethod)
  707. validators.GlobalEntitiesValidator.RegisterTranslation(
  708. "model_provider_configurate_method",
  709. translator,
  710. func(ut ut.Translator) error {
  711. return ut.Add("model_provider_configurate_method", "{0} is not a valid model provider configurate method", true)
  712. },
  713. func(ut ut.Translator, fe validator.FieldError) string {
  714. t, _ := ut.T("model_provider_configurate_method", fe.Field())
  715. return t
  716. },
  717. )
  718. validators.GlobalEntitiesValidator.RegisterValidation("model_provider_form_type", isModelProviderFormType)
  719. validators.GlobalEntitiesValidator.RegisterTranslation(
  720. "model_provider_form_type",
  721. translator,
  722. func(ut ut.Translator) error {
  723. return ut.Add("model_provider_form_type", "{0} is not a valid model provider form type", true)
  724. },
  725. func(ut ut.Translator, fe validator.FieldError) string {
  726. t, _ := ut.T("model_provider_form_type", fe.Field())
  727. return t
  728. },
  729. )
  730. validators.GlobalEntitiesValidator.RegisterValidation("model_parameter_type", isModelParameterType)
  731. validators.GlobalEntitiesValidator.RegisterTranslation(
  732. "model_parameter_type",
  733. translator,
  734. func(ut ut.Translator) error {
  735. return ut.Add("model_parameter_type", "{0} is not a valid model parameter type", true)
  736. },
  737. func(ut ut.Translator, fe validator.FieldError) string {
  738. t, _ := ut.T("model_parameter_type", fe.Field())
  739. return t
  740. },
  741. )
  742. validators.GlobalEntitiesValidator.RegisterValidation("parameter_rule", isParameterRule)
  743. validators.GlobalEntitiesValidator.RegisterValidation("is_basic_type", isBasicType)
  744. }