| 9 | provider: Provider |
| 10 | apiUrl: string |
| 11 | apiKey: string |
| 12 | } |
| 13 | |
| 14 | function toOpenAIMessages(messages: ChatMessage[], supportsVision: boolean) { |
| 15 | return messages.map(m => { |
| 16 | if (m.image && supportsVision) { |
| 17 | return { |
| 18 | role: m.role, |
| 19 | content: [ |
| 20 | ...(m.content ? [{ type: 'text', text: m.content }] : []), |
| 21 | { |
| 22 | type: 'image_url', |
| 23 | image_url: { url: `data:${m.image.mimeType};base64,${m.image.data}` } |
| 24 | } |
| 25 | ] |
| 26 | } |
| 27 | } |
| 28 | return { role: m.role, content: m.content } |
| 29 | }) |
| 30 | } |
| 31 | |
| 32 | export async function streamOpenAICompatible({ req, res, provider, apiUrl, apiKey }: StreamArgs) { |
| 33 | initSSE(res) |
| 34 | try { |
| 35 | const { model, messages }: ChatRequest = req.body |
| 36 | const chatModel = getChatModel(model) |
| 37 | |
| 38 | if (!chatModel || chatModel.provider !== provider) { |
| 39 | sendError(res, `unsupported model: ${model}`) |
| 40 | sendDone(res) |
| 41 | return |
| 42 | } |
| 43 | |
| 44 | const response = await fetch(apiUrl, { |
| 45 | method: 'POST', |
| 46 | headers: { |
| 47 | 'Content-Type': 'application/json', |
| 48 | 'Authorization': `Bearer ${apiKey}` |
| 49 | }, |
| 50 | body: JSON.stringify({ |
| 51 | model: chatModel.modelId, |
| 52 | messages: toOpenAIMessages(messages, chatModel.supportsVision), |
| 53 | stream: true |
| 54 | }) |
| 55 | }) |
| 56 | |
| 57 | if (!response.ok) { |
| 58 | const detail = await response.text() |
| 59 | console.error(`${provider} error:`, response.status, detail) |
| 60 | sendError(res, `provider error (${response.status})`) |
| 61 | sendDone(res) |
| 62 | return |
| 63 | } |
| 64 | |
| 65 | const parse = createSSEParser(data => { |
| 66 | if (data === '[DONE]') return |
| 67 | try { |
| 68 | const parsed = JSON.parse(data) |