model.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import { z } from "zod"
  2. import { eq, and } from "drizzle-orm"
  3. import { Database } from "./drizzle"
  4. import { ModelTable } from "./schema/model.sql"
  5. import { Identifier } from "./identifier"
  6. import { fn } from "./util/fn"
  7. import { Actor } from "./actor"
  8. import { Resource } from "@kirincode-ai/console-resource"
  9. export namespace ZenData {
  10. const FormatSchema = z.enum(["anthropic", "google", "openai", "oa-compat"])
  11. export type Format = z.infer<typeof FormatSchema>
  12. const ModelCostSchema = z.object({
  13. input: z.number(),
  14. output: z.number(),
  15. cacheRead: z.number().optional(),
  16. cacheWrite5m: z.number().optional(),
  17. cacheWrite1h: z.number().optional(),
  18. })
  19. const ModelSchema = z.object({
  20. name: z.string(),
  21. cost: ModelCostSchema,
  22. cost200K: ModelCostSchema.optional(),
  23. allowAnonymous: z.boolean().optional(),
  24. byokProvider: z.enum(["openai", "anthropic", "google"]).optional(),
  25. stickyProvider: z.enum(["strict", "prefer"]).optional(),
  26. trialProvider: z.string().optional(),
  27. trialEnded: z.boolean().optional(),
  28. fallbackProvider: z.string().optional(),
  29. rateLimit: z.number().optional(),
  30. providers: z.array(
  31. z.object({
  32. id: z.string(),
  33. model: z.string(),
  34. priority: z.number().optional(),
  35. tpmLimit: z.number().optional(),
  36. tpsGoal: z.number().optional(),
  37. budgetPriority: z.number().optional(),
  38. budgetContribution: z.number().optional(),
  39. weight: z.number().optional(),
  40. disabled: z.boolean().optional(),
  41. storeModel: z.string().optional(),
  42. payloadModifier: z.record(z.string(), z.any()).optional(),
  43. }),
  44. ),
  45. })
  46. const ProviderSchema = z.object({
  47. displayName: z.string().optional(),
  48. api: z.string(),
  49. apiKey: z.union([z.string(), z.record(z.string(), z.string())]),
  50. format: FormatSchema.optional(),
  51. headerModifier: z.record(z.string(), z.any()).optional(),
  52. payloadModifier: z.record(z.string(), z.any()).optional(),
  53. adjustCacheUsage: z.boolean().optional(),
  54. budget: z.number().optional(),
  55. })
  56. const ModelsSchema = z.object({
  57. zenModels: z.record(
  58. z.string(),
  59. z.union([ModelSchema, z.array(ModelSchema.extend({ formatFilter: FormatSchema }))]),
  60. ),
  61. liteModels: z.record(
  62. z.string(),
  63. z.union([ModelSchema, z.array(ModelSchema.extend({ formatFilter: FormatSchema }))]),
  64. ),
  65. providers: z.record(z.string(), ProviderSchema),
  66. })
  67. export const validate = fn(ModelsSchema, (input) => {
  68. return input
  69. })
  70. export const list = fn(z.enum(["lite", "full"]), (modelList) => {
  71. const json = JSON.parse(
  72. Resource.ZEN_MODELS1.value +
  73. Resource.ZEN_MODELS2.value +
  74. Resource.ZEN_MODELS3.value +
  75. Resource.ZEN_MODELS4.value +
  76. Resource.ZEN_MODELS5.value +
  77. Resource.ZEN_MODELS6.value +
  78. Resource.ZEN_MODELS7.value +
  79. Resource.ZEN_MODELS8.value +
  80. Resource.ZEN_MODELS9.value +
  81. Resource.ZEN_MODELS10.value +
  82. Resource.ZEN_MODELS11.value +
  83. Resource.ZEN_MODELS12.value +
  84. Resource.ZEN_MODELS13.value +
  85. Resource.ZEN_MODELS14.value +
  86. Resource.ZEN_MODELS15.value +
  87. Resource.ZEN_MODELS16.value +
  88. Resource.ZEN_MODELS17.value +
  89. Resource.ZEN_MODELS18.value +
  90. Resource.ZEN_MODELS19.value +
  91. Resource.ZEN_MODELS20.value +
  92. Resource.ZEN_MODELS21.value +
  93. Resource.ZEN_MODELS22.value +
  94. Resource.ZEN_MODELS23.value +
  95. Resource.ZEN_MODELS24.value +
  96. Resource.ZEN_MODELS25.value +
  97. Resource.ZEN_MODELS26.value +
  98. Resource.ZEN_MODELS27.value +
  99. Resource.ZEN_MODELS28.value +
  100. Resource.ZEN_MODELS29.value +
  101. Resource.ZEN_MODELS30.value,
  102. )
  103. const { zenModels, liteModels, providers } = ModelsSchema.parse(json)
  104. const compositeProviders = Object.fromEntries(
  105. Object.entries(providers).map(([id, provider]) => [
  106. id,
  107. typeof provider.apiKey === "string"
  108. ? [{ id: id, key: provider.apiKey }]
  109. : Object.entries(provider.apiKey).map(([kid, key]) => ({
  110. id: `${id}.${kid}`,
  111. key,
  112. })),
  113. ]),
  114. )
  115. return {
  116. providers: Object.fromEntries(
  117. Object.entries(providers).flatMap(([providerId, provider]) =>
  118. compositeProviders[providerId].map((p) => [p.id, { ...provider, apiKey: p.key }]),
  119. ),
  120. ),
  121. models: (() => {
  122. const normalize = (model: z.infer<typeof ModelSchema>) => {
  123. const providers = model.providers.map((p) => ({
  124. ...p,
  125. priority: p.priority ?? Infinity,
  126. weight: p.weight ?? 1,
  127. }))
  128. const composite = providers.find((p) => compositeProviders[p.id].length > 1)
  129. if (!composite)
  130. return {
  131. trialProvider: model.trialProvider ? [model.trialProvider] : undefined,
  132. providers,
  133. }
  134. const weightMulti = compositeProviders[composite.id].length
  135. return {
  136. trialProvider: (() => {
  137. if (!model.trialProvider) return undefined
  138. if (model.trialProvider === composite.id) return compositeProviders[composite.id].map((p) => p.id)
  139. return [model.trialProvider]
  140. })(),
  141. providers: providers.flatMap((p) =>
  142. p.id === composite.id
  143. ? compositeProviders[p.id].map((sub) => ({
  144. ...p,
  145. id: sub.id,
  146. }))
  147. : [
  148. {
  149. ...p,
  150. weight: p.weight * weightMulti,
  151. },
  152. ],
  153. ),
  154. }
  155. }
  156. return Object.fromEntries(
  157. Object.entries(modelList === "lite" ? liteModels : zenModels).map(([modelId, model]) => {
  158. const n = Array.isArray(model)
  159. ? model.map((m) => ({ ...m, ...normalize(m) }))
  160. : { ...model, ...normalize(model) }
  161. return [modelId, n]
  162. }),
  163. )
  164. })(),
  165. }
  166. })
  167. }
  168. export namespace Model {
  169. export const enable = fn(z.object({ model: z.string() }), ({ model }) => {
  170. Actor.assertAdmin()
  171. return Database.use((db) =>
  172. db.delete(ModelTable).where(and(eq(ModelTable.workspaceID, Actor.workspace()), eq(ModelTable.model, model))),
  173. )
  174. })
  175. export const disable = fn(z.object({ model: z.string() }), ({ model }) => {
  176. Actor.assertAdmin()
  177. return Database.use((db) =>
  178. db
  179. .insert(ModelTable)
  180. .values({
  181. id: Identifier.create("model"),
  182. workspaceID: Actor.workspace(),
  183. model: model,
  184. })
  185. .onDuplicateKeyUpdate({
  186. set: {
  187. timeDeleted: null,
  188. },
  189. }),
  190. )
  191. })
  192. export const listDisabled = fn(z.void(), () => {
  193. return Database.use((db) =>
  194. db
  195. .select({ model: ModelTable.model })
  196. .from(ModelTable)
  197. .where(eq(ModelTable.workspaceID, Actor.workspace()))
  198. .then((rows) => rows.map((row) => row.model)),
  199. )
  200. })
  201. export const isDisabled = fn(
  202. z.object({
  203. model: z.string(),
  204. }),
  205. ({ model }) => {
  206. return Database.use(async (db) => {
  207. const result = await db
  208. .select()
  209. .from(ModelTable)
  210. .where(and(eq(ModelTable.workspaceID, Actor.workspace()), eq(ModelTable.model, model)))
  211. .limit(1)
  212. return result.length > 0
  213. })
  214. },
  215. )
  216. }