Creating an AI Text Summarization Bot in Python Using Cohere & Telegram

Gigi KennethGigi Kenneth
5 min read

In this blog post, we will go over how you can build a text summarizer bot using Cohere's API and integrate that into Telegram.

Text summarization is a great technique that can help condense large amounts of text into shorter, more concise summaries. And I decided to give this a shot because I've been doing a lot of summarizing for my AI Ethics project.

We'll be doing three things pretty much:

  • Get our API key from Cohere πŸ”‘

  • Set up our Telegram bot (get your token from The BotFather🀡🏾)

  • Join those two together in a cute way to get them to work πŸ«±πŸΎβ€πŸ«²πŸΎ

Let's get started:

Step 1: Obtain our API Key πŸ—οΈ

You will need to sign up for an account on Cohere's website (https://www.cohere.ai). Once you have an account, follow these steps to obtain the API key:

  1. Log in to your Cohere account.

  2. Navigate to the API Key section in your account settings.

  3. Generate an API key if you don't have one already.

  4. Copy the generated API key to use in your code.

Step 2: Create a Telegram Bot Using BotFather 🀡🏾

To set up your Telegram bot, you will need to create a bot account and obtain the bot token. Here are a couple of steps to do that:

  1. Open the Telegram app and search for BotFather.

  2. Start a chat with BotFather and follow the instructions.

  3. Use the /newbot command to create a new bot.

  4. Provide a name for your bot.

  5. Choose a username for your bot (must end with "bot").

  6. Once your bot is created, BotFather will provide you with a bot token. We'll use this later.

Step 3: Set up the Environment πŸŒ„

Make sure you have Python installed on your machine.

(PS: If you're lazy like me, just use Colab for all of this)

Create a new Python project and install the required dependencies.

In this case, we need the telebot and cohere libraries.

Let's get to pipping:

! pip install cohere
! pip install telebot
#! pip install requests

Step 4: Initialize the Cohere Client and Telegram Bot πŸ«±πŸΎβ€πŸ«²πŸΎ

The next step is to import the necessary libraries and create instances for the Cohere client and the Telegram bot.

Replace "COHERE-API-KEY" with your actual Cohere API key (from Step 1) and "TELEGRAM-BOT-TOKEN" with your Telegram bot token (from Step 2).

import telebot
import cohere

# Cohere API key
API_KEY = "COHERE-API-KEY"

# Create a Cohere client instance
co = cohere.Client(API_KEY)

# Create a Telegram bot instance
bot = telebot.TeleBot("TELEGRAM-BOT-TOKEN")

Step 5: Handle Incoming Messages πŸ“©

Define a message handler function that will be triggered whenever a message is received by the Telegram bot.

Inside the handler, extract the text from the incoming message.

@bot.message_handler(func=lambda message: True)
def handle_message(message):
    # Get the text from the incoming message
    text = message.text

    # ...

Step 6: Using Cohere for Text Summarization πŸ“œ

Inside the message handler, we're going to use the Cohere API to summarize the text.

Wrap the summarization code in a try-except block to handle any potential errors that may occur during the process.

try:
    # Use Cohere to summarize the text
    response = co.summarize(
        text=text,
        length='auto',
        format='auto',
        model='summarize-xlarge',
        additional_command='',
        temperature=0.3,
    )

    # Get the summary from the response
    summary = response.summary

    # Send the summary as a reply
    bot.reply_to(message, summary)

except Exception as e:
    # Log the error message
    print("Error:", str(e))

    # Handle any errors that occur during summarization
    bot.reply_to(message, "Oops! Something went wrong.")

Step 7: Start the Telegram Bot πŸ€–

Add this code at the end to start the Telegram bot and begin polling for incoming messages.

# Start the Telegram bot
bot.polling()

Big Finish Now...

import telebot
import cohere

# Cohere API key
API_KEY = "COHERE-API-KEY"

# Create a Cohere client instance
co = cohere.Client(API_KEY)

# Create a Telegram bot instance
bot = telebot.TeleBot("TELEGRAM BOT KEY")

# Define a handler for incoming messages
@bot.message_handler(func=lambda message: True)
def handle_message(message):
    # Get the text from the incoming message
    text = message.text

    try:
        # Use Cohere to summarize the text
        response = co.summarize(
            text=text,
            length='auto',
            format='auto',
            model='summarize-xlarge',
            additional_command='',
            temperature=0.3,
        )

        # Get the summary from the response
        summary = response.summary

        # Send the summary as a reply
        bot.reply_to(message, summary)

    except Exception as e:
        # Log the error message
        print("Error:", str(e))

        # Handle any errors that occur during summarization
        bot.reply_to(message, "Oops! Something went wrong.")

# Start the Telegram bot
bot.polling()

Conclusion

Congratulations! You have successfully created a text summarizer using the Cohere API and integrated it with a Telegram bot.

This text summarizer can now generate summaries of input text and reply with the condensed version.

You can find my Colab notebook here.

Here's what mine looks like after summarizing the contents of a pretty detailed Nerdfighter newsletter:

You can tweak this further by customizing the summarization parameters and exploring other features Cohere offers.

Resources

If you'd like to learn more about Large Language Models or how text summarization works, you can check out these resources:

0
Subscribe to my newsletter

Read articles from Gigi Kenneth directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Gigi Kenneth
Gigi Kenneth

I am a machine learning engineer interested in managing social impact products, community building, and understanding AI ethics & policies.