|
|
|
import express from 'express'; |
|
import cors from 'cors'; |
|
import fetch from 'node-fetch'; |
|
|
|
const app = express(); |
|
const PORT = process.env.PORT || 7860; |
|
|
|
|
|
const TARGET_API_URLS = [ |
|
"https://gpt4fc.deno.dev/zaiwen", |
|
"https://gpt4fc2.deno.dev/zaiwen", |
|
"https://gpt4fc3.deno.dev/zaiwen", |
|
"https://gpt4fc4.deno.dev/zaiwen", |
|
]; |
|
|
|
|
|
app.use(express.json()); |
|
app.use(cors({ |
|
origin: '*', |
|
methods: ['POST', 'OPTIONS'], |
|
allowedHeaders: ['Content-Type', 'Authorization', 'OpenAI-Organization', 'User-Agent'] |
|
})); |
|
|
|
|
|
async function handleCompletions(req, res) { |
|
try { |
|
const requestBody = req.body; |
|
|
|
|
|
for (const apiUrl of TARGET_API_URLS) { |
|
try { |
|
|
|
const headers = { |
|
'Content-Type': 'application/json', |
|
}; |
|
|
|
|
|
['authorization', 'openai-organization', 'user-agent'].forEach(header => { |
|
if (req.headers[header]) { |
|
headers[header] = req.headers[header]; |
|
} |
|
}); |
|
|
|
const response = await fetch(`${apiUrl}/v1/chat/completions`, { |
|
method: 'POST', |
|
headers: headers, |
|
body: JSON.stringify(requestBody) |
|
}); |
|
|
|
|
|
if (!response.ok) { |
|
console.warn( |
|
`Error from target API ${apiUrl}:`, |
|
response.status, |
|
response.statusText |
|
); |
|
continue; |
|
} |
|
|
|
|
|
const responseBody = await response.json(); |
|
|
|
|
|
if ( |
|
responseBody && |
|
responseBody.choices && |
|
responseBody.choices.length > 0 && |
|
responseBody.choices[0].message && |
|
responseBody.choices[0].message.content && |
|
responseBody.choices[0].message.content.trim() !== "" |
|
) { |
|
|
|
return res.status(response.status).json(responseBody); |
|
} else { |
|
console.warn(`API ${apiUrl} returned empty or invalid content. Trying next API.`); |
|
continue; |
|
} |
|
} catch (error) { |
|
console.warn(`Error calling API ${apiUrl}:`, error); |
|
continue; |
|
} |
|
} |
|
|
|
|
|
return res.status(500).send('All APIs failed to return valid content.'); |
|
} catch (error) { |
|
console.error('Error handling /v1/chat/completions:', error); |
|
return res.status(500).send('Internal Server Error'); |
|
} |
|
} |
|
|
|
|
|
app.post('/v1/chat/completions', handleCompletions); |
|
|
|
|
|
app.get('/', (req, res) => { |
|
res.send('API is running'); |
|
}); |
|
|
|
|
|
app.listen(PORT, () => { |
|
console.log(`Server is running on port ${PORT}`); |
|
}); |
|
|
|
|
|
export default app; |
|
|
|
|