Skip to content

Instantly share code, notes, and snippets.

@leftmove
Last active May 29, 2024 17:38
Show Gist options
  • Save leftmove/d26b1bad8d20cf15ab4e627bfd1e4cd4 to your computer and use it in GitHub Desktop.
Save leftmove/d26b1bad8d20cf15ab4e627bfd1e4cd4 to your computer and use it in GitHub Desktop.
Gemini API Command Line Chat Bot
import os
import json
from datetime import datetime
from dotenv import load_dotenv
from colorama import Fore, Back, Style
load_dotenv()
import google.generativeai as genai
genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
model = genai.GenerativeModel("gemini-1.5-pro-latest")
message_history = []
def get_response(chat, new_question):
response = chat.send_message(new_question)
for chunk in response:
print(chunk.text)
return response
def main():
os.system("cls" if os.name == "nt" else "clear")
previous_questions_and_answers = []
while True:
try:
chat = model.start_chat(history=[])
new_question = input(
Fore.BLUE + Style.BRIGHT + "Chat: " + Style.RESET_ALL
)
if new_question:
response = get_response(chat, new_question)
else:
continue
message_history.append(response.text)
except KeyboardInterrupt:
print("\nGoodbye!")
now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"chat-{now}.json"
with open(filename, 'w') as f:
json.dump(message_history, f, indent=6)
message_history.clear()
break
if __name__ == "__main__":
main()
@leftmove
Copy link
Author

leftmove commented May 21, 2024

Important

You need an API key from Google to operate the above code, you can find one here.

Once you have an API key, setup a .env file with the following text in the same folder as your code.

GOOGLE_API_KEY = "<YOUR API KEY>"

Text is styled, but this is optional; you can disable styling by replacing line 31 with "Chat: ". Additionally, all chat history is automatically stored as local JSON; you can disable this by commenting out lines 44-47. For both disables, make sure to remove unused all imports.


A simple command line chat bot that uses Google's Gemini API.

This works as a free alternative to any CLI chat bots using OpenAI, Anthropic, etc.

You can learn more about the Gemini API at https://ai.google.dev/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment