Open In App

Build an AI Chatbot in Python using Cohere API

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
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:

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads