Build an AI Chatbot in Python using Cohere API

Last Updated : 7 Apr, 2026

A chatbot is a system that simulates human conversation using AI and NLP techniques. It can understand user queries and generate meaningful responses. With the Cohere API, you can easily build intelligent chat-based applications. This setup uses Python and Flask to create a simple web-based chatbot.

Prerequisites

  • Python 3+
  • Flask (Python web framework)

If Flask is not installed, install it using the below command:

pip install flask

Step by Step Implementation

Step 1: Get Your Cohere API Key

Before building the chatbot, you need an API key from Cohere to access their language models. Follow these steps to get your API key:

1. Go to the Cohere dashboard, sign up or log in to your account and navigate to the API Keys section

Screenshot-2026-04-07-131035
select API Keys

2. Click on Create API Key (if not already created) and copy the generated API key

Screenshot-2026-04-07-131518
copy the key and paste it notepad and save it

Note: Keep your API key private and do not share it publicly.

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 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.

app.py

Python
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)

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.

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

Run "python app.py" on your terminal and the link for the local host would be generated.

After that just click on the "http://127.0.0.1:5000/" and you would be redirected to your app(chatbot).

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

Comment