Build an AI Chatbot in Python using Cohere API
Last Updated : 24 Apr, 2025
A chatbot is a technology that is made to mimic human-user communication. It makes use of machine learning, natural language processing (NLP), and artificial intelligence (AI) techniques to comprehend and react in a conversational way to user inquiries or cues. In this article, we will be developing a chatbot that would be capable of answering most of the questions like other GPT models. For that, we will be using Cohere API.
What is Cohere API?
Cohere API is a powerful tool that empowers developers to integrate advanced natural language processing (NLP) features into their apps. This API, created by Cohere, combines the most recent developments in language modeling and machine learning to offer a smooth and intelligent conversational experience.
Cohere offers both free and paid API. The trial version is free to use but it comes with few restrictions. But as for now we only need the trial API.
Chatbot using Cohere API in Python
Below is the step-by-step approach for making a chatbot using cohere API in Python:
Step 1: Installation
This is the first step in which we will install the following libraries and modules before starting:
Step 2: Create a Virtual Environment
Open Anaconda Navigator and Launch vs-code or PyCharm as per your compatibility. Now to create a virtual Environment write the following code on the terminal.
python -m venv ["Your environment name"]
Then activate the environment using the following command.
["Your environment name"]\Scripts\activate
Example for the above stepStep 3: Create a app.py File
In this code, we begin by importing essential packages for our chatbot application. The Flask framework, Cohere API library, and other necessary modules are brought in to facilitate web development and natural language processing. A Form named 'Form' is then created, incorporating a text field to receive user questions and a submit field. The Flask web application is initiated, and a secret key is set for CSRF protection, enhancing security. Then we create a instance of Class 'Form', So that we can utilize the text field and submit field values.
The main route ('/') is established, allowing the application to handle both GET and POST requests. Within the 'home' function, the form is instantiated, and a connection to the Cohere API is established using the provided API key. Upon form submission, the user's input is captured, and the Cohere API is utilized to generate a response. The model parameters are configured to fine-tune the generation process. The resulting response is rendered onto the 'home.html' template along with the form, allowing users to see the generated output.
app.py
Python3 import cohere from flask import Flask, render_template, request, redirect, url_for from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired import secrets app = Flask(__name__) app.secret_key = secrets.token_hex(16) # Set a secret key for CSRF protection class Form(FlaskForm): text = StringField('Enter text to search', validators=[DataRequired()]) submit = SubmitField('Submit') @app.route('/', methods=['GET', 'POST']) def home(): form = Form() co = cohere.Client('YOUR API KEY') if form.validate_on_submit(): text = form.text.data response = co.generate( model='command-nightly', prompt=text, max_tokens=300, temperature=0.9, k=0, p=0.75, stop_sequences=[], return_likelihoods='NONE' ) output = response.generations[0].text return render_template('home.html', form=form, output=output) return render_template('home.html', form=form, output=None) if __name__ == "__main__": app.run(debug=True)
Step 4: Setting up GUI
This code creates a Flask web application that lets users input data. When users submit the form, the text data(Questions) is used to generate the output or answer for that particular question. The output is then displayed on the same webpage.
home.html
HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flask Cohere App</title> <style> body { font-family: 'Arial', sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; box-sizing: border-box; } h1 { text-align: center; color: #333; } form { max-width: 600px; margin: 20px auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } label { display: block; margin-bottom: 10px; font-weight: bold; } input { width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } button { background-color: #4caf50; color: #fff; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #45a049; } h2 { margin-top: 20px; color: #333; } p { color: #555; } /* New style for the output boundary */ .output-container { max-width: 600px; margin: 20px auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } </style> </head> <body> <h1>ChatBot</h1> <form method="post" action="{{ url_for('home') }}"> {{ form.hidden_tag() }} <label for="text">Enter text to search:</label> {{ form.text(size=40) }} {{ form.submit() }} </form> {% if output %} <div class="output-container"> <h2>Generated Output:</h2> <p>{{ output }}</p> </div> {% endif %} </body> </html>
Step 5: Running the app on local host
Just write "python app.py" on your terminal and the link for the local host would be generated.
python app.py
exampleAfter that just click on the "http://127.0.0.1:5000" and you would be redirected to your app(chatbot).
http://127.0.0.1:5000
app running on local hostOutput:
Enter you Questions here on the text field
Video Demonstration
Similar Reads
Build a QnA ChatBot using Gemini Pro
A chatbot is a computer program designed to simulate human conversation, usually through text or voice interactions. They use natural language processing (NLP) and machine learning algorithms to understand and respond to user queries, providing a personalized experience. Gemini is an AI model made b
5 min read
Dominos Chatbot using Python
Chatbots are gaining popularity as a means for businesses to interact with their customers. Domino's Pizza is one such company that has used a chatbot to improve its customer service. In this article, we'll look at how to use Python to create a chatbot for Domino's Pizza. Tools and Technologies Used
11 min read
How to Use ChatGPT API in Python?
ChatGPT and its inevitable applications. Day by Day everything around us seems to be getting automated by several AI models using different AI and Machine learning techniques and Chatbot with Python , there are numerous uses of Chat GPT and one of its useful applications we will be discussing today.
6 min read
Create a ChatBot with OpenAI and Streamlit in Python
ChatGPT is an advanced chatbot built on the powerful GPT-3.5 language model developed by OpenAI.There are numerous Python Modules and today we will be discussing Streamlit and OpenAI Python API to create a chatbot in Python streamlit. The user can input his/her query to the chatbot and it will send
5 min read
Create a ChatBot with OpenAI and Gradio in Python
Computer programs known as chatbots may mimic human users in communication. They are frequently employed in customer service settings where they may assist clients by responding to their inquiries. The usage of chatbots for entertainment, such as gameplay or storytelling, is also possible. OpenAI Ch
3 min read
Deploy a Chatbot using TensorFlow in Python
In this article, you'll learn how to deploy a Chatbot using Tensorflow. A Chatbot is basically a bot (a program) that talks and responds to various questions just like a human would. We'll be using a number of Python modules to do this. This article is divided into two sections: First, we'll train
9 min read
Build Your Own Voice-Activated Calculator Using Python
In this article, you'll be delving into the development of a voice command calculator using Python, taking advantage of libraries like Speech-Recognition and PyAudio that will allow users with swift means of performing arithmetic operations. Developing such a program will require you to go through s
6 min read
Instagram Bot using Python and InstaPy
In this article, we will design a simple fun project âInstagram Botâ using Python and InstaPy. As beginners want to do some extra and learning small projects so that it will help in building big future projects. Now, this is the time to learn some new projects and a better future. This python projec
3 min read
How to Make a Chatbot in Python using Chatterbot Module?
A ChatBot is basically a computer program that conducts conversation between a user and a computer through auditory or textual methods. It works as a real-world conversational partner. ChatterBot is a library in python which generates a response to user input. It used a number of machine learning al
4 min read
Simple Chatbot application using Python, GoogleAPIKey
Google-GenerativeAI is Google AI Python SDK. It uses Gemini to build AI-powered features. In this article, we will see how to create a Simple Chatbot application using Python GoogleAPIKey. What is Google-GenerativeAI?Google-GenerativeAI is nothing but Google AI Python SDK. It enables to use of Gemin
4 min read