Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Flask Templates
  • Jinja2
  • Flask-REST API
  • Python SQLAlchemy
  • Flask Bcrypt
  • Flask Cookies
  • Json
  • Postman
  • Django
  • Flask Projects
  • Flask Interview Questions
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJs
  • Vue.Js
Open In App
Next Article:
Create a ChatBot with OpenAI and Gradio in Python
Next article icon

Build an AI Chatbot in Python using Cohere API

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • Installing Python
  • Installing Flask

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
Screenshot-(503)
Example for the above step

Step 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
Screenshot-(619)
example

After 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
Screenshot-(620)
app running on local host

Output:

Screenshot-(625)
Enter you Questions here on the text field
imgonline-com-ua-resize-YGCuenks8aKkk-min

Video Demonstration



Next Article
Create a ChatBot with OpenAI and Gradio in Python

S

syedalihaider02
Improve
Article Tags :
  • Python
  • Python Flask
  • AI Chatbot
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences