前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >无服务器实现openai接口反向代理和额度查询

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

作者头像
若海
发布2023-05-03 11:02:22
3.1K0
发布2023-05-03 11:02:22
举报
文章被收录于专栏:云原生拾遗云原生拾遗

使用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);
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023年05月01日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 实现接口代理
  • 查询使用情况
  • Worker 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档