reka.ai works代码

抓包用authorization作为key传入
模型:reka-core,reka-flash,reka-edge

 

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

const encoder = new TextEncoder();

async function handleRequest(request) {
  if (request.method !== "POST") {
    return new Response("Not a POST request", { status: 405 })
  }

  const authorizationHeader = request.headers.get("Authorization");
  if (!authorizationHeader) {
    return new Response("Missing Authorization header", { status: 401 });
  }

  const requestBody = await request.json();
  const messages = requestBody.messages;
  const isStream = requestBody.stream;
  const model = requestBody.model;

  // 将OpenAI格式的messages转换为Reka AI的conversation_history格式
  let conversation_history = messages.map(msg => {
    if (msg.role === "user" || msg.role === "system") {
      return { "type": "human", "text": msg.content };  
    } else if (msg.role === "assistant") {
      return { "type": "model", "text": msg.content };
    }
  });

  // 确保对话历史以"human"开始和结束
  if (conversation_history[0].type !== "human") {
    conversation_history.unshift({ "type": "human", "text": "" });
  }
  if (conversation_history[conversation_history.length - 1].type !== "human") {
    conversation_history.push({ "type": "human", "text": "" });
  }

  // 确保"human"和"model"成对出现
  for (let i = 0; i < conversation_history.length - 1; i++) {
    if (conversation_history[i].type === conversation_history[i + 1].type) {
      if (conversation_history[i].type === "human") {
        conversation_history.splice(i + 1, 0, { "type": "model", "text": "" });
      } else {
        conversation_history.splice(i + 1, 0, { "type": "human", "text": "" });
      }
      i++;
    }
  }

  const newRequestBody = {
    conversation_history: conversation_history,
    stream: isStream,
    use_search_engine: false,
    use_code_interpreter: false,
    model_name: "reka-core",
    random_seed: Math.floor(Math.random() * 1000000000000)
  };

  const response = await fetch("https://chat.reka.ai/api/chat", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
      "Accept-Encoding": "gzip, deflate, br, zstd",
      "authorization": authorizationHeader
    },
    body: JSON.stringify(newRequestBody)
  });

  if (isStream) {
    let decoder = new TextDecoder();
    let reader = response.body.getReader();
    let contentBuffer = "";
    let fullContent = ""; // 存储完整的assistant回复内容
    let prevContent = ""; // 存储上一次迭代的内容
    let lastFourTexts = []; // 存储最近的三条text内容
  
    return new Response(new ReadableStream({
      async start(controller) {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
  
          let chunk = decoder.decode(value);
          contentBuffer += chunk;
  
          // 逐行处理数据
          while (contentBuffer.includes("\n")) {
            const newlineIndex = contentBuffer.indexOf("\n");
            const line = contentBuffer.slice(0, newlineIndex);
            contentBuffer = contentBuffer.slice(newlineIndex + 1);
  
            if (line.startsWith("data:")) {
              try {
                const data = JSON.parse(line.slice(5));
                if (data.type === "model") {
                  if (data.text.trim() !== "") { // 判断text是否为非空
                    lastFourTexts.push(data.text); // 将最新的text添加到lastFourTexts
                    if (lastFourTexts.length > 4) {
                      lastFourTexts.shift(); // 如果超过四条,删除最旧的一条
                    }
                    if (lastFourTexts.length === 4) {
                      // 判断是否出现截断情况
                      if (lastFourTexts[3].length < lastFourTexts[2].length || 
                          lastFourTexts[3].endsWith("<sep") || 
                          lastFourTexts[3].endsWith("<")) {
                        // 忽略最旧的两条,并中断响应
                        controller.close();
                        break;
                      }
                    }
                    fullContent = data.text; // 更新完整回复为最新的内容
                    const newContent = fullContent.slice(prevContent.length); // 获取新增的内容
                    prevContent = fullContent; // 更新上一次迭代的内容
                    const formattedData = {
                      id: "chatcmpl-" + Math.random().toString(36).slice(2),
                      object: "chat.completion.chunk",
                      created: Math.floor(Date.now() / 1000),
                      model: model,
                      choices: [{
                        index: 0,
                        delta: {
                          content: newContent
                        },
                        finish_reason: null
                      }]
                    };
                    controller.enqueue(encoder.encode(`data: ${JSON.stringify(formattedData)}\n\n`));
                  }
                }
              } catch (error) {
                console.error("Error parsing JSON:", error, "Raw data:", line);
              }
            }
          }
        }
  
        // 发送[DONE]信号
        const doneData = {
          id: "chatcmpl-" + Math.random().toString(36).slice(2),
          object: "chat.completion.chunk",
          created: Math.floor(Date.now() / 1000),
          model: model,
          choices: [{
            index: 0,
            delta: {},
            finish_reason: "stop"
          }]
        };
        controller.enqueue(encoder.encode(`data: ${JSON.stringify(doneData)}\n\n`));
        controller.enqueue(encoder.encode(`data: [DONE]\n\n`));
  
        controller.close();
      }
    }), {
      headers: { "Content-Type": "text/event-stream" }
    });
  }   else {
    const responseText = await response.text();
    const lines = responseText.split("\n");
    let contentBuffer = "";
    for (const line of lines) {
      if (line.startsWith("data:")) {
        const data = JSON.parse(line.slice(5));
        if (data.type === "model") {
          contentBuffer = data.text; // 更新为最新的完整回复
        }
      }  
    }
    const formattedData = {
      id: "chatcmpl-" + Math.random().toString(36).slice(2),  
      object: "chat.completion",
      created: Math.floor(Date.now() / 1000),
      model: model,
      choices: [{
        index: 0,
        message: {
          role: "assistant",
          content: contentBuffer
        },
        finish_reason: "stop"
      }],
      usage: {
        prompt_tokens: JSON.stringify(conversation_history).length,
        completion_tokens: contentBuffer.length,
        total_tokens: JSON.stringify(conversation_history).length + contentBuffer.length  
      }
    };
    return new Response(JSON.stringify(formattedData), {
      headers: { "Content-Type": "application/json" }  
    });
  }
}

 

posted on 2024-05-12 15:20  WEB前端1989  阅读(10)  评论(0编辑  收藏  举报
云加速