-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgemini.js
151 lines (128 loc) · 4.09 KB
/
gemini.js
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
const axios = require('axios');
const fs = require('fs').promises;
const { v4: uuidv4 } = require('uuid');
class Gemini {
constructor(cookiePath, timeout = 30000) {
this.cookiePath = cookiePath;
this.timeout = timeout;
this.sessionAuth1 = '';
this.sessionAuth2 = '';
this.SNlM0e = '';
this.conversationId = '';
this.responseId = '';
this.choiceId = '';
}
async initialize() {
await this.loadCookies();
this.SNlM0e = await this.getSnlm0e();
}
async loadCookies() {
try {
const cookieData = await fs.readFile(this.cookiePath, 'utf8');
const cookies = JSON.parse(cookieData);
this.sessionAuth1 = cookies.find(item => item.name === '__Secure-1PSID')?.value;
this.sessionAuth2 = cookies.find(item => item.name === '__Secure-1PSIDTS')?.value;
if (!this.sessionAuth1 || !this.sessionAuth2) {
throw new Error('Required cookies not found in the cookie file.');
}
} catch (error) {
throw new Error(`Failed to load cookies: ${error.message}`);
}
}
async getSnlm0e() {
try {
const response = await axios.get('https://gemini.google.com/app', {
timeout: 10000,
headers: this.getHeaders(),
});
const match = response.data.match(/"SNlM0e":"(.*?)"/);
if (!match) {
throw new Error('SNlM0e value not found in response.');
}
return match[1];
} catch (error) {
throw new Error(`Failed to retrieve SNlM0e: ${error.message}`);
}
}
getHeaders() {
return {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'Host': 'gemini.google.com',
'Origin': 'https://gemini.google.com',
'Referer': 'https://gemini.google.com/',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'X-Same-Domain': '1',
'Cookie': `__Secure-1PSID=${this.sessionAuth1}; __Secure-1PSIDTS=${this.sessionAuth2}`,
};
}
async ask(question, sysPrompt = '') {
try {
const params = {
bl: 'boq_assistant-bard-web-server_20230713.13_p0',
_reqid: '0',
rt: 'c',
};
const messageStruct = [
[question],
null,
[this.conversationId, this.responseId, this.choiceId],
];
const data = new URLSearchParams({
'f.req': JSON.stringify([null, JSON.stringify(messageStruct)]),
'at': this.SNlM0e,
});
const response = await axios.post(
'https://gemini.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate',
data.toString(),
{
params,
headers: this.getHeaders(),
timeout: this.timeout,
}
);
const lines = response.data.split('\n');
const chatData = JSON.parse(lines[3])[0][2];
if (!chatData) {
return { content: null, images: [] };
}
const jsonChatData = JSON.parse(chatData);
const images = [];
if (jsonChatData[4]?.[0]?.[4]) {
for (const imgData of jsonChatData[4][0][4]) {
if (imgData?.[0]?.[0]?.[0]) {
images.push(imgData[0][0][0]);
}
}
}
const results = {
content: jsonChatData[4]?.[0]?.[1]?.[0] || null,
conversationId: jsonChatData[1][0],
responseId: jsonChatData[1][1],
images,
};
this.conversationId = results.conversationId;
this.responseId = results.responseId;
this.choiceId = jsonChatData[4]?.[0]?.[0] || '';
return results;
} catch (error) {
console.error(`An error occurred: ${error.message}`);
return { content: null, images: [] };
}
}
}
module.exports = Gemini;
// Example usage:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
async function main() {
const gemini = new Gemini('cookie.json');
await gemini.initialize();
readline.question('>>> ', async (question) => {
const response = await gemini.ask(question);
console.log(response.content);
readline.close();
});
}
main().catch(console.error);