File size: 2,375 Bytes
3444669
6a37520
c8af9b9
6a37520
c8af9b9
 
3444669
 
 
 
 
6a37520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { NextRequest, NextResponse } from "next/server";
import { BingChat, ChatMessage } from "../../bing-chat/index";
import { auth } from "../auth";

export async function POST(req: NextRequest) {
  const authResult = auth(req);
    if (authResult.error) {
      return NextResponse.json(authResult, {
        status: 401,
      });
    }
  try {
    let cookies = process.env.COOKIES;
    const api = new BingChat({
      cookie: cookies,
    });
    let chat: ChatMessage = {
      id: "",
      text: "",
      author: "bot",
      conversationId: "",
      clientId: "",
      conversationSignature: "",
    };
    const res: any = await bingAiMessageSendWrapper(
      api,
      await req.json(),
      chat,
    );
    // const res = await api.sendMessage(await req.json(), {
    //   // print the partial response as the AI is "typing"
    //   onProgress: (partialResponse) => {
    //     console.log(partialResponse.text);
    //   },
    //   variant: "Precise",
    // });
    // console.log(res['text'])
    return new Response(res["text"]);
  } catch (e) {
    console.error("[NewBing] ", e);
    return new Response(JSON.stringify(e));
  }
}

/**
 * @param { import("bing-chat").BingChat } client
 * @param { string } message
 * @param { import("bing-chat").ChatMessage } [session]
 * @returns { Promise<import("bing-chat").ChatMessage> }
 */
function bingAiMessageSendWrapper(
  client: BingChat,
  message: string,
  session: ChatMessage,
) {
  const TIMEOUT_THRESHOLD = 120 * 1000;
  return new Promise((resolve, reject) => {
    let response = {
      text: "",
    };
    let responseText = "";
    let temp = {
      time: new Date().valueOf(),
      response: response,
    };
    const verifyIfResponseChangedInterval = setInterval(() => {
      if (new Date().valueOf() - temp.time > TIMEOUT_THRESHOLD) {
        clearInterval(verifyIfResponseChangedInterval);
        temp.response.text = responseText;
        resolve(temp.response);
      }
    }, 500);
    client
      .sendMessage(message, {
        ...session,
        onProgress: (partialResponse) => {
          temp.response = partialResponse;
          responseText += partialResponse.text;
          temp.time = new Date().valueOf();
        },
      })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
}