使用 Cloudflare Worker 实现无服务器部署ChatGPT聊天界面

使用Cloudflare部署Ai聊天前端界面,无需置备服务器,只要一个可以接入cloudflare的域名即可。

代码摘自开源项目 https://github.com/open-tdp/openai-chat

  • 支持基于gpt-3.5-turbo模型的对话
  • 支持批量查询api到期时间和剩余额度

安装步骤

  • 将代码部署到Cloudflare的worker平台(其他支持worker的平台也可)
/**
 * @auther Rehiy
 * @url https://github.com/open-tdp/openai-chat
 */

const GITHUB_URL = 'https://raw.githubusercontent.com/open-tdp/openai-chat/master';

async function github_proxy(request) {
    const url = new URL(request.url);

    let backend = GITHUB_URL + url.pathname;
    if (url.pathname.endsWith('/')) {
        backend += 'index.html';
    }

    const res = await fetch(backend, {
        method: request.method,
        headers: {
            'User-Agent': request.headers.get('User-Agent'),
        },
    });

    const headers = new Headers();
    headers.set('Content-Type', file_type(backend));
    headers.set('Cache-Control', 'public, max-age=86400');

    return new Response(res.body, {
        status: res.status,
        headers,
    });
}

function file_type(url) {
    const ext = url.split('?').shift().split('.').pop();
    const mines = {
        'json': 'application/json',
        'js': 'application/javascript',
        'css': 'text/css',
        'xml': 'text/xml',
        'html': 'text/html',
        'webm': 'video/webm',
        'mp3': 'audio/mpeg',
        'mp4': 'video/mp4',
        'webp': 'image/webp',
        'gif': 'image/gif',
        'png': 'image/png',
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'svg': 'image/svg+xml',
        'ico': 'image/x-icon',
    };
    return mines[ext] || 'text/plain';
}

// esmodule

export default {
    async fetch(request, env) {
        return github_proxy(request);
    }
}
文章作者: 若海; 原文链接: https://www.rehiy.com/post/501/; 转载需声明来自技术写真 - 若海

仅有一条评论

  1. 不明觉历呀。

添加新评论