Giter Club home page Giter Club logo

bard-ai's Introduction

EvanZhouDev Banner

๐Ÿ‘‹ Hi, I'm Evan Zhou.

A designer and developer. I love new technologies, and am constantly looking for something interesting to play around with. If you've got something, let me know!

Check out my newest project, Google Bard for Raycast. Download it today!

โœจ Skills

What can I do?

General

My Skills

  • Web devlopment
    • React/JSX
    • Next.js Framework
    • Redux
  • Web Scraping
    • Headless browser control with Puppeteer
    • Getting general information with Axios
  • UI/Graphic Design
    • CSS/HTML

Fluent Languages

My Skills

  • Javascript/JSX
  • Python
  • English

JavaScript Specific Toolset

  • NodeJS
  • NPM
  • HTML5 Canvas

๐Ÿ‘พ Software

What's on my computer?

My Skills

Other Productivity Tools:

๐Ÿ’ป Hardware

What do I use?

  • Computer: M1 Macbook Air
  • Keyboard: Keychron K2 w/ Gateron Brown switches
  • Mouse: Logi MX 2 Anywhere
  • Stand: Rain Design mStand

๐Ÿ“ˆ Stats

How much do I do what I do?

bard-ai's People

Contributors

aldhanekaa avatar evanzhoudev avatar rfs-adreno avatar thatxliner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bard-ai's Issues

Unable to use package

const { default: bard } = require('bard-ai')
                          ^

Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/anshtyagi/Documents/BACKUP/Cosmicbot/node_modules/bard-ai/index.js from /Users/anshtyagi/Documents/BACKUP/Cosmicbot/test.js not supported.
Instead change the require of index.js in /Users/anshtyagi/Documents/BACKUP/Cosmicbot/test.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (/Users/anshtyagi/Documents/BACKUP/Cosmicbot/test.js:1:27) {
  code: 'ERR_REQUIRE_ESM'
}

Error !!

/bard-ia/node_modules/bard-ai/index.js:29
else throw new Error("Could not get Google Bard.");
^

โœจ [FEATURE]: Would be cool to have this extension with this model "CodeLlama-34b-Instruct-hf"

Prerequisites

  • I have searched the issues and believe that it has not already been requested (and possibly rejected)
  • I am using the latest version of bard-ai

Feature description

I want this Raycast extension but with this model instead of bard "https://huggingface.co/codellama/CodeLlama-34b-Instruct-hf". I couldn't figure out how to do it myself i tried but I'm new to coding. Willing to try again if anyone can give me a little direction on how this could be implemented.

bard-ai with langchainjs

I am trying to use bard-ai with langchainjs https://js.langchain.com/docs/
Here is the code of my custom langchain model with bard-ai

import { LLM } from "langchain/llms/base"
import Bard from "bard-ai";

class BardAI extends LLM {

  constructor(config) {
    super(config);
    this.model = Bard
    this.controller = new AbortController();
  }

  async init(token) {
    await Bard.init(token)
  }

  async _call(prompt, options = { signal: controller.signal }, runManager) {
    return this.caller.call(this.model.askAI.bind(this.model), prompt)
  }

  _llmType() {
    return 'bard.chat'
  }

  cancel() {
    this.controller.abort();
  }
}

The model is working fine with lanchainjs except with initializeAgentExecutorWithOptions. Following code is not working.

import { Tool } from "langchain/tools";
import { initializeAgentExecutorWithOptions } from "langchain/agents";

class Greet extends Tool {
  _call(arg) {
    // Implement your tool logic here
    console.log('Running Greet tool.....')
    return "Welcme, " + arg + "!";
  }
  name = "greet";
  description = "A custom tool that greets the user.";
}

async function main() {
  let model = new BardAI({
    cache: false, maxConcurrency: 4, streaming: false,
  })
  await model.init(<cookie>)

  const tools = [new Greet()];

  const executor = await initializeAgentExecutorWithOptions(tools, model, {
    agentType: "zero-shot-react-description",
    verbose: true,
  });

  console.log(await executor.call({ input: 'hi, I am Zafar' }));
}

main();

Here is the output

[llm/end] [1:chain:agent_executor > 2:chain:llm_chain > 3:llm:bard.chat] [4.69s] Exiting LLM run with output: {
  "generations": [
    [
      {
        "text": "Sure, I can help you with that.\n\n**Question:** hi, I am Zafar\n\n**Thought:** I need to greet Zafar.\n\n**Action:** greet\n\n**Action Input:** Zafar\n\n**Observation:** Zafar is greeted.\n\n**Thought:** I now know the final answer.\n\n**Final Answer:** Hello, Zafar! How can I help you today?"
      }
    ]
  ]
}
[chain/end] [1:chain:agent_executor > 2:chain:llm_chain] [4.70s] Exiting Chain run with output: {
  "text": "Sure, I can help you with that.\n\n**Question:** hi, I am Zafar\n\n**Thought:** I need to greet Zafar.\n\n**Action:** greet\n\n**Action Input:** Zafar\n\n**Observation:** Zafar is greeted.\n\n**Thought:** I now know the final answer.\n\n**Final Answer:** Hello, Zafar! How can I help you today?"
}
[chain/end] [1:chain:agent_executor] [4.70s] Exiting Chain run with output: {
  "output": "** Hello, Zafar! How can I help you today?"
}
{ output: '** Hello, Zafar! How can I help you today?' }

I think the reason is that the bard-ai is returning response as markdown where as langchainjs is expecting text. Langchainjs integration will make bard-ai more useful If we can fix this issue.

๐Ÿ› [BUG]: Upon using Bard-ai for a few minutes or so, it will invalidate the cookie or return NULL

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

As said in the title, when you are using it for more than 5 minutes, it will start returning null responses or have a invalidated cookie.
image
and I use a new cookie every time, it would work, but after 5 minutes, it gets invalidated.
Im not sure if this is a issue with the library itself, or bard.

Reproduction Steps

  1. Getting a new cookie
  2. Using bard for 5 minutes or so
  3. It gets invalidated and returns null

Other information

No response

Occurance Rate

I can reproduce this bug 100% of the time.

Error when using the bard-ai in Discord.js (Typescript)

I attempted to migrate to this library, to evaluate its performance compared to the 'googlebard' library. However, I encountered an error while trying to use it. I also need clarification on whether this module has bypassed the recent update of Google Bard AI. Please note that the code provided is written in TypeScript.

Code:

if (messageContent && typeof messageContent === "string" && !message.author.bot) {
    // New Code using EvanZhouDev/bard-ai/
    let COOKIE_KEY = process.env.BARD_COOKIES || "";
    await Bard.init(COOKIE_KEY);
    let response = await askAI(messageContent);
    await message.reply(response.substring(0, 2000));

    // My previous code with googlebard
    // let importDynamic = new Function('modulePath', 'return import(modulePath)')
    // const { Bard } = await importDynamic("googlebard")
    // let bot =new Bard(cookies, {
    //     inMemory: false, 
    //     savePath: "./conversations.json", 
    //     proxy: {
    //         host: process.env.PROXY_HOST,
    //         port: process.env.PROXY_PORT,
    //         auth: {
    //             username: process.env.PROXY_USERNAME,
    //             password: process.env.PROXY_PASSWORD,
    //         },
    //         protocol: "https",
    //     },
    // });
    // let response = await bot.ask(messageContent, user_id);
} else {
    await message.reply("I can only process text messages.");
}

Error Message: 'askAI' only refers to a type, but is being used as a value here.ts(2693)

Steps to Reproduce:

  1. Ensure the required environment variables are properly set.
  2. Execute the provided code in a TypeScript project.
  3. Observe the error message 'askAI' only refers to a type, but is being used as a value here.ts(2693).

Expected Behavior:

  • The code should successfully utilize the 'EvanZhouDev/bard-ai' library to interact with the AI model and provide a response to the user message.

Additional Information:

  • This code snippet attempts to migrate from the googlebard library to bard-ai for enhanced performance evaluation.
  • The error message suggests that the identifier 'askAI' is being treated as a type rather than a value, causing the compilation error.
  • Please provide guidance on resolving this error and clarify if bard-ai has bypassed the recent update of Google Bard AI.

Please let me know if you need any further information. Thank you!

๐Ÿ› [BUG]: Error: Could not use your Cookie. Make sure that you copied correctly the Cookie with name __Secure-1PSID exactly. If you are sure your cookie is correct, you may also have reached your rate limit.

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

image
even though I use the same key, but using the bard-ai module gets this error, but if using the googlebard module, it works.

Reproduction Steps

let bot = new Bard(bardKey);

console.log(await bot.ask("Hello world!"));
console.log(await bot.ask("What is 1+1?"));
console.log(await bot.ask("What about 2+2?"));
console.log(await bot.ask("Goodbye."));

Other information

No response

Occurance Rate

I can reproduce this bug 100% of the time.

โœจ [FEATURE]: Proxy and Reverse Proxy

Prerequisites

  • I have searched the issues and believe that it has not already been requested (and possibly rejected)
  • I am using the latest version of bard-ai

Feature description

I hope to add proxy and reverse proxy configurations to allow access to Bard through proxy and add host modifications to Bard, in order to facilitate the use of Bard in areas where Bard is not available.

raycast extension

Hi - thanks i have been looking for this to work with raycast extension. It works but rather than sending text from selection text on browser, can you please make it such that we can type in raycast search box and it then sends to google bard to get a respondse back.

Ideally like the ChatGPT extension on raycast https://www.raycast.com/abielzulio/chatgpt. which in my mind is perfect except I would like to use Google bard for it. It has things like storing history etc.

๐Ÿ› [BUG]: Working with Windows, Crashing on Linux

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

So i coded a Discord Bot in Discord.JS in CJS and imported it correctly and everything works when using it in Windows, but when i upload it to a Linux Server(Running Ubuntu 20) it crashes when using Bard.Chat().ask() trying to ask something...

Reproduction Steps

Using:

const Bard = await import("bard-ai").catch(e => {
   throw "Missing Module: The Package 'bard-ai' was not found, please install it manually using 'npm i bard-ai'"
});
await Bard.init(config.aicookie);
let conv = new Bard.Chat();
await conv.ask("A MSG");

After i start the Bot it Gives this Error:

node:events:492
      throw er; // Unhandled 'error' event
      ^

Error: Google Bard encountered an error )]}'

38
[["wrb.fr",null,null,null,null,[9]]]
55
[["di",81],["af.httprm",80,"-1146363392943947525",2]]
25
[["e",4,null,null,130]]
.
    at queryBard (file:///Bot/node_modules/bard-ai/index.js:88:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Chat.ask (file:///Bot/node_modules/bard-ai/index.js:147:23)
    at async Object.execute (/Bot/events/ready.js:87:9) // This Being the Lines i sent Above: await conv.ask()
Emitted 'error' event on Client instance at:
    at emitUnhandledRejectionOrErr (node:events:395:10)
    at process.processTicksAndRejections (node:internal/process/task_queues:84:21)

Node.js v18.17.0

Other information

No response

Occurance Rate

I can reproduce this bug 100% of the time.

Custom Request Callback to Google API

When I develop my application using this library in Electron Application environment (Obsidian Application), it denies request (because it is a request from client, not a server) as this issue experience #2 .

Well I've managed to solve it, by requesting to Google Bard API using Obsidian Plugin requestUrl and therefore I rewrite all of this library codebase to my project (really inefficient) .

I think, it is important to add custom request callback, if a user faced the same issue as me, and they can be Electron Developers, or JavaScript Mobile Application Developers.


What do you guys think?

๐Ÿ› [BUG]: Could not fetch Google Bard. You may be disconnected from internet: TypeError: fetch failed

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

I'm not disconnected from the internet. Is the package owner still maintaining the package? It still has bard.google.com not gemini.google.com

Reproduction Steps

  1. Set Up Bard-AI
  2. Run It
  3. Bug

Other information

none

Occurance Rate

I can reproduce this bug 100% of the time.

๐Ÿ› [BUG]: The API is identified as a robot after some requests

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

I am making an application based in bard AI and after some requests it gave me this error :
Error creating channel: Error: Could not get Google Bard.
from the init function as the website identifies the api as a robot and when I try to open the website from the browser it gives me a captcha.

Reproduction Steps

const cookies = process.env.BARD_COOKIE;
await Bard.init(cookies);
const conversation = new Bard.Chat();
const response = await conversation.ask(question);
const userData = await conversation.export();

Other information

No response

Occurance Rate

I can reproduce this bug 50% of the time.

ISSUE FROM NODE.JS

Sorry, but i am just starting to code in Javascript. I get this error while using the command '''node script.js''' and i get this error:

import Bard, { askAI } from "bard-ai";
^^^^^^

SyntaxError: Cannot use import statement outside a module
โ†[90m    at Module._compile (internal/modules/cjs/loader.js:892:18)โ†[39m
โ†[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)โ†[39m
โ†[90m    at Module.load (internal/modules/cjs/loader.js:812:32)โ†[39m
โ†[90m    at Function.Module._load (internal/modules/cjs/loader.js:724:14)โ†[39m
โ†[90m    at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)โ†[39m
โ†[90m    at internal/main/run_main_module.js:17:11โ†[3

It would be great if you help me

๐Ÿ› [BUG]: TypeError: Cannot read properties of null (reading '4')

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

sometimes i get this error while talking to bard, after some digging, turns out that the variable chatData is null sometimes due to a problem in the parsing from json. here is the full error:

TypeError: Cannot read properties of null (reading '4') at #query (file:///C:/Users/mma91/OneDrive/%D7%A9%D7%95%D7%9C%D7%97%D7%9F%20%D7%94%D7%A2%D7%91%D7%95%D7%93%D7%94/milki/node_modules/bard-ai/index.js:240:32) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async Chat.ask (file:///C:/Users/mma91/OneDrive/%D7%A9%D7%95%D7%9C%D7%97%D7%9F%20%D7%94%D7%A2%D7%91%D7%95%D7%93%D7%94/milki/node_modules/bard-ai/index.js:353:32) at async bardAI (file:///C:/Users/mma91/OneDrive/%D7%A9%D7%95%D7%9C%D7%97%D7%9F%20%D7%94%D7%A2%D7%91%D7%95%D7%93%D7%94/milki/index.js:53:22) at async file:///C:/Users/mma91/OneDrive/%D7%A9%D7%95%D7%9C%D7%97%D7%9F%20%D7%94%D7%A2%D7%91%D7%95%D7%93%D7%94/milki/index.js:115:32

Reproduction Steps

talk to bard for a while, i did notice it tends happen more in the evening

Other information

No response

Occurance Rate

I can reproduce this bug 60% of the time.

๐Ÿ› [BUG]: Cannot read properties of null (reading '4')

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

when using the id it works at first then as the second requesting using the same id, it says
Cannot read properties of null (reading '4')

Reproduction Steps

Cannot read properties of null (reading '4')

Other information

No response

Occurance Rate

I can reproduce this bug 100% of the time..

CORS error

Hi There!

I am using bard-ai in React project so that I can generate content for my website. But I am getting a CORS error along with other issues upon running the website. I am running my website on the Chrome browser.

Screenshot 2023-05-27 at 12 53 11 PM

โœจ [FEATURE]: Integration With Gemini

Prerequisites

  • I have searched the issues and believe that it has not already been requested (and possibly rejected)
  • I am using the latest version of bard-ai

Feature description

As people may be aware now, Gemini has been released! I came back to this repo and I see that it isn't being actively maintained, and I thought I'd voice my feelings about it... This project is too good to let go! Hopefully this request will spark a fire and get the ball rolling again ๐Ÿ™‚ https://deepmind.google/technologies/gemini

๐Ÿช Multi-Cookie Use Alternative Solution

Alternative Solution to Multi-Cookie Use (#12)

This solution causes a minor breaking change, documented at the end.

Bard.init() now returns an object. This object contains its own askAI and Chat functions, all linked to the SNlM0e generated from the initialization.
In fact, Bard.init() can still set the global SNlM0e, allowing global askAI() and Chat to still work normally.

For example, it could look something like this:

let myBard1 = Bard.init(COOKIE_KEY_1)
let myBard2 = Bard.init(COOKIE_KEY_2)

myBard1.askAI("hi!") // uses COOKIE_KEY_1
let myBardChat1 = new myBard1.Chat() // uses COOKIE_KEY_1

myBard2.askAI("hi!") // uses COOKIE_KEY_2
let myBardChat2 = new myBard2.Chat() // uses COOKIE_KEY_2

The one concern is that Bard.init() used to return SNlM0e as a string, but now rather returns what is similar to an entire Bard instance...

๐Ÿ› [BUG]: Module not found: Error: Can't resolve 'fs'

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

This happens when I try to build my chrome extension that uses this package.

Module not found: Error: Can't resolve 'fs' in '/Users/sujit/Documents/My Projects/chrome-ext-litcode-solver/node_modules/bard-ai'

Reproduction Steps

  1. Create a sample application meant for the front-end (For example a website/extension).
  2. Add some bard sample code that will be executed on the front-end (This probably won't work for a website due to CORS policy, but will work for chrome extensions).
  3. fs cannot be imported because it is a server-side module, so it'll throw some kind of error.

Other information

No response

Occurance Rate

I can reproduce this bug 100% of the time.

Unsupported endgine

Hi, I am getting an error message on NPM Install
EBADENGINE Unsupported engine {
npm WARN EBADENGINE required: { node: '> 8.15.0', npm: '= 3.9.6' },
npm WARN EBADENGINE current: { node: 'v14.20.0', npm: '9.5.0' }
npm WARN EBADENGINE }
Thanks
Frank

๐Ÿ› [BUG]: context is sometimes reset even the conversation id is the same

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

IMG_20231019_140359_785
The conversation is already the same but it didn't save the context, bug?

Reproduction Steps

  1. Saved to json db
  2. Same conversation id
  3. Context is lost

Other information

No response

Occurance Rate

I can reproduce this bug 100% of the time.

Could not get Google Bard.

Hi, it was working fine for some time but today, I keep getting Could not get Google Bard. errors and can not make calls.

Checked the cookie and it is valid. Any ideas ?

[Bug]: cors issue

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • I have made sure this bug reproduces on the latest version
  • I agree to follow the Code of Conduct

Bug description

facing cors issue, while i run basic code

Reproduction steps

  1. cess to fetch at 'https://bard.google.com/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Other information

No response

Reproduces how often

I can reproduce this bug 100% of the time

โœจ [FEATURE]: get tts in the result

Prerequisites

  • I have searched the issues and believe that it has not already been requested (and possibly rejected)
  • I am using the latest version of bard-ai

Feature description

I want to make a request to add new feature text to sound feature and also search an image through this bard AI, is it possible?

Error when initializing Bard

Hey, I am getting a ReferenceError: fetch is not defined,
when trying to initialize Bard with Bard.init("KEY"), I am calling the init function on a express js app route, am I doing a mistake?

Can't generate response when using old chat export only works with new chat

when i use old chat export it only returns "Google Bard encountered an error )]}'

39
[["wrb.fr",null,null,null,null,[13]]]
58
[["di",8769],["af.httprm",8768,"6620395296999733811",0]]
25
[["e",4,null,null,134]]
.
at queryBard (file:///home/runner/XaviaBot/node_modules/bard-ai/index.js:88:15)
at processTicksAndRejections (node:internal/process/task_queues:96:5)"here's my code:import Bard from "bard-ai";
import sqlite3 from "sqlite3";
import fetch from 'node-fetch'
global.fetch = fetch;

Bard.init("YAgdpqonMlUB0ELzDB_hFNjqXtv-4iXn29DaSsr-abQGyVy8rvehwyE8Q0EfyvBGbOCmQw.");

const db = new sqlite3.Database("database.db");

db.run(CREATE TABLE IF NOT EXISTS users ( uid TEXT PRIMARY KEY, conversationID TEXT, responseID TEXT, choiceID TEXT, _reqID TEXT ));

async function generateResponse(prompt, uid) {
prompt = decodeURIComponent(prompt);

if (!prompt) {
throw new Error("Please provide a prompt.");
}

if (!uid) {
const response = await Bard.askAI(prompt, { useJSON: true });
const images = response.images ? response.images.map((image) => image.url) : [];
const contentWithoutImages = response.content?.replace(/![.?]([^)]+)\n/g, "") || response.content;
const modifiedResponse = {
content: contentWithoutImages,
...(images.length > 0 && { images }),
};

return modifiedResponse;

}

try {
const userData = await getUserData(uid);
console.log(userData)

if (userData) {
  const { conversationID, responseID, choiceID, _reqID } = userData;
  const userChat = new Bard.Chat({ conversationID, responseID, choiceID, _reqID });
  const response = await userChat.ask(prompt, { useJSON: true });
  const ID = userChat.export();
  const images = response.images ? response.images.map((image) => image.url) : [];
  const contentWithoutImages = response.content?.replace(/\!\[.*?\]\([^)]+\)\n*/g, "") || response.content;
  const modifiedResponse = {
    content: contentWithoutImages,
    ...(images.length > 0 && { images }),
  };

  await updateUserData(uid, {
    conversationID: ID.conversationID,
    responseID: ID.responseID,
    choiceID: ID.ids.choiceID,
    _reqID: ID._reqID,
  });

  return modifiedResponse;
} else {
  const newChat = new Bard.Chat();
  const response = await newChat.ask(prompt, { useJSON: true });
  const ID = newChat.export();
  const images = response.images ? response.images.map((image) => image.url) : [];
  const contentWithoutImages = response.content?.replace(/\!\[.*?\]\([^)]+\)\n*/g, "") || response.content;
  const newUser = {
    uid: uid,
    conversationID: ID.conversationID,
    responseID: ID.responseID,
    choiceID: ID._reqIDchoiceID,
    _reqID: ID._reqID,
  };

  await createUserData(newUser);

  const modifiedResponse = {
    content: contentWithoutImages,
    ...(images.length > 0 && { images }),
  };

  return modifiedResponse;
}

} catch (error) {
console.error("Failed to generate response:", error);
throw new Error("Failed to generate response.");
}
}

async function getUserData(uid) {
return new Promise((resolve, reject) => {
db.get("SELECT * FROM users WHERE uid = ?", uid, (err, row) => {
if (err) {
console.error("Failed to retrieve user data:", err);
reject(err);
} else {
resolve(row);
}
});
});
}

async function createUserData(userData) {
return new Promise((resolve, reject) => {
db.run(
"INSERT INTO users (uid, conversationID, responseID, choiceID, _reqID) VALUES (?, ?, ?, ?, ?)",
[userData.uid, userData.conversationID, userData.responseID, userData.choiceID, userData._reqID],
(err) => {
if (err) {
console.error("Failed to create user data:", err);
reject(err);
} else {
resolve();
}
}
);
});
}

async function updateUserData(uid, userData) {
return new Promise((resolve, reject) => {
db.run(
"UPDATE users SET conversationID = ?, responseID = ?, choiceID = ?, _reqID = ? WHERE uid = ?",
[userData.conversationID, userData.responseID, userData.choiceID, userData._reqID, uid],
(err) => {
if (err) {
console.error("Failed to update user data:", err);
reject(err);
} else {
resolve();
}
}
);
});
}

async function resetChat(uid) {
try {
await deleteUserData(uid);
} catch (error) {
console.error("Failed to reset chat:", error);
throw new Error("Failed to reset chat.");
}
}

async function deleteUserData(uid) {
return new Promise((resolve, reject) => {
db.run("DELETE FROM users WHERE uid = ?", uid, (err) => {
if (err) {
console.error("Failed to delete user data:", err);
reject(err);
} else {
resolve();
}
});
});
}

export { generateResponse, resetChat };

Error: TypeError: Cannot read properties of nul l (reading '4')

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

const answer = chatData[4][0];

TypeError: Cannot read properties of nul l (reading '4') at #query (file:///home/runner/node- api/node_modules/bard-ai/index.js:240:32)

at process.processTicksAndRejections (node: internal/process/task_queues:95:5 )

at async Bard.ask (file:///home/runn er/node-api/node_modules/bard-ai/index.j s:342:24)

at async file:///home/runner/node-api/test.js:7:13

Reproduction Steps

See err

Other information

No response

Occurance Rate

I can reproduce this bug 100% of the time.

Error [ERR_REQUIRE_ESM]: require() of ES Module...

Hello!

I'm trying to implement a short typescript script to play around, but somehow I am not able to get it running.
Here are the most important files.

{
  "name": "bard",
  "version": "1.0.0",
  "description": "",
  "main": "./src/index.ts",
  "scripts": {
      "start": "ts-node ./src/index.ts"
  },
  "keywords": [],
  "author": "anon",
  "license": "ISC",
  "dependencies": {
    "@types/node": "^20.4.2",
    "bard-ai": "^1.5.4",
    "ts-node": "^10.9.1"
  }
}
import { askAI, init } from "bard-ai";

const COOKIE_KEY =
  "__Secure-1PSID=XXX";

const main = async () => {
  await init(COOKIE_KEY);
  console.log(await askAI("Hello world!"));
};

main();

When I try

npm run start

i get this:

Error [ERR_REQUIRE_ESM]: require() of ES Module ~/bard/node_modules/bard-ai/index.js from ~/bard/src/index.ts not supported.
Instead change the require of index.js in ~/bard/src/index.ts to a dynamic import() which is available in all CommonJS modules.

Any idea why? I'm not sure if i understand the error.

fix-esm issue to use bard-ai.

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

I was using bard-ai with this instead of import:
const Bard = require("fix-esm").require("bard-ai");

It was working great. But after the bard-ai v2:

It started to give this error:
TypeError: Bard is not a constructor

Is it still possible for me to use it? I was be able to use it before the v2.
Currently impossible for me to use import.

Reproduction Steps

Use fix-esm.

Other information

No response

Occurance Rate

I can reproduce this bug 100% of the time.

Error: Could not get Google Bard.

Error: Could not get Google Bard.
at Module.init (file:///c:/alok/node_modules/bard-ai/index.js:29:16)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async hamz (c:\alok\connect\hamz.js:2467:1)

Bard changed their API UI

Since Google changed the API of bard, using jsonChatData[0][0] no longer works, a solution to that is fairly simple, change it to jsonChatData[4][0][1][0]. A re-written version of index.js is attached bellow.
Kind regards, Azury Industries. @EvanZhouDev

let session, SNlM0e;

export const init = async (sessionID) => {
    session = {
        baseURL: "https://bard.google.com",
        headers: {
            Host: "bard.google.com",
            "X-Same-Domain": "1",
            "User-Agent":
                "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
            Origin: "https://bard.google.com",
            Referer: "https://bard.google.com/",
            Cookie: `__Secure-1PSID=${sessionID};`,
        },
    };

    const response = await fetch("https://bard.google.com/", {
        method: "GET",
        headers: session.headers,
        credentials: "include",
    });

    const data = await response.text();

    const match = data.match(/SNlM0e":"(.*?)"/);

    if (match) SNlM0e = match[1];
    else throw new Error("Could not get Google Bard.");

    return SNlM0e;
};

export const queryBard = async (message, ids = {}) => {
    if (!SNlM0e)
        throw new Error("Make sure to call Bard.init(SESSION_ID) first.");

    // Parameters and POST data
    const params = {
        bl: "boq_assistant-bard-web-server_20230613.09_p0",
        _reqID: ids._reqID ? `${ids._reqID}` : "0",
        rt: "c",
    };

    const messageStruct = [
        [message],
        null,
        ids ? Object.values(ids).slice(0, 3) : [null, null, null],
    ];

    const data = {
        "f.req": JSON.stringify([null, JSON.stringify(messageStruct)]),
        at: SNlM0e,
    };

    let url = new URL(
        "/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate",
        session.baseURL
    );

    Object.keys(params).forEach((key) =>
        url.searchParams.append(key, params[key])
    );

    let formBody = [];

    for (let property in data) {
        let encodedKey = encodeURIComponent(property);
        let encodedValue = encodeURIComponent(data[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }

    formBody = formBody.join("&");

    const response = await fetch(url.toString(), {
        method: "POST",
        headers: session.headers,
        body: formBody,
        credentials: "include",
    });

    const responseData = await response.text();

    const chatData = JSON.parse(responseData.split("\n")[3])[0][2];

    // Check if there is data
    if (!chatData) {
        return `Google Bard encountered an error ${responseData}.`;
    }

    // Get important data, and update with important data if set to do so
    const jsonChatData = JSON.parse(chatData);

    let text = jsonChatData[4][0][1][0];

    let images = jsonChatData[4][0][4]
        ? jsonChatData[4][0][4].map((x) => {
            return {
                tag: x[2],
                url: x[0][5].match(/imgurl=([^&%]+)/)[1],
            };
        })
        : undefined;

    return {
        content: formatMarkdown(text, images),
        images: images,
        ids: {
            // Make sure kept in order, because using Object.keys() to query above
            conversationID: jsonChatData[1][0],
            responseID: jsonChatData[1][1],
            choiceID: jsonChatData[4][0][0],
            _reqID: parseInt(ids._reqID ?? 0) + 100000,
        },
    };
};

const formatMarkdown = (text, images) => {
    if (!images) return text;

    const formattedTags = new Map();

    for (let imageData of images) {
        const formattedTag = `![${imageData.tag.slice(1, -1)}](${imageData.url
            })`;

        if (formattedTags.has(imageData.tag)) {
            const existingFormattedTag = formattedTags.get(imageData.tag);

            formattedTags.set(
                imageData.tag,
                `${existingFormattedTag}\n${formattedTag}`
            );
        } else {
            formattedTags.set(imageData.tag, formattedTag);
        }
    }

    for (let [tag, formattedTag] of formattedTags) {
        text = text.replace(tag, formattedTag);
    }

    return text;
};

export const askAI = async (message, useJSON = false) => {
    if (useJSON) return await queryBard(message);
    else return (await queryBard(message)).content;
};

export class Chat {
    constructor(ids) {
        this.ids = ids;
    }

    async ask(message, useJSON = false) {
        let request = await queryBard(message, this.ids);
        this.ids = { ...request.ids };
        if (useJSON) return request;
        else return request.content;
    }

    export() {
        return this.ids;
    }
}

export default { init, askAI, Chat };

`bard-ai` v2.0

This is the feature tracker for bard-ai Version 2 (See v2 branch). Here's what's in store:

  • ๐Ÿ—๏ธ API redesign
  • ๐Ÿช Multiple Cookie Usage with new Bard(COOKIE)
  • โš™๏ธ Advanced Configuration with {...config} on Bard and ask()
  • ๐Ÿ”Š Verbose Mode
  • ๐Ÿ–ผ๏ธ Photo input

What still needs to be done:

  • ๐Ÿ’ฌ Re-implement Chat
  • ๐Ÿช Different User Cookies: __Secure-PSID${x}
  • ๐Ÿงช Tests (with vitest)
    • ๐Ÿ“– Extract a Bard.parse function that ensures text response is parsed correctly
    • ๐Ÿ—“๏ธ Daily Bard runs to ensure bard-ai is working fine
  • ๐Ÿ“ Separate README for GitHub and NPM (so that assets don't have to be downloaded)
  • ๐Ÿ Finishing Touches
  • Make sure to modify branch on test

After everything has been re-imagined, we will be testing for a while, and it should be released!

Use cases for advance and json response

I am quite confuse about:

let myConversationContinued = new Bard.Chat({
	conversationID: string,
	responseID: string,
	choiceID: string,
	_reqID: string,
});

I can understand the conversationID however why do we need the responseID, choiceID, and _reqID we need brief explanation such us what does it do, how important it is. conversationID based on what I understand this is the one that keeps or holds the entire conversation. but I am lost at responseID, choiceID, and _reqID. Can you enlighten me about this? or is it possible to use conversationID id only? because i have conversationID via supabase database that group them together and maybe i can use that to specify which conversation they are talking right?

Also how do you guys use the useJSON if ever i use the advanced way? do i have to include it on the myConversationContinued thing to i still have to do it next to the message?

๐Ÿ› [BUG]: TypeError: Cannot read properties of undefined (reading 'createChat') - [v2.0.3]

Prerequisites

  • I have searched the issues and believe that it has not already been reported
  • It occurs on the latest version of bard-ai
  • I have read the FAQ and there are no solutions there

Bug Description

I am trying to implement from 1.5.X to 2.0.3 and I have encountered TypeError: Cannot read properties of undefined (reading 'createChat') while following this new documentation for V2.

Console log:

TypeError: Cannot read properties of undefined (reading 'createChat')
    at handler (webpack-internal:///(api)/./pages/api/ai.ts:170:67)
    at D:\Mechi\node_modules\next\dist\server\api-utils\node.js:463:16
    at D:\Mechi\node_modules\next\dist\server\lib\trace\tracer.js:117:36
    at NoopContextManager.with (D:\Mechi\node_modules\next\dist\compiled\@opentelemetry\api\index.js:1:7057)
    at ContextAPI.with (D:\Mechi\node_modules\next\dist\compiled\@opentelemetry\api\index.js:1:516)
    at NoopTracer.startActiveSpan (D:\Mechi\node_modules\next\dist\compiled\@opentelemetry\api\index.js:1:18086)
    at ProxyTracer.startActiveSpan (D:\Mechi\node_modules\next\dist\compiled\@opentelemetry\api\index.js:1:18847)
    at D:\Mechi\node_modules\next\dist\server\lib\trace\tracer.js:106:107
    at NoopContextManager.with (D:\Mechi\node_modules\next\dist\compiled\@opentelemetry\api\index.js:1:7057)
    at ContextAPI.with (D:\Mechi\node_modules\next\dist\compiled\@opentelemetry\api\index.js:1:516)
    at NextTracerImpl.trace (D:\Mechi\node_modules\next\dist\server\lib\trace\tracer.js:106:32)
    at apiResolver (D:\Mechi\node_modules\next\dist\server\api-utils\node.js:461:63)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async DevServer.runApi (D:\Mechi\node_modules\next\dist\server\next-server.js:675:9)
    at async Object.fn (D:\Mechi\node_modules\next\dist\server\next-server.js:1146:35)
    at async Router.execute (D:\Mechi\node_modules\next\dist\server\router.js:315:32)
    at async DevServer.runImpl (D:\Mechi\node_modules\next\dist\server\base-server.js:615:29)
    at async DevServer.run (D:\Mechi\node_modules\next\dist\server\dev\next-dev-server.js:908:20)
    at async DevServer.handleRequestImpl (D:\Mechi\node_modules\next\dist\server\base-server.js:546:20)

Reproduction Steps

Code:

//other imports..
import Bard from "bard-ai";
import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
//other code..
switch (req.method) {
  case 'POST':
    //other code..
    case 'bard':
      try {

        //For google bard only

        //If new conversation
        const newBard = req.body.newBard; 

        //If already have a previous
        const conversationID = req.body.conversationID;
        const responseID = req.body.responseID;
        const choiceID = req.body.choiceID;
        const _reqID = req.body._reqID;

        const myBard  = new Bard({
          "__Secure-1PSID": 'XXXXXXXXXXXXXXX',
          "__Secure-1PSIDTS": 'XXXXXXXXXXXXXXXXXXX',
        });

        const myChat = myBard.createChat();

        if(newBard) {

          const response = await myChat.ask(message);

          res.status(200).send({ bot: response, bard: myChat.export() });

          let obj: any;

          if (typeof response === 'string') {
            // response is already a string, so use it as it is
            obj = response;
          } else {
            // response is of type queryBardValidRes, stringify the object
            obj = JSON.stringify(response);
          }
          

        }else{

          let myConversationContinued = newBard.createChat({
            conversationID: conversationID,
            responseID: responseID,
            choiceID: choiceID,
            _reqID: _reqID,
          });

          const response = await myConversationContinued.ask(message);

          res.status(200).send({ bot: response });

          let obj: any;

          if (typeof response === 'string') {
            // response is already a string, so use it as it is
            obj = response;
          } else {
            // response is of type queryBardValidRes, stringify the object
            obj = JSON.stringify(response);
          }

        }
      }
      catch (error) {
        //Send temporary error message to users in the chat
        res.status(200).send({ bot: 'Something went wrong! I am experiencing high volume of request at the moment, Please try again later.' });
        console.error(error);
      }
    break;
    //other code..
  default:
    res.status(405).end(); //Method Not Allowed
  }
};

Other information

{
  "name": "XXXX",
  "version": "XXXX",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@headlessui/react": "^1.7.15",
    "@types/node": "20.4.1",
    "@types/react": "18.2.14",
    "@types/react-dom": "18.2.6",
    "autoprefixer": "10.4.14",
    "bard-ai": "^2.0.3",
    "daisyui": "^3.2.1",
    "eslint": "8.44.0",
    "eslint-config-next": "13.4.9",
    "flowbite": "^1.7.0",
    "next": "13.4.9",
    "next-pwa": "^5.6.0",
    "next-themes": "^0.2.1",
    "node-fetch": "^3.3.1",
    "postcss": "8.4.25",
    "react": "18.2.0",
    "tailwindcss": "3.3.2",
    "typescript": "5.1.6",
    "webpack": "^5.88.1",
    "zustand": "^4.3.9"
  },
  "devDependencies": { }
}

Occurance Rate

I can reproduce this bug 100% of the time.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.