sessionModel.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import type { ModelOption } from '@shared/types'
  2. import { record, string } from '@/utils/normalize'
  3. export interface SessionModelSelection {
  4. model: string
  5. provider?: string
  6. }
  7. /**
  8. * The model chooser uses this exact value for its option IDs. Providers may
  9. * themselves contain colons, so callers must compare the whole value instead
  10. * of splitting it back into provider and model parts.
  11. */
  12. export function modelChoiceId(option: Pick<ModelOption, 'id' | 'provider'>): string {
  13. return `${option.provider}:${option.id}`
  14. }
  15. export function modelForChoiceId(options: ModelOption[], choiceId: string): ModelOption | undefined {
  16. return options.find(option => modelChoiceId(option) === choiceId)
  17. }
  18. export function modelForSession(options: ModelOption[], model?: string, provider?: string): ModelOption | undefined {
  19. const id = model?.trim()
  20. if (!id) return undefined
  21. const normalizedId = id.toLocaleLowerCase()
  22. const normalizedProvider = provider?.trim().toLocaleLowerCase() || ''
  23. const exact = options.find(option => option.id.toLocaleLowerCase() === normalizedId
  24. && (!normalizedProvider || option.provider.toLocaleLowerCase() === normalizedProvider))
  25. if (exact) return exact
  26. const byId = options.find(option => option.id.toLocaleLowerCase() === normalizedId)
  27. if (byId) return byId
  28. return { id, name: id, provider: provider?.trim() || '' }
  29. }
  30. export function modelSelectionFromSessionInfo(payload: unknown): SessionModelSelection | undefined {
  31. const source = record(payload)
  32. const info = record(source.info)
  33. const model = string(source.model ?? info.model).trim()
  34. if (!model) return undefined
  35. const provider = string(source.provider ?? info.provider).trim()
  36. return { model, provider: provider || undefined }
  37. }