|
| 1 | +from Bard import Chatbot |
| 2 | +from pytgpt.base import Provider |
| 3 | +from pytgpt.utils import Conversation |
| 4 | +from pytgpt.utils import Optimizers |
| 5 | +from os import path |
| 6 | +from json import load |
| 7 | +from json import dumps |
| 8 | +import warnings |
| 9 | + |
| 10 | +warnings.simplefilter("ignore", category=UserWarning) |
| 11 | + |
| 12 | + |
| 13 | +class BARD(Provider): |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + auth: str, |
| 17 | + proxy: dict = {}, |
| 18 | + timeout: int = 30, |
| 19 | + ): |
| 20 | + """Initializes BARD |
| 21 | +
|
| 22 | + Args: |
| 23 | + auth (str): `__Secure-1PSID` cookie value (session id) or path to `bard.google.com.cookies.json` file |
| 24 | + proxy (dict, optional): Http request proxy. Defaults to {}. |
| 25 | + timeout (int, optional): Http request timeout. Defaults to 30. |
| 26 | + """ |
| 27 | + self.conversation = Conversation(False) |
| 28 | + self.session_auth = None |
| 29 | + assert isinstance(auth, str), f"auth should be of {str} only not '{type(auth)}'" |
| 30 | + if path.isfile(auth): |
| 31 | + # let's assume auth is a path to exported .json cookie-file |
| 32 | + with open(auth) as fh: |
| 33 | + entries = load(fh) |
| 34 | + for entry in entries: |
| 35 | + if entry["name"] == "__Secure-1PSID": |
| 36 | + self.session_auth = entry["value"] |
| 37 | + assert bool( |
| 38 | + self.session_auth |
| 39 | + ), f"Failed to extract the required cookie value from file '{auth}'" |
| 40 | + else: |
| 41 | + # Assume auth is the targeted cookie value |
| 42 | + self.session_auth = auth |
| 43 | + |
| 44 | + self.session = Chatbot(self.session_auth, proxy, timeout) |
| 45 | + self.last_response = {} |
| 46 | + self.__available_optimizers = ( |
| 47 | + method |
| 48 | + for method in dir(Optimizers) |
| 49 | + if callable(getattr(Optimizers, method)) and not method.startswith("__") |
| 50 | + ) |
| 51 | + |
| 52 | + def ask( |
| 53 | + self, |
| 54 | + prompt: str, |
| 55 | + stream: bool = False, |
| 56 | + raw: bool = False, |
| 57 | + optimizer: str = None, |
| 58 | + conversationally: bool = False, |
| 59 | + ) -> dict: |
| 60 | + """Chat with AI |
| 61 | +
|
| 62 | + Args: |
| 63 | + prompt (str): Prompt to be send. |
| 64 | + stream (bool, optional): Flag for streaming response. Defaults to False. |
| 65 | + raw (bool, optional): Stream back raw response as received. Defaults to False. |
| 66 | + optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defeaults to None |
| 67 | + conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False. |
| 68 | + Returns: |
| 69 | + dict : {} |
| 70 | + ```json |
| 71 | + { |
| 72 | + "content": "General Kenobi! \n\n(I couldn't help but respond with the iconic Star Wars greeting since you used it first. )\n\nIs there anything I can help you with today?\n[Image of Hello there General Kenobi]", |
| 73 | + "conversation_id": "c_f13f6217f9a997aa", |
| 74 | + "response_id": "r_d3665f95975c368f", |
| 75 | + "factualityQueries": null, |
| 76 | + "textQuery": [ |
| 77 | + "hello there", |
| 78 | + 1 |
| 79 | + ], |
| 80 | + "choices": [ |
| 81 | + { |
| 82 | + "id": "rc_ea075c9671bfd8cb", |
| 83 | + "content": [ |
| 84 | + "General Kenobi! \n\n(I couldn't help but respond with the iconic Star Wars greeting since you used it first. )\n\nIs there anything I can help you with today?\n[Image of Hello there General Kenobi]" |
| 85 | + ] |
| 86 | + }, |
| 87 | + { |
| 88 | + "id": "rc_de6dd3fb793a5402", |
| 89 | + "content": [ |
| 90 | + "General Kenobi! (or just a friendly hello, whichever you prefer!). \n\nI see you're a person of culture as well. *Star Wars* references are always appreciated. \n\nHow can I help you today?\n" |
| 91 | + ] |
| 92 | + }, |
| 93 | + { |
| 94 | + "id": "rc_a672ac089caf32db", |
| 95 | + "content": [ |
| 96 | + "General Kenobi! (or just a friendly hello if you're not a Star Wars fan!). \n\nHow can I help you today? Feel free to ask me anything, or tell me what you'd like to chat about. I'm here to assist in any way I can.\n[Image of Obi-Wan Kenobi saying hello there]" |
| 97 | + ] |
| 98 | + } |
| 99 | + ], |
| 100 | +
|
| 101 | + "images": [ |
| 102 | + "https://i.pinimg.com/originals/40/74/60/407460925c9e419d82b93313f0b42f71.jpg" |
| 103 | + ] |
| 104 | + } |
| 105 | +
|
| 106 | + ``` |
| 107 | + """ |
| 108 | + conversation_prompt = self.conversation.gen_complete_prompt(prompt) |
| 109 | + if optimizer: |
| 110 | + if optimizer in self.__available_optimizers: |
| 111 | + conversation_prompt = getattr(Optimizers, optimizer)( |
| 112 | + conversation_prompt if conversationally else prompt |
| 113 | + ) |
| 114 | + else: |
| 115 | + raise Exception( |
| 116 | + f"Optimizer is not one of {self.__available_optimizers}" |
| 117 | + ) |
| 118 | + |
| 119 | + def for_stream(): |
| 120 | + response = self.session.ask(prompt) |
| 121 | + self.last_response.update(response) |
| 122 | + self.conversation.update_chat_history( |
| 123 | + prompt, self.get_message(self.last_response) |
| 124 | + ) |
| 125 | + yield dumps(response) if raw else response |
| 126 | + |
| 127 | + def for_non_stream(): |
| 128 | + # let's make use of stream |
| 129 | + for _ in for_stream(): |
| 130 | + pass |
| 131 | + return self.last_response |
| 132 | + |
| 133 | + return for_stream() if stream else for_non_stream() |
| 134 | + |
| 135 | + def chat( |
| 136 | + self, |
| 137 | + prompt: str, |
| 138 | + stream: bool = False, |
| 139 | + optimizer: str = None, |
| 140 | + conversationally: bool = False, |
| 141 | + ) -> str: |
| 142 | + """Generate response `str` |
| 143 | + Args: |
| 144 | + prompt (str): Prompt to be send. |
| 145 | + stream (bool, optional): Flag for streaming response. Defaults to False. |
| 146 | + optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None. |
| 147 | + conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False. |
| 148 | + Returns: |
| 149 | + str: Response generated |
| 150 | + """ |
| 151 | + |
| 152 | + def for_stream(): |
| 153 | + for response in self.ask( |
| 154 | + prompt, True, optimizer=optimizer, conversationally=conversationally |
| 155 | + ): |
| 156 | + yield self.get_message(response) |
| 157 | + |
| 158 | + def for_non_stream(): |
| 159 | + return self.get_message( |
| 160 | + self.ask( |
| 161 | + prompt, |
| 162 | + False, |
| 163 | + optimizer=optimizer, |
| 164 | + conversationally=conversationally, |
| 165 | + ) |
| 166 | + ) |
| 167 | + |
| 168 | + return for_stream() if stream else for_non_stream() |
| 169 | + |
| 170 | + def get_message(self, response: dict) -> str: |
| 171 | + """Retrieves message only from response |
| 172 | +
|
| 173 | + Args: |
| 174 | + response (dict): Response generated by `self.ask` |
| 175 | +
|
| 176 | + Returns: |
| 177 | + str: Message extracted |
| 178 | + """ |
| 179 | + assert isinstance(response, dict), "Response should be of dict data-type only" |
| 180 | + return response["content"] |
0 commit comments