大佬的Flutter ChatBot很受到大家的青睐,但是它对部分模型兼容性不是很好,在请求的时候总会发出store
参数,导致Azure OpenAI、Groq等不完全兼容OpenAI SDK的提供商的模型无法在Flutter ChatBot中调用,这个问题也困扰了我很久,今天总算通过Cloudflare Workers反代解决了,下面分享我写的Cloudflare Workers源码,欢迎大家拿去使用
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
if (request.method === 'OPTIONS') {
return handleOptions(request)
}
const targetUrl = new URL(request.url)
targetUrl.hostname = API_BASE_URL
let newRequestBody = null
if (request.method !== 'GET') {
try {
const contentType = request.headers.get('content-type')
if (contentType && contentType.includes('application/json')) {
const bodyJson = await request.json()
if (bodyJson.store !== undefined) {
delete bodyJson.store
}
newRequestBody = JSON.stringify(bodyJson)
} else {
newRequestBody = request.body
}
} catch (error) {
newRequestBody = request.body
}
}
const newHeaders = new Headers(request.headers)
newHeaders.set('Origin', targetUrl.origin)
const newRequest = new Request(targetUrl.toString(), {
method: request.method,
headers: newHeaders,
body: newRequestBody,
redirect: 'follow'
})
try {
const response = await fetch(newRequest)
const newResponse = new Response(response.body, response)
newResponse.headers.set('Access-Control-Allow-Origin', '*')
newResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
newResponse.headers.set('Access-Control-Allow-Headers', '*')
newResponse.headers.set('Access-Control-Expose-Headers', '*')
const originalContentType = response.headers.get('content-type')
if (originalContentType) {
newResponse.headers.set('Content-Type', originalContentType)
}
return newResponse
} catch (error) {
return new Response('Internal Server Error', {
status: 500,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'text/plain'
}
})
}
}
function handleOptions(request) {
const reqHeaders = request.headers
const accessControlRequestHeaders = reqHeaders.get('Access-Control-Request-Headers')
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': accessControlRequestHeaders || '*',
'Access-Control-Max-Age': '86400',
'Access-Control-Expose-Headers': '*'
}
})
}
注意
使用这个源码需要配置一个API_BASE_URL
变量,这个变量的值就是需要反代API的主机名