分享一个Open WebUI转OpenAI格式API的Cloudflare Workers代码

直接给出Cloudflare Workers代码

const OPENWEBUI_BASE_URL = OPENWEBUI_BASE_URL;
const OPENWEBUI_API_KEY = OPENWEBUI_API_KEY;
const API_KEY = API_KEY;

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  if (request.method !== 'POST') {
    return new Response('Method Not Allowed', { status: 405 });
  }

  const apiKey = request.headers.get('Authorization');
  if (!apiKey || apiKey !== `Bearer ${API_KEY}`) {
    return new Response('Unauthorized', { status: 401 });
  }

  const contentType = request.headers.get('content-type');
  if (!contentType || !contentType.includes('application/json')) {
    return new Response('Content-Type must be application/json', { status: 400 });
  }

  try {
    const requestUrl = new URL(request.url);
    const path = requestUrl.pathname;

    let apiUrl;
    switch (path) {
      case '/v1/chat/completions':
        apiUrl = `${OPENWEBUI_BASE_URL}/api/chat/completions`;
        break;
      case '/v1/models':
        apiUrl = `${OPENWEBUI_BASE_URL}/api/models`;
        break;
      default:
        return new Response('Not Found', { status: 404 });
    }

    const requestBody = await request.json();
    const customResponse = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENWEBUI_API_KEY}`
      },
      body: JSON.stringify(requestBody)
    });

    if (!customResponse.ok) {
      throw new Error(`API request failed with status ${customResponse.status}`);
    }

    const responseData = await customResponse.json();
    return new Response(JSON.stringify(responseData), {
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

环境变量配置

在 Cloudflare Workers 控制面板中,添加以下环境变量:

  • 名称OPENWEBUI_BASE_URL
    替换成Open WebUI的网址(带https)

  • 名称OPENWEBUI_API_KEY
    替换成你在Open WebUI申请的API密钥

  • 名称API_KEY
    你设置的Workers接口保护密钥

54 个赞

#Cloudflare添加

牛啊 老哥 哈哈哈哈哈哈哈

2 个赞

感谢分享!!开干

1 个赞

厉害了٩(‘ω’)و

1 个赞

有點牛比
我去把他們都自動化變成渠道tieba_072

转 api 放自己 openwebui :rofl: :rofl: :rofl:

1 个赞

兄弟,你来套壳是吧!绝绝子:notes::loudspeaker:

1 个赞

速率马上限制起来,防止乱刷

这不是多套一层了吗?

这个可以啊,牛

感谢大佬分享

最后都是套中套,到底谁出了token

太强了,感谢

老為甚麼我請求不會成功啊
https://owu2api.joegodwanggod.workers.dev/v1/models

之后怎么获取api地址和key?