无服务器实现openai接口反向代理和额度查询

2023-05-03 11:02:22 浏览数 (1)

使用Cloudflare代理openai接口,并实现简单查询额度。

实现接口代理

  • 将代码部署到Cloudflare的worker平台(其他支持worker的平台也可)
  • 替换自己代码中的api.openai.com为你自己的worker域名,例如 your.worker.domain

查询使用情况

  • 访问地址 https://your.worker.domain}/usage/{sk-key} 即可

Worker 代码

代码语言:javascript复制
// 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);
    }
}

0 人点赞