In this short guide, we will build an AI chatbot that works in your command line program.
This is really how to guide and showcase how powerful the new chat API from cohereAI is.
Let’s dive in
Table of Contents
Requirements and Pre-requisites
- You need to have Python 3.x or higher installed
- You should know your way around a command line program like Terminal on Mac or Linux or cmd or PowerShell on Windows
- You should have your own cohereAI API key. If you don’t have one, you should go ahead and create an account now.
- create a new folder/directory and cd to the directory
- set up an environment variable COHEREAI_API_KEY Example on a Linux or Mac machine:
- Install cohere python package
pip install cohere==3.1.6
Let’s write the code
Create a new file called app.py in the folder and below code and save it.
# import necessary packages import os import cohere # initialize cohere api client co = cohere.Client(os.environ.get('COHEREAI_API_KEY')) # initialize a conversation session id cohere_chat_res_start = co.chat("Hi") conv_session_id = cohere_chat_res_start.session_id # continue existing chat session def talk(prompt): response = co.chat(prompt, session_id=conv_session_id) return response.reply # take prompt from user and call talk function. run this in loop till user exits while True: prompt = input("You: ") if prompt == "exit": break print("Bot: ", talk(prompt))
This code imports the necessary packages ‘os’ and ‘cohere’. Then it initializes the cohere API client using an API key stored in the environment variable ‘COHEREAI_API_KEY’.
It then starts a conversation by calling the chat function with the initial message ‘Hi’ and stores the session id. The function ‘talk’ is defined, which takes a prompt as input and uses the cohere API client to continue the existing chat session by passing the prompt and session id as arguments.
In a while loop, the user’s prompt is taken as input, and the ‘talk’ function is called with this prompt as an argument. The loop continues until the user quits the program. The bot’s response is printed after each prompt.
Run the chatbot
Run this command to start the chatbot
This is how it would look like when you run it.
Note: This tool uses the same session as long as you keep running it. To start fresh, just quit the tool and run again
Show me the code
Here is the code repo on github that contains the example I put together for this guide.