Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

23.8 KB
Raw Blame
import { and, asc, desc, eq, isNotNull, isNull, sql } from 'drizzle-orm';
import type {
  AiModelConfig,
  AiModelReasoningConfig,
  AiModelSortMap,
  AiProviderModelListItem,
  EnabledAiModel,
  ToggleAiModelEnableParams,
} from 'model-bank';
import { AiModelSourceEnum, getAutoGeneratedModelSourceId, normalizeAiModelType } from 'model-bank';

import type { AiModelSelectItem, NewAiModelItem } from '../schemas';
import { aiModels } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';

export class AiModelModel {
  private userId: string;
  private workspaceId?: string;
  private db: LobeChatDatabase;

  constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
    this.userId = userId;
    this.workspaceId = workspaceId;
    this.db = db;
  }

  private scopeWhere = () =>
    buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, aiModels);

  /**
   * Personal scope regardless of the active workspace (userId + workspaceId IS NULL).
   * Used by the model-instance reasoning-config helpers, which are cross-workspace.
   */
  private personalScopeWhere = () => buildWorkspaceWhere({ userId: this.userId }, aiModels);

  private values<T extends object>(base: T) {
    return buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, base);
  }

  private conflictTarget() {
    return this.workspaceId
      ? {
          target: [aiModels.id, aiModels.providerId, aiModels.userId, aiModels.workspaceId],
          targetWhere: isNotNull(aiModels.workspaceId),
        }
      : {
          target: [aiModels.id, aiModels.providerId, aiModels.userId],
          targetWhere: isNull(aiModels.workspaceId),
        };
  }

  /**
   * The database column is varchar(10). Remote model feeds can send ISO timestamps
   * such as `2025-01-01T00:00:00.000Z`, which PostgreSQL rejects on insert.
   */
  private normalizeReleasedAt(releasedAt?: string | null) {
    if (!releasedAt) return releasedAt;

    return releasedAt.length > 10 ? releasedAt.slice(0, 10) : releasedAt;
  }

  private normalizeAiModelValues<T extends { releasedAt?: string | null; type?: string | null }>(
    values: T,
  ): T {
    return {
      ...values,
      releasedAt: this.normalizeReleasedAt(values.releasedAt),
      // Heal the legacy `stt` value on write (lazy migration): any natural
      // create/update persists the standard `asr`. `undefined` is left as-is so
      // partial updates don't clobber the column (drizzle skips undefined).
      type: normalizeAiModelType(values.type),
    };
  }

  /**
   * Helper method to validate if array is empty and return early if needed
   * @param array - Array to validate
   * @returns true if array is empty, false otherwise
   */
  private isEmptyArray(array: unknown[]): boolean {
    return array.length === 0;
  }

  /**
   * Whether a row exists only to persist the personal reasoning preference
   * (`config.chatConfig`): created by {@link AiModelModel.updateModelReasoningConfig}
   * or left behind when {@link AiModelModel.clearRemoteModels} demotes a remote
   * row. Such shells carry no user-visible identity — list reads hide them and
   * duplicate checks must not treat them as real models.
   */
  static isPreferenceOnlyRow = (row: {
    contextWindowTokens?: number | null;
    displayName?: string | null;
    enabled?: boolean | null;
    releasedAt?: string | null;
    source?: string | null;
  }) =>
    row.source == null &&
    row.enabled == null &&
    row.displayName == null &&
    row.contextWindowTokens == null &&
    row.releasedAt == null;

  create = async (params: NewAiModelItem) => {
    const values = this.normalizeAiModelValues(params);

    const [result] = await this.db
      .insert(aiModels)
      .values(
        this.values({
          ...values,
          enabled: params.enabled ?? true, // enabled by default, but respect explicit value
          source: AiModelSourceEnum.Custom,
        }),
      )
      .returning();

    return result;
  };

  delete = async (id: string, providerId: string) => {
    return this.db
      .delete(aiModels)
      .where(and(eq(aiModels.id, id), eq(aiModels.providerId, providerId), this.scopeWhere()));
  };

  deleteAll = async () => {
    return this.db.delete(aiModels).where(this.scopeWhere());
  };

  query = async () => {
    return this.db.query.aiModels.findMany({
      orderBy: [desc(aiModels.updatedAt)],
      where: this.scopeWhere(),
    });
  };

  getModelListByProviderId = async (providerId: string) => {
    const result = await this.db
      .select({
        abilities: aiModels.abilities,
        config: aiModels.config,
        contextWindowTokens: aiModels.contextWindowTokens,
        description: aiModels.description,
        displayName: aiModels.displayName,
        enabled: aiModels.enabled,
        id: aiModels.id,
        parameters: aiModels.parameters,
        pricing: aiModels.pricing,
        releasedAt: aiModels.releasedAt,
        settings: aiModels.settings,
        source: aiModels.source,
        type: aiModels.type,
      })
      .from(aiModels)
      .where(and(eq(aiModels.providerId, providerId), this.scopeWhere()))
      .orderBy(
        asc(aiModels.sort),
        desc(aiModels.enabled),
        desc(aiModels.releasedAt),
        desc(aiModels.updatedAt),
      );

    return result as AiProviderModelListItem[];
  };

  getAllModels = async () => {
    const data = await this.db
      .select({
        abilities: aiModels.abilities,
        config: aiModels.config,
        contextWindowTokens: aiModels.contextWindowTokens,
        displayName: aiModels.displayName,
        enabled: aiModels.enabled,
        id: aiModels.id,
        parameters: aiModels.parameters,
        providerId: aiModels.providerId,
        pricing: aiModels.pricing,
        releasedAt: aiModels.releasedAt,
        settings: aiModels.settings,
        sort: aiModels.sort,
        source: aiModels.source,
        type: aiModels.type,
      })
      .from(aiModels)
      .where(this.scopeWhere());

    return data as EnabledAiModel[];
  };

  findById = async (id: string) => {
    return this.db.query.aiModels.findFirst({
      where: and(eq(aiModels.id, id), this.scopeWhere()),
    });
  };

  findByIdAndProvider = async (id: string, providerId: string) => {
    return this.db.query.aiModels.findFirst({
      where: and(eq(aiModels.id, id), eq(aiModels.providerId, providerId), this.scopeWhere()),
    });
  };

  update = async (id: string, providerId: string, value: Partial<AiModelSelectItem>) => {
    const normalizedValue = this.normalizeAiModelValues(value);

    const set: Record<string, unknown> = { ...normalizedValue };
    // Shallow-merge `config` instead of replacing the column: callers send partial
    // config (the model-config modal only knows `deploymentName`), and a full
    // replace would silently wipe sibling keys such as the user's `chatConfig`
    // model-instance reasoning defaults.
    if (normalizedValue.config !== undefined && normalizedValue.config !== null) {
      set.config = sql`COALESCE(ai_models.config, '{}'::jsonb) || excluded.config`;
    }

    return this.db
      .insert(aiModels)
      .values(this.values({ ...normalizedValue, id, providerId, updatedAt: new Date() }))
      .onConflictDoUpdate({
        set,
        ...this.conflictTarget(),
      });
  };

  /**
   * Personal-scope read of the user's per-model-instance reasoning defaults
   * (`config.chatConfig`). Deliberately ignores the active workspace: the
   * preference is keyed by userId + providerId + modelId and shared across
   * workspaces by design.
   */
  getModelReasoningConfig = async (
    id: string,
    providerId: string,
  ): Promise<AiModelReasoningConfig | undefined> => {
    const row = await this.db.query.aiModels.findFirst({
      columns: { config: true },
      where: and(
        eq(aiModels.id, id),
        eq(aiModels.providerId, providerId),
        this.personalScopeWhere(),
      ),
    });

    return (row?.config as AiModelConfig | null)?.chatConfig;
  };

  /**
   * Bulk counterpart of getModelReasoningConfig (same personal scope): every
   * saved reasoning default, keyed by `${providerId}/${modelId}`. Lets the
   * client seed all model-list rows with one read instead of one per model.
   */
  getAllModelReasoningConfigs = async (): Promise<Record<string, AiModelReasoningConfig>> => {
    const rows = await this.db
      .select({ config: aiModels.config, id: aiModels.id, providerId: aiModels.providerId })
      .from(aiModels)
      .where(
        and(
          this.personalScopeWhere(),
          sql`COALESCE(jsonb_exists(${aiModels.config}, 'chatConfig'), false)`,
        ),
      );

    const configs: Record<string, AiModelReasoningConfig> = {};
    for (const row of rows) {
      const chatConfig = (row.config as AiModelConfig | null)?.chatConfig;
      if (chatConfig) configs[`${row.providerId}/${row.id}`] = chatConfig;
    }

    return configs;
  };

  /**
   * Personal-scope partial update of `config.chatConfig` (see
   * getModelReasoningConfig for the scoping rationale).
   */
  updateModelReasoningConfig = async (
    id: string,
    providerId: string,
    chatConfig: AiModelReasoningConfig,
  ) => {
    const config: AiModelConfig = { chatConfig };

    return this.db
      .insert(aiModels)
      .values({
        config,
        id,
        providerId,
        updatedAt: new Date(),
        userId: this.userId,
        // No `enabled` / `source` on purpose: a row created only to hold the
        // preference must not flip model visibility (enabled NULL falls back to
        // the builtin default in AiInfraRepos.getEnabledModels) nor claim an
        // origin that would block later remote-sync updates.
        workspaceId: null,
      })
      .onConflictDoUpdate({
        set: {
          // Nested merge: keep sibling config keys (deploymentName, enabledSearch)
          // and previously saved chatConfig fields absent from this partial write.
          config: sql`jsonb_set(
            COALESCE(ai_models.config, '{}'::jsonb),
            '{chatConfig}',
            COALESCE(ai_models.config -> 'chatConfig', '{}'::jsonb) || ${JSON.stringify(chatConfig)}::jsonb
          )`,
          updatedAt: new Date(),
        },
        target: [aiModels.id, aiModels.providerId, aiModels.userId],
        targetWhere: isNull(aiModels.workspaceId),
      });
  };

  toggleModelEnabled = async (value: ToggleAiModelEnableParams) => {
    const now = new Date();
    const insertValues = {
      ...value,
      updatedAt: now,
      userId: this.userId,
      workspaceId: this.workspaceId ?? null,
    } as typeof aiModels.$inferInsert;

    // A toggle without a type (CLI, API) must not let the column default turn a builtin
    // non-chat model (e.g. a speech-to-text card) into a `chat` row, which would leak it into
    // chat pickers. Only the inserted row takes the builtin type; an existing row keeps its own.
    const type =
      value.type ??
      (await this.#resolveDefaultModelTypes(value.providerId, [value.id])).get(value.id);
    if (type) insertValues.type = normalizeAiModelType(type);

    const updateValues: Partial<typeof aiModels.$inferInsert> = {
      enabled: value.enabled,
      updatedAt: now,
    };

    if (value.type) updateValues.type = normalizeAiModelType(value.type);

    return this.db
      .insert(aiModels)
      .values(insertValues)
      .onConflictDoUpdate({
        set: updateValues,
        ...this.conflictTarget(),
      });
  };

  batchUpdateAiModels = async (providerId: string, models: AiProviderModelListItem[]) => {
    // Early return if models array is empty to prevent database insertion error
    if (this.isEmptyArray(models)) {
      return [];
    }

    type BatchAiModelInput = Omit<AiProviderModelListItem, 'id'> &
      Partial<Pick<AiModelSelectItem, 'description' | 'organization' | 'sort'>>;

    const sourceModelIds = new Set(models.map(({ id }) => id));
    const uniqueModelMap = new Map<string, AiProviderModelListItem>();

    for (const model of models) {
      if (!uniqueModelMap.has(model.id)) {
        uniqueModelMap.set(model.id, model);
        continue;
      }

      const sourceModelId = getAutoGeneratedModelSourceId(model.id);
      const shouldKeepLast = !!sourceModelId && sourceModelIds.has(sourceModelId);

      if (shouldKeepLast) uniqueModelMap.set(model.id, model);
    }

    const uniqueModels = [...uniqueModelMap.values()];

    const records = uniqueModels.map(({ id, ...model }) => {
      const input = model as BatchAiModelInput;
      const record: typeof aiModels.$inferInsert = {
        id,
        providerId,
        updatedAt: new Date(),
        userId: this.userId,
        workspaceId: this.workspaceId ?? null,
      };

      // Only include fields that have meaningful values
      // Normalize releasedAt if present
      if (input.releasedAt !== undefined && input.releasedAt !== null) {
        record.releasedAt = this.normalizeReleasedAt(input.releasedAt);
      }

      // Only include abilities if it has at least one truthy capability
      const hasAnyAbility = input.abilities && Object.values(input.abilities).some((v) => v);
      if (hasAnyAbility) {
        record.abilities = input.abilities;
      } else if (input.abilities !== undefined) {
        // Mark as explicitly absent to distinguish from "not provided"
        record.abilities = null;
      }

      // Only include parameters if it has at least one key with non-null value
      const hasAnyParameter =
        input.parameters &&
        Object.keys(input.parameters).length > 0 &&
        Object.values(input.parameters).some((v) => v !== null && v !== undefined);
      if (hasAnyParameter) {
        record.parameters = input.parameters;
      } else if (input.parameters !== undefined) {
        // Mark as explicitly absent
        record.parameters = null;
      }

      // Include type if explicitly provided
      // When type is undefined, omit it to use schema default ('chat')
      // This means we can't distinguish "remote explicitly said chat" vs "remote didn't provide type"
      // Trade-off: remote models with type != 'chat' won't be updated back to 'chat' via batch update
      if (input.type !== undefined) {
        record.type = normalizeAiModelType(input.type);
      }

      // Include other provider-sourced fields if present
      if (input.contextWindowTokens !== undefined && input.contextWindowTokens !== null) {
        record.contextWindowTokens = input.contextWindowTokens;
      }
      if (input.pricing !== undefined && input.pricing !== null) {
        record.pricing = input.pricing;
      }

      // Include user-editable fields if present
      if (input.displayName !== undefined && input.displayName !== null) {
        record.displayName = input.displayName;
      }

      // Include other fields from model
      if (input.config !== undefined) record.config = input.config;
      if (input.enabled !== undefined) record.enabled = input.enabled;
      if (input.settings !== undefined) record.settings = input.settings;
      if (input.source !== undefined) record.source = input.source;

      // Include optional internal fields if present via wider caller payloads.
      if (input.description !== undefined) record.description = input.description;
      if (input.organization !== undefined) record.organization = input.organization;
      if (input.sort !== undefined) record.sort = input.sort;

      return record;
    });

    return this.db
      .insert(aiModels)
      .values(records)
      .onConflictDoUpdate({
        set: {
          // User-editable fields: keep existing DB value; only fill when NULL
          displayName: sql`COALESCE(ai_models.display_name, excluded.display_name)`,
          // Provider-sourced fields: allow remote data to update remote/custom/new models
          // For custom models, users can add a model ID before the provider supports it;
          // when the provider later adds that model, we should fill in pricing/abilities/etc.
          // Only builtin models are fully protected from remote updates.
          // Only update if excluded value is not NULL (meaning it was explicitly provided and valid)
          // Note: empty objects {} may come from schema defaults when field was omitted in payload
          abilities: sql`CASE
            WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL)
              AND excluded.abilities IS NOT NULL
              AND excluded.abilities != '{}'::jsonb
            THEN excluded.abilities
            ELSE ai_models.abilities
          END`,
          contextWindowTokens: sql`CASE
            WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.context_window_tokens IS NOT NULL
            THEN excluded.context_window_tokens
            ELSE ai_models.context_window_tokens
          END`,
          description: sql`CASE
            WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.description IS NOT NULL
            THEN excluded.description
            ELSE ai_models.description
          END`,
          parameters: sql`CASE
            WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL)
              AND excluded.parameters IS NOT NULL
              AND excluded.parameters != '{}'::jsonb
            THEN excluded.parameters
            ELSE ai_models.parameters
          END`,
          pricing: sql`CASE
            WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.pricing IS NOT NULL
            THEN excluded.pricing
            ELSE ai_models.pricing
          END`,
          releasedAt: sql`CASE
            WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.released_at IS NOT NULL
            THEN excluded.released_at
            ELSE ai_models.released_at
          END`,
          type: sql`CASE
            WHEN (ai_models.source = 'remote' OR ai_models.source = 'custom' OR ai_models.source IS NULL) AND excluded.type IS NOT NULL AND excluded.type != 'chat'
            THEN excluded.type
            WHEN ai_models.source = 'builtin' AND excluded.type IS NOT NULL
            THEN COALESCE(ai_models.type, excluded.type)
            ELSE ai_models.type
          END`,
          // source marks model origin (remote/custom/builtin); once set, never
          // overwrite. A preference-only row (source NULL, config.chatConfig —
          // see updateModelReasoningConfig) IS claimed as remote here so the
          // synced metadata stays clearable; clearRemoteModels then demotes
          // rows carrying a chatConfig instead of deleting them, so the
          // personal preference survives either way.
          source: sql`COALESCE(ai_models.source, excluded.source)`,
          updatedAt: sql`excluded.updated_at`,
          // Note: enabled is intentionally omitted to preserve user toggle state
        },
        ...this.conflictTarget(),
      })
      .returning();
  };

  /**
   * Types of builtin model cards, keyed by model id. Prefers the card under the same provider and
   * falls back to a same-id card from another provider (e.g. a custom provider serving a builtin id).
   */
  #resolveDefaultModelTypes = async (providerId: string, modelIds: string[]) => {
    const { loadModels } = await import('@lobechat/business-model-bank/model-config');
    const defaultModels = await loadModels();
    const defaultModelMap = new Map(defaultModels.map((m) => [`${m.providerId}:${m.id}`, m]));

    const types = new Map<string, NonNullable<typeof aiModels.$inferInsert.type>>();
    for (const modelId of modelIds) {
      const defaultModel =
        defaultModelMap.get(`${providerId}:${modelId}`) ??
        defaultModels.find((model) => model.id === modelId);
      if (defaultModel?.type) types.set(modelId, defaultModel.type);
    }

    return types;
  };

  batchToggleAiModels = async (providerId: string, models: string[], enabled: boolean) => {
    // Early return if models array is empty to prevent database insertion error
    if (this.isEmptyArray(models)) {
      return;
    }

    // Get default model list to preserve type information
    const defaultTypes = await this.#resolveDefaultModelTypes(providerId, models);

    // Prepare all records for batch upsert
    const allRecords = models.map((modelId) => {
      const defaultType = defaultTypes.get(modelId);
      const record: typeof aiModels.$inferInsert = this.values({
        enabled,
        id: modelId,
        providerId,
        // if the model is not in the db, it's a builtin model
        source: AiModelSourceEnum.Builtin,
        updatedAt: new Date(),
      });

      // Preserve type if available from default model list
      if (defaultType) record.type = defaultType;

      return record;
    });

    // Use batch upsert to handle both insert and update in a single query
    return this.db
      .insert(aiModels)
      .values(allRecords)
      .onConflictDoUpdate({
        set: {
          enabled: sql`excluded.enabled`,
          updatedAt: sql`excluded.updated_at`,
        },
        ...this.conflictTarget(),
      });
  };

  clearRemoteModels(providerId: string) {
    return this.db.transaction(async (trx) => {
      // A remote row that accumulated a personal reasoning preference
      // (remote-first order: fetched, then the user saved an Effort default —
      // see updateModelReasoningConfig) must not lose it. Demote the row to a
      // preference-only shape (strip remote metadata, drop the remote source)
      // instead of deleting it.
      await trx
        .update(aiModels)
        .set({
          abilities: null,
          config: sql`jsonb_build_object('chatConfig', ${aiModels.config} -> 'chatConfig')`,
          contextWindowTokens: null,
          description: null,
          displayName: null,
          enabled: null,
          organization: null,
          parameters: null,
          pricing: null,
          releasedAt: null,
          settings: null,
          sort: null,
          source: null,
          updatedAt: new Date(),
        })
        .where(
          and(
            eq(aiModels.providerId, providerId),
            eq(aiModels.source, AiModelSourceEnum.Remote),
            // NOT `config -> 'chatConfig' IS NOT NULL`: jsonb null tests in
            // WHERE clauses crash the production engine (see jsonbNullTest)
            sql`COALESCE(${aiModels.config} ->> 'chatConfig', '') <> ''`,
            this.scopeWhere(),
          ),
        );

      return trx
        .delete(aiModels)
        .where(
          and(
            eq(aiModels.providerId, providerId),
            eq(aiModels.source, AiModelSourceEnum.Remote),
            this.scopeWhere(),
          ),
        );
    });
  }

  clearModelsByProvider(providerId: string) {
    return this.db
      .delete(aiModels)
      .where(and(eq(aiModels.providerId, providerId), this.scopeWhere()));
  }

  updateModelsOrder = async (providerId: string, sortMap: AiModelSortMap[]) => {
    // Early return if sortMap array is empty
    if (this.isEmptyArray(sortMap)) {
      return;
    }

    await this.db.transaction(async (tx) => {
      const updates = sortMap.map(({ id, sort, type }) => {
        const now = new Date();
        const insertValues: typeof aiModels.$inferInsert = {
          enabled: true,
          id,
          providerId,
          sort,
          // source: isBuiltin ? 'builtin' : 'custom',
          updatedAt: now,
          userId: this.userId,
          workspaceId: this.workspaceId ?? null,
        };

        if (type) insertValues.type = type;

        const updateValues: Partial<typeof aiModels.$inferInsert> = {
          sort,
          updatedAt: now,
        };

        if (type) updateValues.type = type;

        return tx
          .insert(aiModels)
          .values(insertValues)
          .onConflictDoUpdate({
            set: updateValues,
            ...this.conflictTarget(),
          });
      });

      await Promise.all(updates);
    });
  };
}