使用Cloudflare代理openai接口,并实现简单查询额度。
api.openai.com
为你自己的worker域名,例如 your.worker.domain
https://your.worker.domain}/usage/{sk-key}
即可// code from https://www.rehiy.com/post/500
async function openai_get(api, key) {
const resp = await fetch('https://api.openai.com/v1' + api, {
method: 'GET',
headers: {
Authorization: 'Bearer ' + key,
},
});
return resp.json();
}
async function openai_usage(key) {
const today = new Date();
const start_date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-1'
const end_date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate()
const subscription = await openai_get('/dashboard/billing/subscription', key);
const usage = await openai_get(`/dashboard/billing/usage?start_date=${start_date}&end_date=${end_date}`, key);
return new Response(JSON.stringify({
access_until: (new Date(subscription.access_until * 1000)).toISOString(),
hard_limit_usd: subscription.hard_limit_usd,
total_usage: usage.total_usage
}));
}
async function openai_proxy(request) {
const url = new URL(request.url);
const auth = request.headers.get('Authorization');
const backend = request.url.replace(url.host, 'api.openai.com');
const payload = {
method: request.method,
headers: {
Authorization: auth,
},
};
if (request.body) {
payload.body = await request.text();
payload.headers['Content-Type'] = 'application/json';
}
return fetch(backend, payload);
}
export default {
async fetch(request) {
if (request.method === 'OPTIONS') {
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS',
'Access-Control-Allow-Headers': '*',
};
return new Response(null, { headers: corsHeaders });
}
const url = new URL(request.url);
if (url.pathname.startsWith('/usage/')) {
const res = url.pathname.match(/^\/usage\/(.+)$/)
return openai_usage(res[1]);
}
return openai_proxy(request);
}
}