mirror of
https://github.com/router-for-me/Cli-Proxy-API-Management-Center.git
synced 2026-06-16 21:03:58 +08:00
feat(codex): add model discovery via /v1/models
This commit is contained in:
@@ -250,6 +250,19 @@
|
||||
"codex_models_label": "Custom Models (Optional):",
|
||||
"codex_models_hint": "Leave empty to allow all models, or add name[, alias] entries to limit/alias them.",
|
||||
"codex_models_add_btn": "Add Model",
|
||||
"codex_models_fetch_button": "Fetch via /v1/models",
|
||||
"codex_models_fetch_title": "Pick Models from /v1/models",
|
||||
"codex_models_fetch_hint": "Call GET /v1/models using the Base URL above, sending the API key as Bearer (if provided) and merging your custom headers.",
|
||||
"codex_models_fetch_url_label": "Request URL",
|
||||
"codex_models_fetch_refresh": "Refresh",
|
||||
"codex_models_fetch_loading": "Fetching models from /v1/models...",
|
||||
"codex_models_fetch_empty": "No models returned. Please check Base URL, API key, or headers.",
|
||||
"codex_models_fetch_error": "Failed to fetch models",
|
||||
"codex_models_fetch_apply": "Add selected models",
|
||||
"codex_models_search_label": "Search models",
|
||||
"codex_models_search_placeholder": "Filter by name, alias, or description",
|
||||
"codex_models_search_empty": "No models match your search. Try a different keyword.",
|
||||
"codex_models_fetch_added": "{{count}} new models added",
|
||||
"codex_models_count": "Models Count",
|
||||
"codex_edit_modal_title": "Edit Codex API Configuration",
|
||||
"codex_edit_modal_key_label": "API Key:",
|
||||
|
||||
@@ -250,6 +250,19 @@
|
||||
"codex_models_label": "Пользовательские модели (необязательно):",
|
||||
"codex_models_hint": "Оставьте пустым, чтобы разрешить все модели, или добавьте записи name[, alias], чтобы ограничить/переименовать их.",
|
||||
"codex_models_add_btn": "Добавить модель",
|
||||
"codex_models_fetch_button": "Получить через /v1/models",
|
||||
"codex_models_fetch_title": "Выбор моделей из Codex /v1/models",
|
||||
"codex_models_fetch_hint": "Вызывает GET /v1/models по спецификации OpenAI. По умолчанию отправляет API-ключ как Bearer (если указан) и объединяет его с пользовательскими заголовками.",
|
||||
"codex_models_fetch_url_label": "URL запроса",
|
||||
"codex_models_fetch_refresh": "Обновить",
|
||||
"codex_models_fetch_loading": "Получение моделей из /v1/models...",
|
||||
"codex_models_fetch_empty": "Модели не получены. Проверьте Base URL, API-ключ или заголовки.",
|
||||
"codex_models_fetch_error": "Не удалось получить модели",
|
||||
"codex_models_fetch_apply": "Добавить выбранные модели",
|
||||
"codex_models_search_label": "Поиск моделей",
|
||||
"codex_models_search_placeholder": "Фильтр по имени, псевдониму или описанию",
|
||||
"codex_models_search_empty": "Модели по запросу не найдены. Попробуйте другой запрос.",
|
||||
"codex_models_fetch_added": "Добавлено новых моделей: {{count}}",
|
||||
"codex_models_count": "Количество моделей",
|
||||
"codex_edit_modal_title": "Редактирование конфигурации Codex API",
|
||||
"codex_edit_modal_key_label": "API-ключ:",
|
||||
|
||||
@@ -250,6 +250,19 @@
|
||||
"codex_models_label": "自定义模型 (可选):",
|
||||
"codex_models_hint": "为空表示使用全部模型;可填写 name[, alias] 以限制或重命名模型。",
|
||||
"codex_models_add_btn": "添加模型",
|
||||
"codex_models_fetch_button": "从 /v1/models 获取",
|
||||
"codex_models_fetch_title": "从 /v1/models 选择模型",
|
||||
"codex_models_fetch_hint": "使用上方 Base URL 调用 /v1/models 端点,附带 API Key(Bearer)与自定义请求头。",
|
||||
"codex_models_fetch_url_label": "请求地址",
|
||||
"codex_models_fetch_refresh": "重新获取",
|
||||
"codex_models_fetch_loading": "正在从 /v1/models 获取模型列表...",
|
||||
"codex_models_fetch_empty": "未获取到模型,请检查端点或鉴权信息。",
|
||||
"codex_models_fetch_error": "获取模型失败",
|
||||
"codex_models_fetch_apply": "添加所选模型",
|
||||
"codex_models_search_label": "搜索模型",
|
||||
"codex_models_search_placeholder": "按名称、别名或描述筛选",
|
||||
"codex_models_search_empty": "没有匹配的模型,请更换关键字试试。",
|
||||
"codex_models_fetch_added": "已添加 {{count}} 个新模型",
|
||||
"codex_models_count": "模型数量",
|
||||
"codex_edit_modal_title": "编辑Codex API配置",
|
||||
"codex_edit_modal_key_label": "API密钥:",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocation, useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
@@ -6,16 +6,18 @@ import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { HeaderInputList } from '@/components/ui/HeaderInputList';
|
||||
import { ModelInputList } from '@/components/ui/ModelInputList';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
import { ToggleSwitch } from '@/components/ui/ToggleSwitch';
|
||||
import { useEdgeSwipeBack } from '@/hooks/useEdgeSwipeBack';
|
||||
import { SecondaryScreenShell } from '@/components/common/SecondaryScreenShell';
|
||||
import { providersApi } from '@/services/api';
|
||||
import { modelsApi, providersApi } from '@/services/api';
|
||||
import { useAuthStore, useConfigStore, useNotificationStore } from '@/stores';
|
||||
import type { ProviderKeyConfig } from '@/types';
|
||||
import { buildHeaderObject, headersToEntries } from '@/utils/headers';
|
||||
import { entriesToModels, modelsToEntries } from '@/components/ui/modelInputListUtils';
|
||||
import { excludedModelsToText, parseExcludedModels } from '@/components/providers/utils';
|
||||
import type { ProviderFormState } from '@/components/providers';
|
||||
import type { ModelInfo } from '@/utils/models';
|
||||
import layoutStyles from './AiProvidersEditLayout.module.scss';
|
||||
import styles from './AiProvidersPage.module.scss';
|
||||
|
||||
@@ -41,6 +43,12 @@ const parseIndexParam = (value: string | undefined) => {
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
};
|
||||
|
||||
const getErrorMessage = (err: unknown) => {
|
||||
if (err instanceof Error) return err.message;
|
||||
if (typeof err === 'string') return err;
|
||||
return '';
|
||||
};
|
||||
|
||||
export function AiProvidersCodexEditPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -61,6 +69,15 @@ export function AiProvidersCodexEditPage() {
|
||||
const [error, setError] = useState('');
|
||||
const [form, setForm] = useState<ProviderFormState>(() => buildEmptyForm());
|
||||
|
||||
const [modelDiscoveryOpen, setModelDiscoveryOpen] = useState(false);
|
||||
const [modelDiscoveryEndpoint, setModelDiscoveryEndpoint] = useState('');
|
||||
const [discoveredModels, setDiscoveredModels] = useState<ModelInfo[]>([]);
|
||||
const [modelDiscoveryFetching, setModelDiscoveryFetching] = useState(false);
|
||||
const [modelDiscoveryError, setModelDiscoveryError] = useState('');
|
||||
const [modelDiscoverySearch, setModelDiscoverySearch] = useState('');
|
||||
const [modelDiscoverySelected, setModelDiscoverySelected] = useState<Set<string>>(new Set());
|
||||
const autoFetchSignatureRef = useRef<string>('');
|
||||
|
||||
const hasIndexParam = typeof params.index === 'string';
|
||||
const editIndex = useMemo(() => parseIndexParam(params.index), [params.index]);
|
||||
const invalidIndexParam = hasIndexParam && editIndex === null;
|
||||
@@ -138,6 +155,133 @@ export function AiProvidersCodexEditPage() {
|
||||
|
||||
const canSave = !disableControls && !saving && !loading && !invalidIndexParam && !invalidIndex;
|
||||
|
||||
const discoveredModelsFiltered = useMemo(() => {
|
||||
const filter = modelDiscoverySearch.trim().toLowerCase();
|
||||
if (!filter) return discoveredModels;
|
||||
return discoveredModels.filter((model) => {
|
||||
const name = (model.name || '').toLowerCase();
|
||||
const alias = (model.alias || '').toLowerCase();
|
||||
const description = (model.description || '').toLowerCase();
|
||||
return name.includes(filter) || alias.includes(filter) || description.includes(filter);
|
||||
});
|
||||
}, [discoveredModels, modelDiscoverySearch]);
|
||||
|
||||
const mergeDiscoveredModels = useCallback(
|
||||
(selectedModels: ModelInfo[]) => {
|
||||
if (!selectedModels.length) return;
|
||||
|
||||
let addedCount = 0;
|
||||
setForm((prev) => {
|
||||
const mergedMap = new Map<string, { name: string; alias: string }>();
|
||||
prev.modelEntries.forEach((entry) => {
|
||||
const name = entry.name.trim();
|
||||
if (!name) return;
|
||||
mergedMap.set(name.toLowerCase(), { name, alias: entry.alias?.trim() || '' });
|
||||
});
|
||||
|
||||
selectedModels.forEach((model) => {
|
||||
const name = String(model.name ?? '').trim();
|
||||
if (!name) return;
|
||||
const key = name.toLowerCase();
|
||||
if (mergedMap.has(key)) return;
|
||||
mergedMap.set(key, { name, alias: model.alias ?? '' });
|
||||
addedCount += 1;
|
||||
});
|
||||
|
||||
const mergedEntries = Array.from(mergedMap.values());
|
||||
return {
|
||||
...prev,
|
||||
modelEntries: mergedEntries.length ? mergedEntries : [{ name: '', alias: '' }],
|
||||
};
|
||||
});
|
||||
|
||||
if (addedCount > 0) {
|
||||
showNotification(t('ai_providers.codex_models_fetch_added', { count: addedCount }), 'success');
|
||||
}
|
||||
},
|
||||
[setForm, showNotification, t]
|
||||
);
|
||||
|
||||
const fetchCodexModelDiscovery = useCallback(async () => {
|
||||
setModelDiscoveryFetching(true);
|
||||
setModelDiscoveryError('');
|
||||
|
||||
try {
|
||||
const headerObject = buildHeaderObject(form.headers);
|
||||
const hasCustomAuthorization = Object.keys(headerObject).some(
|
||||
(key) => key.toLowerCase() === 'authorization'
|
||||
);
|
||||
const apiKey = form.apiKey.trim() || undefined;
|
||||
const list = await modelsApi.fetchV1ModelsViaApiCall(
|
||||
form.baseUrl ?? '',
|
||||
hasCustomAuthorization ? undefined : apiKey,
|
||||
headerObject
|
||||
);
|
||||
setDiscoveredModels(list);
|
||||
} catch (err: unknown) {
|
||||
setDiscoveredModels([]);
|
||||
const message = getErrorMessage(err);
|
||||
setModelDiscoveryError(`${t('ai_providers.codex_models_fetch_error')}: ${message}`);
|
||||
} finally {
|
||||
setModelDiscoveryFetching(false);
|
||||
}
|
||||
}, [form.apiKey, form.baseUrl, form.headers, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!modelDiscoveryOpen) {
|
||||
autoFetchSignatureRef.current = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const nextEndpoint = modelsApi.buildV1ModelsEndpoint(form.baseUrl ?? '');
|
||||
setModelDiscoveryEndpoint(nextEndpoint);
|
||||
setDiscoveredModels([]);
|
||||
setModelDiscoverySearch('');
|
||||
setModelDiscoverySelected(new Set());
|
||||
setModelDiscoveryError('');
|
||||
|
||||
if (!nextEndpoint) return;
|
||||
|
||||
const headerObject = buildHeaderObject(form.headers);
|
||||
const hasCustomAuthorization = Object.keys(headerObject).some(
|
||||
(key) => key.toLowerCase() === 'authorization'
|
||||
);
|
||||
const hasApiKeyField = Boolean(form.apiKey.trim());
|
||||
const canAutoFetch = hasApiKeyField || hasCustomAuthorization;
|
||||
|
||||
if (!canAutoFetch) return;
|
||||
|
||||
const headerSignature = Object.entries(headerObject)
|
||||
.sort(([a], [b]) => a.toLowerCase().localeCompare(b.toLowerCase()))
|
||||
.map(([key, value]) => `${key}:${value}`)
|
||||
.join('|');
|
||||
const signature = `${nextEndpoint}||${form.apiKey.trim()}||${headerSignature}`;
|
||||
if (autoFetchSignatureRef.current === signature) return;
|
||||
autoFetchSignatureRef.current = signature;
|
||||
|
||||
void fetchCodexModelDiscovery();
|
||||
}, [fetchCodexModelDiscovery, form.apiKey, form.baseUrl, form.headers, modelDiscoveryOpen]);
|
||||
|
||||
const toggleModelDiscoverySelection = (name: string) => {
|
||||
setModelDiscoverySelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(name)) {
|
||||
next.delete(name);
|
||||
} else {
|
||||
next.add(name);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleApplyDiscoveredModels = () => {
|
||||
const selectedModels = discoveredModels.filter((model) => modelDiscoverySelected.has(model.name));
|
||||
if (selectedModels.length) {
|
||||
mergeDiscoveredModels(selectedModels);
|
||||
}
|
||||
setModelDiscoveryOpen(false);
|
||||
};
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (!canSave) return;
|
||||
|
||||
@@ -195,6 +339,15 @@ export function AiProvidersCodexEditPage() {
|
||||
updateConfigValue,
|
||||
]);
|
||||
|
||||
const canOpenModelDiscovery =
|
||||
!disableControls &&
|
||||
!saving &&
|
||||
!loading &&
|
||||
!invalidIndexParam &&
|
||||
!invalidIndex &&
|
||||
Boolean((form.baseUrl ?? '').trim());
|
||||
const canApplyModelDiscovery = !disableControls && !saving && !modelDiscoveryFetching;
|
||||
|
||||
return (
|
||||
<SecondaryScreenShell
|
||||
ref={swipeRef}
|
||||
@@ -297,6 +450,14 @@ export function AiProvidersCodexEditPage() {
|
||||
>
|
||||
{t('ai_providers.codex_models_add_btn')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => setModelDiscoveryOpen(true)}
|
||||
disabled={!canOpenModelDiscovery}
|
||||
>
|
||||
{t('ai_providers.codex_models_fetch_button')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.sectionHint}>{t('ai_providers.codex_models_hint')}</div>
|
||||
@@ -328,6 +489,103 @@ export function AiProvidersCodexEditPage() {
|
||||
/>
|
||||
<div className="hint">{t('ai_providers.excluded_models_hint')}</div>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
open={modelDiscoveryOpen}
|
||||
title={t('ai_providers.codex_models_fetch_title')}
|
||||
onClose={() => setModelDiscoveryOpen(false)}
|
||||
width={720}
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => setModelDiscoveryOpen(false)}
|
||||
disabled={modelDiscoveryFetching}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleApplyDiscoveredModels}
|
||||
disabled={!canApplyModelDiscovery}
|
||||
>
|
||||
{t('ai_providers.codex_models_fetch_apply')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={styles.openaiModelsContent}>
|
||||
<div className={styles.sectionHint}>{t('ai_providers.codex_models_fetch_hint')}</div>
|
||||
<div className={styles.openaiModelsEndpointSection}>
|
||||
<label className={styles.openaiModelsEndpointLabel}>
|
||||
{t('ai_providers.codex_models_fetch_url_label')}
|
||||
</label>
|
||||
<div className={styles.openaiModelsEndpointControls}>
|
||||
<input
|
||||
className={`input ${styles.openaiModelsEndpointInput}`}
|
||||
readOnly
|
||||
value={modelDiscoveryEndpoint}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => void fetchCodexModelDiscovery()}
|
||||
loading={modelDiscoveryFetching}
|
||||
disabled={disableControls || saving}
|
||||
>
|
||||
{t('ai_providers.codex_models_fetch_refresh')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Input
|
||||
label={t('ai_providers.codex_models_search_label')}
|
||||
placeholder={t('ai_providers.codex_models_search_placeholder')}
|
||||
value={modelDiscoverySearch}
|
||||
onChange={(e) => setModelDiscoverySearch(e.target.value)}
|
||||
disabled={modelDiscoveryFetching}
|
||||
/>
|
||||
{modelDiscoveryError && <div className="error-box">{modelDiscoveryError}</div>}
|
||||
{modelDiscoveryFetching ? (
|
||||
<div className={styles.sectionHint}>{t('ai_providers.codex_models_fetch_loading')}</div>
|
||||
) : discoveredModels.length === 0 ? (
|
||||
<div className={styles.sectionHint}>{t('ai_providers.codex_models_fetch_empty')}</div>
|
||||
) : discoveredModelsFiltered.length === 0 ? (
|
||||
<div className={styles.sectionHint}>{t('ai_providers.codex_models_search_empty')}</div>
|
||||
) : (
|
||||
<div className={styles.modelDiscoveryList}>
|
||||
{discoveredModelsFiltered.map((model) => {
|
||||
const checked = modelDiscoverySelected.has(model.name);
|
||||
return (
|
||||
<label
|
||||
key={model.name}
|
||||
className={`${styles.modelDiscoveryRow} ${
|
||||
checked ? styles.modelDiscoveryRowSelected : ''
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => toggleModelDiscoverySelection(model.name)}
|
||||
/>
|
||||
<div className={styles.modelDiscoveryMeta}>
|
||||
<div className={styles.modelDiscoveryName}>
|
||||
{model.name}
|
||||
{model.alias && (
|
||||
<span className={styles.modelDiscoveryAlias}>{model.alias}</span>
|
||||
)}
|
||||
</div>
|
||||
{model.description && (
|
||||
<div className={styles.modelDiscoveryDesc}>{model.description}</div>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
@@ -101,6 +101,40 @@ export const modelsApi = {
|
||||
return normalizeModelList(payload, { dedupe: true });
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch models from /v1/models endpoint via api-call.
|
||||
* Useful when the configured baseUrl is the upstream host root (e.g. https://api.example.com).
|
||||
*/
|
||||
async fetchV1ModelsViaApiCall(
|
||||
baseUrl: string,
|
||||
apiKey?: string,
|
||||
headers: Record<string, string> = {}
|
||||
) {
|
||||
const endpoint = buildV1ModelsEndpoint(baseUrl);
|
||||
if (!endpoint) {
|
||||
throw new Error('Invalid base url');
|
||||
}
|
||||
|
||||
const resolvedHeaders = { ...headers };
|
||||
const hasAuthHeader = Boolean(resolvedHeaders.Authorization || resolvedHeaders.authorization);
|
||||
if (apiKey && !hasAuthHeader) {
|
||||
resolvedHeaders.Authorization = `Bearer ${apiKey}`;
|
||||
}
|
||||
|
||||
const result = await apiCallApi.request({
|
||||
method: 'GET',
|
||||
url: endpoint,
|
||||
header: Object.keys(resolvedHeaders).length ? resolvedHeaders : undefined
|
||||
});
|
||||
|
||||
if (result.statusCode < 200 || result.statusCode >= 300) {
|
||||
throw new Error(getApiCallErrorMessage(result));
|
||||
}
|
||||
|
||||
const payload = result.body ?? result.bodyText;
|
||||
return normalizeModelList(payload, { dedupe: true });
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch models from /models endpoint via api-call (for OpenAI provider discovery)
|
||||
*/
|
||||
@@ -134,6 +168,10 @@ export const modelsApi = {
|
||||
return normalizeModelList(payload, { dedupe: true });
|
||||
},
|
||||
|
||||
buildV1ModelsEndpoint(baseUrl: string) {
|
||||
return buildV1ModelsEndpoint(baseUrl);
|
||||
},
|
||||
|
||||
buildClaudeModelsEndpoint(baseUrl: string) {
|
||||
return buildClaudeModelsEndpoint(baseUrl);
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user