Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 26 additions & 17 deletions src-api/src/app/api/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ interface DetectBody {
baseUrl: string;
apiKey: string;
model?: string;
apiType?: 'anthropic-messages' | 'openai-completions';
}

interface DetectSuccessResponse {
Expand All @@ -317,21 +318,22 @@ interface DetectErrorResponse {
// type DetectResponse = DetectSuccessResponse | DetectErrorResponse;

/**
* Build API URL from base URL
* Handles various base URL formats and ensures proper /v1/messages path
* Build API URL from base URL based on API type.
*/
function buildApiUrl(baseUrl: string): string {
function buildApiUrl(baseUrl: string, apiType?: string): string {
const normalized = baseUrl.replace(/\/$/, '');
const isOpenAI = apiType === 'openai-completions';
const suffix = isOpenAI ? '/chat/completions' : '/messages';

if (normalized.includes('/messages')) {
if (normalized.includes('/chat/completions') || normalized.includes('/messages')) {
return normalized;
}

if (normalized.endsWith('/v1')) {
return `${normalized}/messages`;
return `${normalized}${suffix}`;
}

return `${normalized}/v1/messages`;
return `${normalized}/v1${suffix}`;
}

/**
Expand All @@ -345,31 +347,38 @@ providersRoutes.post('/detect', async (c) => {
return c.json({ error: 'baseUrl and apiKey are required' }, 400);
}

const apiUrl = buildApiUrl(body.baseUrl);
const apiType = body.apiType || 'anthropic-messages';
const apiUrl = buildApiUrl(body.baseUrl, apiType);
const testModel = body.model || DEFAULT_TEST_MODEL;

console.log('[ProvidersAPI] Detecting API connection:', {
baseUrl: body.baseUrl,
apiUrl,
apiType,
model: testModel,
});

const isOpenAI = apiType === 'openai-completions';
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
if (isOpenAI) {
headers['Authorization'] = `Bearer ${body.apiKey}`;
} else {
headers['x-api-key'] = body.apiKey;
headers['anthropic-version'] = '2023-06-01';
}

const requestBody = isOpenAI
? { model: testModel, messages: [{ role: 'user', content: DETECT_TEST_MESSAGE }], max_tokens: 1, stream: false }
: { model: testModel, messages: [{ role: 'user', content: DETECT_TEST_MESSAGE }], max_tokens: 1 };

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), API_TIMEOUT_MS);

try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${body.apiKey}`,
},
body: JSON.stringify({
model: testModel,
messages: [{ role: 'user', content: DETECT_TEST_MESSAGE }],
max_tokens: 1,
stream: false,
}),
headers,
body: JSON.stringify(requestBody),
signal: controller.signal,
});

Expand Down