cf 部署 workers ai

cf workers ai 提供了60多个开源模型 以下是通过worker部署
没有账号的首先注册账号
有账号直接登录




删除原来所有的代码
粘贴以下代码

const API_KEY='linuxdo';
export default {
  async fetch(request, env) {
    const tasks = [];
    let url = new URL(request.url);
    const path = url.pathname;

    const authHeader = request.headers.get("authorization") || request.headers.get("x-api-key");
    const apiKey = authHeader?.startsWith("Bearer ")  ? authHeader.slice(7)  : null;

    if (API_KEY && apiKey !== API_KEY) {

      return new Response(JSON.stringify({
        error: {
            message: "Invalid API key. Use 'Authorization: Bearer your-api-key' header",
            type: "invalid_request_error",
            param: null,
            code: "invalid_api_key"
        }
      }), {
          status: 401,
          headers: {
              "Content-Type": "application/json",
          }
      });
    }
    // prompt - simple completion style input
    // let simple = {
    //   prompt: 'Tell me a joke about Cloudflare'
    // };
    // let response = await env.AI.run('@cf/meta/llama-3-8b-instruct', simple);
    // tasks.push({ inputs: simple, response });

    // messages - chat style input
    if (path === "/v1/chat/completions") {
      const requestBody = await request.json();
      // console.log(111,requestBody)
      // let chat = {
      //   messages: [
      //     { role: 'system', content: 'You are a helpful assistant.' },
      //     { role: 'user', content: '你是谁' }
      //   ]
      // };
      let chat=requestBody
      let response = await env.AI.run('@cf/meta/llama-3.3-70b-instruct-fp8-fast', chat);
      tasks.push({
        id: "01945b22aa36e40ca329ee13dce52199",
    object: "chat.completion",
        model:"llama-3.3-70b-instruct-fp8-fast",
        created:Date.now(),
         "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": response.response
            },
            "finish_reason": "stop"
        }
    ]});
  
      return Response.json(tasks);
    }
    
  }
};

点击右上角部署
为了能直接 访问点击下图位置返回


再点击

添加自己的域名

然后访问如下

7 Likes

我记得 免费额度非常少吧

感谢分享。

写的每日10k 自己用应该够用了吧

10k是啥概念。。。cline一次提问 输入97k 输出2k
随便问点啥,带点思考prompt 估计也得输出个2k多
cf在ai上,还是保守了 不善了

我也不知道啥概念 等大佬来回答 不知道一次消耗多少 等我观察观察

感谢大佬

感谢水王 :grinning: