本代码基于 @zhong_little 大佬的github models worker 分享 修改,解决了Flutter ChatBot不支持Azure OpenAI模型store
参数的问题
user:addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const { method, url } = request
const originalUrl = new URL(url)
if (!originalUrl.pathname.startsWith('/v1/')) {
return new Response('Forbidden', { status: 403 })
}
const allowedMethods = ['OPTIONS', 'GET', 'POST']
if (!allowedMethods.includes(method)) {
return new Response('Method Not Allowed', { status: 405 })
}
if (method === 'OPTIONS') {
return handleOptions()
}
const targetUrl = new URL(request.url)
targetUrl.hostname = 'models.inference.ai.azure.com'
targetUrl.pathname = originalUrl.pathname.replace(/^\/v1/, '')
let newRequestBody = null
if (method === 'POST') {
const bodyJson = await request.json()
if (bodyJson.store !== undefined) {
delete bodyJson.store
}
newRequestBody = JSON.stringify(bodyJson)
}
const newRequest = new Request(targetUrl.toString(), {
method: request.method,
headers: request.headers,
body: newRequestBody,
redirect: 'follow'
})
try {
const response = await fetch(newRequest)
if (originalUrl.pathname === '/v1/models') {
const data = await response.json()
if (Array.isArray(data)) {
let modifiedData = data.map(item => {
const newItem = { ...item }
if ('id' in newItem) {
newItem.id_original = newItem.id
delete newItem.id
}
if ('name' in newItem) {
newItem.id = newItem.name
delete newItem.name
}
return newItem
})
modifiedData = JSON.stringify(
{'data': modifiedData}
)
return new Response(modifiedData, {
status: response.status,
statusText: response.statusText,
headers: {
...response.headers,
'Content-Type': 'application/json'
}
})
} else {
return response
}
}
return response
} catch (error) {
return new Response('Internal Server Error', { status: 500 })
}
}
function handleOptions() {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400'
}
})
}