File size: 5,128 Bytes
30991e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
const axios = require('axios');

const TEMP_MAIL_API = 'https://api.internal.temp-mail.io/api/v3';
const CHATAI_API = 'https://chataibot.pro/api';

const headers = {
  'Content-Type': 'application/json',
  'Accept-Language': 'en'
};

const tempMailHeaders = {
  ...headers,
  'Application-Name': 'web',
  'Application-Version': '4.0.0',
  'X-CORS-Header': 'iaWg3pchvFx48fY'
};

const handler = async (req, res) => {
  try {
    const { text } = req.query;

    if (!text) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: text'
      });
    }

    const result = await gpt4(text, chatId = null);
    res.json({
      author: "Herza",
      success: true,
      data: {
        msg: result.response,
        chatID: result.chatId
      }
    });

  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
};

module.exports = {
  name: 'Haiku Claude AIv3',
  description: 'Generate responses using Haiku Anthropic Model v3',
  type: 'GET',
  routes: ['api/AI/haiku'],
  tags: ['ai', 'Anthropic', 'Claude'],
  main: ['AI'],
  parameters: ['text', 'chatId', 'key'],
  enabled: true,
  handler
};

async function createTempEmail() {
  const { data } = await axios.post(`${TEMP_MAIL_API}/email/new`, {
    min_name_length: 10,
    max_name_length: 10
  }, { headers: tempMailHeaders });
  return data;
}

async function registerAccount(email) {
  const { data } = await axios.post(`${CHATAI_API}/register`, {
    email,
    password: 'Mxlineeecero5632@_++((+))9098+-+-!;::::#$',
    isAdvertisingAccepted: false,
    mainSiteUrl: 'https://chataibot.pro/api',
    utmSource: '',
    utmCampaign: '',
    connectBusiness: ''
  }, { headers });
  return data;
}

async function getMessages(email) {
  const { data } = await axios.get(`${TEMP_MAIL_API}/email/${email}/messages`, {
    headers: tempMailHeaders
  });
  return data;
}

async function waitForVerificationCode(email, maxAttempts = 10) {
  for (let i = 0; i < maxAttempts; i++) {
    await new Promise(r => setTimeout(r, 3000));
    const msgs = await getMessages(email);
    const chatAiMsg = msgs.find(m => m.from.includes('chataibot.pro'));
    if (chatAiMsg) {
      const match = chatAiMsg.body_text.match(/Your code: (\d+)/);
      if (match) return match[1];
    }
  }
  throw new Error('Verification code not received');
}

async function verifyAccount(email, token) {
  const { data, headers: responseHeaders } = await axios.post(`${CHATAI_API}/register/verify`, {
    email,
    token,
    connectBusiness: ''
  }, { headers });
  
  const cookies = responseHeaders['set-cookie'] || [];
  return { jwtToken: data.jwtToken, cookies };
}

async function createChat(jwtToken, cookies, title = 'New Chat') {
  const cookieString = cookies.map(c => c.split(';')[0]).join('; ');
  
  await axios.post(`${CHATAI_API}/message/change-context-model`, {
    chatId: 0,
    title,
    isInternational: true
  }, {
    headers: {
      ...headers,
      'Authorization': `Bearer ${jwtToken}`,
      'Cookie': cookieString
    }
  });

  const { data } = await axios.post(`${CHATAI_API}/message/context`, {
    title,
    chatModel: 'claude-3-haiku'
  }, {
    headers: {
      ...headers,
      'Authorization': `Bearer ${jwtToken}`,
      'Cookie': cookieString
    }
  });
  return data.id;
}

async function sendMessage(jwtToken, cookies, text, chatId) {
  const cookieString = cookies.map(c => c.split(';')[0]).join('; ');
  
  const { data } = await axios.post(`${CHATAI_API}/message/streaming`, {
    text,
    chatId,
    withPotentialQuestions: true,
    linksToParse: []
  }, {
    headers: {
      ...headers,
      'Authorization': `Bearer ${jwtToken}`,
      'Cookie': cookieString
    },
    responseType: 'text'
  });

  const lines = data.split('}{').map((line, i, arr) => {
    if (i === 0) return line + '}';
    if (i === arr.length - 1) return '{' + line;
    return '{' + line + '}';
  });

  let result = '';
  for (const line of lines) {
    try {
      const json = JSON.parse(line);
      if (json.type === 'chunk') {
        result += json.data;
      } else if (json.type === 'finalResult') {
        return json.data.mainText;
      }
    } catch (e) {}
  }

  return result;
}

let cachedToken = null;
let cachedCookies = null;
let cachedChatId = null;

async function gpt4(query, chatId = null) {
  try {
    if (!cachedToken) {
      const { email } = await createTempEmail();
      await registerAccount(email);
      const code = await waitForVerificationCode(email);
      const verifyResult = await verifyAccount(email, code);
      cachedToken = verifyResult.jwtToken;
      cachedCookies = verifyResult.cookies;
    }

    if (!chatId && !cachedChatId) {
      cachedChatId = await createChat(cachedToken, cachedCookies, query);
    }

    const targetChatId = chatId || cachedChatId;
    const response = await sendMessage(cachedToken, cachedCookies, query, targetChatId);

    return { response, chatId: targetChatId };
  } catch (err) {
    cachedToken = null;
    cachedCookies = null;
    cachedChatId = null;
    throw err;
  }
}