pawanosman / googlebard Goto Github PK
View Code? Open in Web Editor NEWGoogleBard - A reverse engineered API for Google Bard chatbot for NodeJS
Home Page: https://bard.google.com
License: MIT License
GoogleBard - A reverse engineered API for Google Bard chatbot for NodeJS
Home Page: https://bard.google.com
License: MIT License
Hello!
I recently encountered an issue while using proxies, specifically with Axios. I'm fairly confident that I've set up my proxy correctly, but I'm unsure if the problem lies with Axios itself or if there's a misconfiguration with my proxy.
The issue arose when using the default settings:
const agent = new https.Agent({
rejectUnauthorized: false,
});
let axiosOptions = {
proxy: this.options.proxy,
httpsAgent: agent,
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0",
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate, br",
Connection: "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
TE: "trailers",
},
};
With these settings, I received a 502 error, which stated "The requested URL could not be retrieved". This issue seemed to occur when using a Squid proxy.
To rectify this problem, I implemented the following steps:
Here's an example of the changes I made:
import HttpsProxyAgent from "https-proxy-agent";
let axiosOptions = {
proxy: false,
httpsAgent: new HttpsProxyAgent(`http://user:password@ip:port`),
headers: {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/109.0",
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate, br",
Connection: "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
TE: "trailers",
},
};
I suspect the issue may be a bug with Axios, possibly related to its handling of proxying HTTP to HTTPS. Alternatively, it might be a configuration issue with the Squid proxy. I thought it would be worth raising this issue to bring it to attention.
Sometimes response is simple en or [SWML_HOME_TOWN] . What might be the reason @PawanOsman
Issue:
wait - compiling...
event - compiled client and server successfully in 914 ms (307 modules)
wait - compiling / (client and server)...
error - ./node_modules/dbcontext/dist/classes/dbcontext.js:1:0
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/dbcontext/dist/index.js
./node_modules/googlebard/dist/classes/app-dbcontext.js
./node_modules/googlebard/dist/classes/bard.js
./node_modules/googlebard/dist/index.js
./components/chat/messages.tsx
./pages/index.tsx
https://nextjs.org/docs/messages/module-not-found
Could not find files for / in .next/build-manifest.json
Could not find files for / in .next/build-manifest.json
Major Packages installed:
"fs": "0.0.1-security",
"googlebard": "^1.0.5",
"next": "^12.0.9",
"react": "17.0.2",
"react-dom": "17.0.2",
Hi if have this error:
Traceback (most recent call last):
File "v:\Abschluss_V4\main.py", line 75, in <module>
main()
File "v:\Abschluss_V4\main.py", line 71, in main
response = prompt_bard(prompt_text)
File "v:\Abschluss_V4\main.py", line 24, in prompt_bard
response = chatbot.ask(prompt)
File "C:\Users\Olive\AppData\Roaming\Python\Python310\site-packages\Bard.py", line 132, in ask
"content": json_chat_data[0][0],
TypeError: 'NoneType' object is not subscriptable
Here is my code/project:
from Bard import Chatbot
from playsound import playsound
import speech_recognition as sr
from os import system
import whisper
import warnings
import sys
token = 'YOUR TOKEN'
chatbot = Chatbot(token)
r = sr.Recognizer()
tiny_model = whisper.load_model('tiny')
base_model = whisper.load_model('base')
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using Fp32 instead")
if sys.platform != 'darwin':
import pyttsx3
engine = pyttsx3.init()
rate = engine.getProperty('rate')
engine.setProperty('rate', rate-50)
def prompt_bard(prompt):
response = chatbot.ask(prompt)
return response['content']
def speak(text):
if sys.platform == 'darwin':
ALLOWED_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?!-_$: ")
clean_text = ''.join(c for c in text if c in ALLOWED_CHARS)
system(f"sys '{clean_text}'")
else:
engine.say(text)
engine.runAndWait()
def main():
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
while True:
while True:
try:
print('\n Say "hey" to wake me up. \n"')
audio = r.listen(source)
with open("wake_detect.wav", "wb") as f:
f.write(audio.get_wav_data())
result = tiny_model.transcribe('wake_detect.wav')
text_input = result['text']
if 'hey' in text_input.lower().strip():
break
else:
print("No wake word found. Try again.")
except Exception as e:
print("Error transcibing audio: ", e)
continue
try:
playsound('wake_detected.mp3')
print("Wake word detected. Please speak your prompt to Bard \n")
audio = r.listen(source)
with open("prompt.wav", "wb") as f:
f.write(audio.get_wav_data())
result = base_model.transcribe('prompt.wav')
prompt_text = result['text']
print("Sending to Bard: ", prompt_text, '\n')
if len(prompt_text.strip()) == 0:
print("Empty prompt. Please speak again.")
speak("Empty prompt. Please speak again.")
continue
except Exception as e:
print("Error transcribing audio: ", e)
continue
response = prompt_bard(prompt_text)
speak(response)
if __name__ == '__main__':
main()
Here is my code (I'm using commonJS):
const { Bard } = await import('googlebard');
const bard = new Bard(process.env.BARD_TOKEN);
const res = await bard.ask('Hi!');
I install proxies as shown in the example, but they don't work. I used a proxy for bing and they work 100%. On replit, I insert only cookies and it works, I connect a proxy, and the proxy does not work on replit either. The error is definitely not in the proxy and not in the cookies, because they work separately. Cookies from usa
I figured out that __Secure-1PSIDTS
also must be included in the cookies.
./node_modules/.pnpm/[email protected]/node_modules/dbcontext/dist/classes/dbcontext.js:1:0
Module not found: Can't resolve 'fs'
https://nextjs.org/docs/messages/module-not-found
Import trace for requested module:
./node_modules/.pnpm/[email protected]/node_modules/dbcontext/dist/index.js
./node_modules/.pnpm/[email protected]/node_modules/googlebard/dist/classes/app-dbcontext.js
./node_modules/.pnpm/[email protected]/node_modules/googlebard/dist/classes/bard.js
./node_modules/.pnpm/[email protected]/node_modules/googlebard/dist/index.js
./src/agents/babyagi/bard.ts
./src/agents/babyagi/service.ts
./src/agents/babyagi/index.ts
./src/components/Agent/Agent.tsx
./src/pages/index.tsx
The fs
module doesn't exist in browser contexts. Maybe we could not import dbcontext
if inMemory
is true?
Hello, thank you for the help, because it's really helpful. I want to know how to get the cookie, directly with a code, if you an astuce, because, the problem, is that the cookie cannot work sometimes and for a long term project, it's not easy to always put it manually.
Thanks for the help
how to change language
/home/runner/bard/index.js:1
const Bard = require('googlebard')
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/runner/bard/node_modules/googlebard/dist/index.js from /home/runner/bard/index.js not supported.
Instead change the require of /home/runner/bard/node_modules/googlebard/dist/index.js in /home/runner/bard/index.js to a dynamic import() which is available in all CommonJS modules.
at Object. (/home/runner/bard/index.js:1:14) {
code: 'ERR_REQUIRE_ESM'
}
Hi;
I was using the AI to make a Voice Assistant but encounter an error Below you can find my py file:
Google Bard encountered an error: b')]}'\n\n38\n[["wrb.fr",null,null,null,null,[9]]]\n56\n[["di",58],["af.httprm",58,"-8469647117787525651",16]]\n25\n[["e",4,null,null,131]]\n'.
from Bard import Chatbot
from playsound import playsound
import speech_recognition as sr
from os import system
import whisper
import warnings
import sys
token = "YOUR TOKEN"
chatbot = Chatbot(token)
r = sr.Recognizer()
tiny_model = whisper.load_model('tiny')
base_model = whisper.load_model('base')
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")
if sys.platform != 'darwin':
import pyttsx3
engine = pyttsx3.init()
rate = engine.getProperty('rate')
engine.setProperty('rate', rate-50)
def prompt_bard(prompt):
response = chatbot.ask(prompt)
return response['content']
def speak(text):
if sys.platform == 'darwin':
ALLOWED_CHARS = set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?!-_$: ")
clean_text = ''.join(c for c in text if c in ALLOWED_CHARS)
system(f"say '{clean_text}'")
else:
engine.say(text)
engine.runAndWait()
def main():
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source)
while True:
while True:
try:
print('\nSay "google" to wake me up. \n')
audio = r.listen(source)
with open("wake_detect.wav", "wb") as f:
f.write(audio.get_wav_data())
result = tiny_model.transcribe('wake_detect.wav')
text_input = result['text']
if 'google' in text_input.lower().strip():
break
else:
print("No wake word found. Try again.")
except:
print("Error transcribe audio: ", e)
continue
try:
playsound('wake_detected.mp3')
print("Wake word detected. Please speak your prompt to Bard. \n")
audio = r.listen(source)
with open("prompt.wav", "wb") as f:
f.write(audio.get_wav_data())
result = base_model.transcribe('prompt.wav')
prompt_text = result['text']
print("Sending to Bard:", prompt_text, '\n')
if len(prompt_text.strip()) == 0:
print("Empty prompt. Please speak again.")
speak("Empty prompt. Please speak again.")
continue
except Exception as e:
print("Error transcribing audio: ", e)
continue
response = prompt_bard(prompt_text)
if sys.platform.startswith('win'):
print('Bards response: ', response)
else:
print('Bards response: ', response)
speak(response)
if name == 'main':
main()
The response is empty when the query includes a link to a webpage. For example try this query:
Can you summarize this article for me? https://blog.google/technology/ai/code-with-bard/
This happens because resData[3] contains an empty string. To get the actual response text the ask method needs to be modified to return resData[1]:
async ask(prompt, conversationId) {
let resData = await this.send(prompt, conversationId);
return resData[3].length > 0 ? resData[3] : resData[1];
}
E:\lab\node\line-chatgpt\node_modules\ts-node\dist\index.js:851
return old(m, filename);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module E:\lab\node\line-chatgpt\node_modules\googlebard\dist\index.js from E:\lab\node\line-chatgpt\src\index.ts not supported.
Instead change the require of index.js in E:\lab\node\line-chatgpt\src\index.ts to a dynamic import() which is available in all CommonJS modules.
at Object.require.extensions. [as .js] (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\index.js:851:20)
at Object. (E:\lab\node\line-chatgpt\src\index.ts:21:18)
at Module.m._compile (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\index.js:857:29)
at Object.require.extensions. [as .ts] (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\index.js:859:16)
at phase4 (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\bin.js:466:20)
at bootstrap (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\bin.js:54:12)
at main (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\bin.js:33:12)
at Object. (E:\lab\node\line-chatgpt\node_modules\ts-node\dist\bin.js:579:5) {
code: 'ERR_REQUIRE_ESM'
}
For How much time does the cookie Valid ?
Am i required to change the cookie every x hours or days ?
Can you call the chat and use it normally now? Now report this problem Error parsing response: make sure you are using the correct cookie, copy the value of "__Secure-1PSID" cookie and set it like this:
new Bard("__Secure-1PSID=<COOKIE_VALUE>")
Also using a US proxy is recommended.
If this error persists, please open an issue on github.
The cookie setting is correct, and the network environment is also set up. Before, you can successfully receive chat replies, but now you canβt
project/node_modules/ts-node/dist/index.js:851
return old(m, filename);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module
const bardUnofficalChat=async (req,res)=>{
let {message}=req.body
const {Bard} = await import("googlebard")
let cookies = __Secure-1PSID=${process.env.BARD_AUTH}
;
let bot = new Bard(cookies, {
inMemory: false, // optional: if true, it will not save conversations to disk
savePath: "./chatjson/conversations.json", // optional: path to save conversations
});
let conversationId = "conversation name"; // optional: to make it remember the conversation
// let response = await bot.ask(message); // conversationId is optional
// console.log(response);
// res.json({
// data:response
// })
// Simulating response streaming
await bot.askStream(
(res) => {
console.log(res);
},
message,
// conversationId,
);
}
I ran the above code and found that adding {
inMemory: false, // optional: if true, it will not save conversations to disk
savePath: "./chatjson/conversations.json", // optional: path to save conversations
} With this code, node will be restarted due to changes in the file, resulting in the inability to output chat messages. Then I configure { in nodemon.json
"ignore": [
"chatjson/*"
]
}
It doesn't work either, do you guys know how to solve it?
The value of __Secure-1PSIDTS (or __Secure-2PSIDTS, __Secure-3PSIDTS, etc, depending on the user number) must be included in the cookie. This is what the cookies variable should look like in order to make a successful request:
let cookies = `__Secure-1PSID=<COOKIE_VALUE>; __Secure-1PSIDTS=<COOKIE_VALUE>`;
When it is not included (as described in the current readme) the request fails with this error:
Error parsing response: make sure you are using the correct cookie, copy the value of "__Secure-1PSID" cookie and set it like this:
new Bard("__Secure-1PSID=<COOKIE_VALUE>")
Also using a US proxy is recommended.
If this error persists, please open an issue on github.
https://github.com/PawanOsman/GoogleBard
file:///C:/Users/user/Source/bard-test/node_modules/googlebard/dist/classes/bard.js:174
return resData[3];
^
TypeError: Cannot read properties of undefined (reading '3')
at Bard.ask (file:///C:/Users/user/Source/bard-test/node_modules/googlebard/dist/classes/bard.js:174:23)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async file:///C:/Users/user/Source/bard-test/index.js:8:16
How can we use this module with Langchainjs js.langchain.com/docs/api/llms_base/classes/LLM
Starting today, the bot's answers became dull and unintelligent, replying with the same prompt that was given or fragments of the prompt.
Example:
import { Bard } from "googlebard";
let cookies = `__Secure-1PSID=<YOUR_COOKIE>`;
let bot = new Bard(cookies, {
inMemory: false,
savePath: "./conversations.json",
});
let conversationId = "test_id";
let response = await bot.ask("My name is Mehul", conversationId);
console.log(response);
>> Mehul
The issue persists after the module is reinstalled and also after the conversation is reset. Updating the cookie ID didn't help either. It used to work perfectly, this issue started presenting itself just today.
axios is too big. I recommend replacing it with https://github.com/alovajs/alova or https://github.com/developit/redaxios
I can't import on my code that's running as CommonJS. Everything else can't just be converted. Any ideas?
I was trying to use this package (well done btw), and it kept not working, so I decided to look into the code, and found that SNlM0e does not seem to be there (in the html data) when being fetched? It could just be something on my side, please look into it, many thanks.
Hello, this is my case of trying to use contextual dialog:
const chatjson=require('../../chatjson/conversations.json')
const bardUnofficalChat=async (req,res)=>{
let {message,isfirst}=req.body
const {Bard} = await import("googlebard")
let cookies = `__Secure-1PSID=${process.env.BARD_AUTH}`;
let bot = new Bard(cookies, {
inMemory: false, // optional: if true, it will not save conversations to disk
savePath: "./chatjson/conversations.json", // optional: path to save conversations
// proxy: {
// // optional: proxy configuration
// host: process.env.PROXY_HOST,
// port: process.env.PROXY_PORT,
// auth: {
// username: process.env.PROXY_USERNAME,
// password: process.env.PROXY_PASSWORD,
// },
// protocol: "http",
// },
});
let conversationId = ''; // optional: to make it remember the conversation
if(isfirst){
conversationId=Date.now()
}else{
conversationId=chatjson.conversations.rows[chatjson.conversations.rows.length-1].id
}
let response = await bot.ask(message,conversationId); // conversationId is optional
console.log(response);
res.json({
data:response
})
// Simulating response streaming
// await bot.askStream(
// (res) => {
// console.log(res);
// },
// message,
// conversationId,
// );
}
module.exports={
bardUnofficalChat
}
But it is not possible to carry out contextual dialogue. Please tell me how to use the correct usage. The cases in the document are not very clear.
import express from 'express';
import * as dotenv from 'dotenv';
import cors from 'cors';
import { Bard } from "googlebard";
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
app.get('/', async (req, res) => {
res.status(200).send({
message: '- Last Update May 17, 2023',
})
});
app.post('/', async (req, res) => {
try {
const prompt = req.body.prompt;
let cookies = `__Secure-1PSID=<i insert my token here>`;
let bot = new Bard(cookies);
let response = await bot.ask(prompt);
console.log(response);
res.status(200).send({
bot: response
});
} catch (error) {
res.status(500).send(error || 'Something went wrong, please try again.');
}
})
app.listen(5500, () => console.log('Started on port 5500'))
Where i get the key? Inside this..
Sample json request:
{
"prompt": "Hello"
}
Using proxy doesn't make any sense if the token you got is whitelisted and also i am able to use bard even i am not in US without using VPN.
Sometimes it just comes back to this error
SWML_DESCRIPTION_FROM_YOUR_INTERNET_ADDRESS
But in bard there is text
Hello there! If you're looking to reverse engineer Google Bard, I've got some news for you. Due to a recent update, Google Bard's behavior has changed, making traditional reverse engineering methods less fruitful. The current version of Google Bard, when prompted, simply responds by echoing back your original input. Consequently, attempting to delve into the inner workings of Google Bard to uncover its underlying mechanisms may yield limited or unsatisfactory results. It's akin to peering into a puzzle box, only to find a reflection of your own query staring back at you. Therefore, the effectiveness of reverse engineering Google Bard has been curtailed with this update.
This is my bard url, I don't have account number 1,2,3
https://bard.google.com/u/0/chat
Sometimes googlebard response country code like (zh-hans,en)
let response = await bot.ask(sendMessage,message.author.id)
Hello, I'm not sure what happened, but after using this fine for a month or so all of a sudden, I keep getting the following error. Also as an attachment is a response for the request (cookie censored), using node 18.16.0 with googlebard 1.0.6
file:///root/nodejs/yetanotherbot/node_modules/googlebard/dist/classes/bard.js:175
return resData[0];
^
TypeError: Cannot read properties of undefined (reading '0')
at Bard.ask (file:///root/nodejs/yetanotherbot/node_modules/googlebard/dist/classes/bard.js:175:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async file:///root/nodejs/yetanotherbot/aiHelper.js:58:21
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.