57 lines
1.9 KiB
TypeScript
57 lines
1.9 KiB
TypeScript
import { BaseProvider } from "./BaseProvider";
|
|
import { OpenAIProvider } from "./OpenAIProvider";
|
|
import { providerApiService } from '@electron/service/provider-api-service';
|
|
import type { ProviderAccount } from '@runtime/lib/providers';
|
|
import { getProviderTypeInfo } from '@runtime/lib/providers';
|
|
|
|
function normalizeBaseUrl(baseUrl?: string): string | undefined {
|
|
const trimmed = baseUrl?.trim();
|
|
if (!trimmed) {
|
|
return undefined;
|
|
}
|
|
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) {
|
|
return trimmed;
|
|
}
|
|
return `https://${trimmed}`;
|
|
}
|
|
|
|
function resolveProviderBaseUrl(account: ProviderAccount): string | undefined {
|
|
return normalizeBaseUrl(account.baseUrl)
|
|
|| normalizeBaseUrl(account.metadata?.resourceUrl)
|
|
|| getProviderTypeInfo(account.vendorId)?.defaultBaseUrl;
|
|
}
|
|
|
|
function resolveProviderApiProtocol(account: ProviderAccount): ProviderAccount['apiProtocol'] | undefined {
|
|
return account.apiProtocol || getProviderTypeInfo(account.vendorId)?.apiProtocol;
|
|
}
|
|
|
|
export function createProvider(accountId: string): BaseProvider {
|
|
const account = providerApiService.getAccounts().find((a) => a.id === accountId);
|
|
if (!account) {
|
|
throw new Error(`Provider account ${accountId} not found`);
|
|
}
|
|
|
|
const apiKeyResult = providerApiService.getApiKey(accountId);
|
|
const apiKey = apiKeyResult.apiKey;
|
|
if (!apiKey) {
|
|
throw new Error(`API key for account ${accountId} not found`);
|
|
}
|
|
|
|
const baseURL = resolveProviderBaseUrl(account);
|
|
if (!baseURL) {
|
|
throw new Error(`Base URL for account ${accountId} not found`);
|
|
}
|
|
|
|
switch (resolveProviderApiProtocol(account)) {
|
|
case 'anthropic-messages':
|
|
throw new Error('Anthropic provider not yet implemented');
|
|
case 'openai-completions':
|
|
case 'openai-responses':
|
|
default:
|
|
return new OpenAIProvider(apiKey, baseURL, account.headers);
|
|
}
|
|
}
|
|
|
|
export * from './BaseProvider';
|
|
export { OpenAIProvider };
|