Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

modelFamilyGrouping.ts

208 lines7.1 KB

1import {
2 PROVIDER_DISPLAY_NAMES,
3 type ProviderDriverKind,
4 type ProviderOptionDescriptor,
5 type ProviderOptionSelection,
6 type ModelCapabilities,
7 type ServerProviderModel,
8} from "@t3tools/contracts";
9import { getProviderOptionCurrentValue, getProviderOptionDescriptors } from "@t3tools/shared/model";
10​
11/**
12 * The descriptor id used for the primary reasoning-effort select option.
13 * Providers expose reasoning level through different descriptor ids (`effort`,
14 * `reasoningEffort`, `variant`); the first select descriptor on a model's
15 * capabilities is treated as the reasoning-level control, matching the
16 * convention in {@link getComposerProviderState} and {@link TraitsPicker}.
17 */
18const REASONING_DESCRIPTOR_IDS = new Set([
19 "effort",
20 "reasoningEffort",
21 "variant",
22 "reasoning",
23 "thinking",
24]);
25​
26export interface ReasoningLevelOption {
27 readonly id: string;
28 readonly label: string;
29 readonly isDefault: boolean;
31​
32export interface ReasoningLevelDescriptor {
33 readonly descriptorId: string;
34 readonly label: string;
35 readonly currentValue: string | null;
36 readonly options: ReadonlyArray<ReasoningLevelOption>;
38​
39/**
40 * Extract the reasoning-level select descriptor from a model's capabilities.
41 * Returns the first select descriptor whose id is a known reasoning id, or
42 * the first select descriptor overall when none match by id (preserving the
43 * existing "primary select descriptor" convention). Returns `null` when the
44 * model exposes no select options.
45 */
46export function getReasoningLevelDescriptor(input: {
47 readonly caps: ModelCapabilities;
48 readonly selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
49}): ReasoningLevelDescriptor | null {
50 const descriptors = getProviderOptionDescriptors({
51 caps: input.caps,
52 selections: input.selections,
53 });
54 const selectDescriptors = descriptors.filter(
55 (descriptor): descriptor is Extract<ProviderOptionDescriptor, { type: "select" }> =>
56 descriptor.type === "select",
57 );
58 if (selectDescriptors.length === 0) {
59 return null;
60 }
61 const descriptor =
62 selectDescriptors.find((candidate) => REASONING_DESCRIPTOR_IDS.has(candidate.id)) ??
63 selectDescriptors[0]!;
64 const currentValue = getProviderOptionCurrentValue(descriptor);
65 return {
66 descriptorId: descriptor.id,
67 label: descriptor.label,
68 currentValue: typeof currentValue === "string" ? currentValue : null,
69 options: descriptor.options.map((option) => ({
70 id: option.id,
71 label: option.label,
72 isDefault: Boolean(option.isDefault),
73 })),
74 };
76​
77/**
78 * Read the current reasoning level value from a stored options array,
79 * resolving against the descriptor's default when no explicit selection
80 * exists. Returns `null` when the model has no reasoning descriptor.
81 */
82export function resolveReasoningLevel(input: {
83 readonly caps: ModelCapabilities;
84 readonly selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
85}): string | null {
86 const descriptor = getReasoningLevelDescriptor(input);
87 return descriptor?.currentValue ?? null;
89​
90/**
91 * Produce the next options array after changing the reasoning level, leaving
92 * every other option untouched. Returns `undefined` when the model has no
93 * reasoning descriptor (so callers can short-circuit).
94 */
95export function withReasoningLevelChange(input: {
96 readonly caps: ModelCapabilities;
97 readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;
98 readonly nextValue: string;
99}): ReadonlyArray<ProviderOptionSelection> | undefined {
100 const descriptor = getReasoningLevelDescriptor({
101 caps: input.caps,
102 selections: input.selections,
103 });
104 if (!descriptor) {
105 return undefined;
106 }
107 const existing = input.selections ?? [];
108 const filtered = existing.filter((selection) => selection.id !== descriptor.descriptorId);
109 return [...filtered, { id: descriptor.descriptorId, value: input.nextValue }];
111​
112/**
113 * Derive a clean "family" display name from a model slug + provider. Strips
114 * trailing reasoning-effort qualifiers (e.g. `-low`, `-high`, `:medium`) that
115 * some providers append to variant slugs, then falls back to the raw name.
116 */
117export function getModelFamilyLabel(
118 slug: string,
119 provider: ProviderDriverKind,
120 fallbackName?: string,
121): string {
122 const stripped = stripReasoningQualifier(slug);
123 if (stripped.length > 0 && stripped !== slug) {
124 return humanizeSlug(stripped);
125 }
126 if (fallbackName && fallbackName.length > 0) {
127 return fallbackName;
128 }
129 return humanizeSlug(slug);
131​
132function stripReasoningQualifier(slug: string): string {
133 return slug.replace(/[-_:](?:low|medium|minimal|high|max|extended|none)$/iu, "");
135​
136function humanizeSlug(slug: string): string {
137 return slug
138 .replace(/[_-]+/g, " ")
139 .replace(/([a-z])([A-Z])/g, "$1 $2")
140 .replace(/\b\w/g, (char) => char.toUpperCase())
141 .trim();
143​
144/**
145 * Resolve the provider display name for a driver kind, using the canonical
146 * contracts constant and falling back to a title-cased kind slug.
147 */
148export function getProviderGroupLabel(driverKind: ProviderDriverKind): string {
149 return PROVIDER_DISPLAY_NAMES[driverKind] ?? humanizeSlug(driverKind);
151​
152/**
153 * Group a flat list of items by their provider (driver kind), preserving the
154 * first-appearance order of providers. Each group keeps its items in their
155 * original relative order. Used by the model picker to render provider logo
156 * headers above each provider's models in favorites and search views.
157 */
158export function groupByProvider<T extends { readonly driverKind: ProviderDriverKind }>(
159 items: ReadonlyArray<T>,
160): ReadonlyArray<{ readonly driverKind: ProviderDriverKind; readonly items: readonly T[] }> {
161 const order: ProviderDriverKind[] = [];
162 const buckets = new Map<ProviderDriverKind, T[]>();
163 for (const item of items) {
164 const bucket = buckets.get(item.driverKind);
165 if (bucket) {
166 bucket.push(item);
167 } else {
168 buckets.set(item.driverKind, [item]);
169 order.push(item.driverKind);
170 }
171 }
172 return order.map((driverKind) => ({
173 driverKind,
174 items: buckets.get(driverKind)!,
175 }));
177​
178/**
179 * Look up a model's capabilities by slug within an instance's model snapshot.
180 * Returns an empty-capabilities object when the model is not found so callers
181 * can treat the result uniformly.
182 */
183export function findModelCapabilities(
184 models: ReadonlyArray<ServerProviderModel>,
185 slug: string,
186): ModelCapabilities {
187 return (
188 models.find((candidate) => candidate.slug === slug)?.capabilities ?? {
189 optionDescriptors: [],
190 }
191 );
193​
194/**
195 * Read the reasoning level for a model from its capabilities + stored
196 * selections, returning the option label (e.g. "High") rather than the id.
197 * Returns `null` when the model has no reasoning descriptor.
198 */
199export function resolveReasoningLevelLabel(input: {
200 readonly caps: ModelCapabilities;
201 readonly selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;
202}): string | null {
203 const descriptor = getReasoningLevelDescriptor(input);
204 if (!descriptor || !descriptor.currentValue) {
205 return null;
206 }
207 return descriptor.options.find((option) => option.id === descriptor.currentValue)?.label ?? null;