Message Boards Message Boards

TelegramBotAPI v0.2.0: Advanced AI integration with Wolfram language for chatbot development

enter image description here

Telegram Bot API GitHub repository: https://github.com/vasilsaroka/TelegramBotAPI
LinkedIn: https://www.linkedin.com/pulse/telegrambotapi-ai-agents-yet-vasil-saroka-ggn3f/


Intro

In year 2024, artificial intelligence (AI) not only continued to fuel innovation in various fields of economy, healthcare, science and education, but also itself underwent a significant transformation. In brief, we have seen a dramatic going down of prices due to increased energy efficiency and competition at the market and flourishing in features due to introduction of the multi-modal and reasoning models. Yet, according to experts, commercial products and technical infrastructure growing around the base service providers have failed in delivering AI agents as most of us envisaged them. One of the reasons is a lack of sharp focus and specific problem approach. While this conclusion is generally arguable, it definitely contains a grain of truth. In other words, there is a lot of room for improvement and further trials in delivering meaningful AI-based services. In TBpack Ltd., we believe we have managed to provide meaningful assistance with our Telegram chatbots reinforced with AI by being focused on the areas we deal with, i.e. conference management, and problems we solve, i.e. conference agenda compilation and participants navigation. Therefore, we ready to share our tools wrapped as a new release of TelegramBotAPI for Wolfram Language.

Telegram Bot API

In this version tagged v0.2.0, we have expanded the range of the accessible Telegram Bot API functions and updated the previously published functions to the Telegram Bot API 8.2 released on 1 Jan 2025. This package does not contain all possible functions but rather it contains all the functions that we have used in our TBpack Ltd. chatbots.

In order to implement all the function we had to develop a follow certain basic principles of organization, that are useful to know for everyone who has intention to try the package for developing their unique products. Let us begin with reminding that Wolfram Language base principle in naming convention is to give all the built-in symbols explicit linguistic names reflecting their semantics, starting from the capital letter and capitalizing the letter of any new word used in the symbol name. The convention instructs one to call functions with full words, using say "String" instead of "str". This is very powerful and easy to grasp principle that gives Wolfram Language an advantage of clarity, readability and quick start, which later at an expert level can be reinforced by aliases making code concise, though less clear because it is in effect a transition to "str" from "String". In our case, clarity was our main objective, therefore we used "semantic" naming convention as a starting point. However, we noticed that quite often it comes at odds with functions from outside the Wolfram Language without an explicit renaming of them. Keeping in mind coherence and clarity that is to be maintained across several services, we deemed the renaming as not appropriate and dared to amend the Wolfram Language naming conventions in those cases, where we wanted to keep the original "semantics" given to the services by their providers. These tweaks in symbol naming conventions are detailed below.

First of all, to separate TelegramBotAPI functions from built-in Wolfram Language functions we start them from lowercase letters and capitalize the letters of any new word in the name of the function. This allows us to avoid conflicts between such built-in functions as SendMessage and TelegramBotAPI functions as sendMessage.

However, all the options of the TelegramBotAPI functions follow the naming convention of Wolfram Language. We have sticked to this convention because it does not seem to introduce confusion, at least for work of the Wolfram Kernel. For example, the commonly used built-in Text function of Wolfram Language "overlaps" with an option Text of our answerCallbackQuery function. The usage message returned for the Text symbol will contain TelegramBotAPI usage message that overshadows the usage message of the Text function of the Wolfram Language. However, when used as a function, say in

Graphics[{Text["Hello!",{0,0}]}]

the performance of the function is standard for the Wolfram Language. This is because option symbols are free of definitions and protected from assigning to them any values which allows the same symbol to operate independently in two separate universes: a space of functions and a space of options.

Along with Telegram Bot API functions, the TelegramBotAPI package contains some custom functions, which are meant to facilitate bot development. Since these functions do not belong to the official Telegram Bot API, they follow the native Wolfram Language naming convention, e.g. MessageQ[...].

The standard Wolfram Language has two systems storing and retrieving basic information about symbols, i.e. functions, options etc.: Help and Documentation. The Help is represented by built-in tags attached as usage messages to every symbol. These usage messages are usually concise and only suitable for expert to recover some knowledge about this or that function. On the other hand, the Documentation center is a complex and comprehensive system that includes full range of options and supplemented by interactive examples. As such, it is targeting a fast learning of newcomers. The TelegramBotAPI package contains only Help, but we made an effort to make each usage message useful for beginners. This hopefully was achieved by listing of all the options for each of the function and provided url links to the official Telegram Bot API documentation. We believe it is a trade off between a complex Documentation center and limited Help.

Open AI API

The modern bots are unimaginable without large language models (LLMs), though in general bots can operate and perform many useful tasks even without LLMs. Therefore, in this release, we supplemented TelegramBotAPI with a subpackage providing access to the OpenAI API. This subpackage is realized as a separate context "TelegramBotAPIOpenAI" that is loaded together with TelegramBotAPI and must facilitate development of human-like chatbots.

The functions of this subpackage follow naming convention of the TelegramBotAPI package, but all the options are chosen to be provided as strings that follow option names exactly as they are described in official OpenAI API documentation. We hope this will allow one to quickly make a clear relation between options and their usage. For example, chatCompletion[] function of "TelegramBotAPIOpenAI" context has an option "frequency_penalty" that can be set as

chatCompletion[message,model,"frequency_penalty"->1]

.Specifying options as strings means they do not have associated symbols for them and, therefore, no usage message tags. However the usage message of the related function, i.e. chatCompletion, lists all the available options and has a link to the official web page in OpenAI API documentation.

New players on the stage - xAI API

At the moment, the competition between LLMs providers is sky-high. Therefore, it would be bias to advertise one provider such as OpenAI even if it is considered kind of the best on the market. Taking this into account, we extended TelegramBotAPI with xAI API. This is supposed to give developer a freedom of choice between OpenAI and xAI LLMs. xAI API has appeared on the market just recently - 4th November 2024 - and to acquire audience by reverting part of the OpenAI customers to their service, they thoughtfully made the migration to xAI API as hustle-free as possible. Namely, they fully copied the structure and names of the OpenAI API functions so that xAI API could be accessed using an official Python client of OpenAI by changing only the name of requested model and the access end point. Technically, this means that xAI API can be accessed in TelegramBotAPI via "TelegramBotAPIOpenAI" context and chatCompletion function. We, however, decided to put xAI API functions into a separate context "TelegramBotAPIxAI", because, since release of xAI API in November 2024, OpenAI deployed API for their new reasoning models (o1-preview and o1-mini) and, therefore, introduced new options for their API, which are not relevant for xAI API. In order to make difference between chatCompletion functions in the OpenAI and xAI contexts, we supplemented the function name with a postfix "Xai". Thus, the chatCompletion[] function in "TelegramBotAPIxAI" context became chatCompletionXai[]. In principle, context in Wolfram Language are like environments in other programming languages, so they are independent by default but when they are used simultaneously or switch frequently back and force the conflicts may arise. Given this, explicit postfix separation seems to be a handy approach. All options in this context are supposed to follow the same string-type convention as described for "TelegramBotAPIOpenAI" context.

ElevenLabs API

Despite entering a multi-modal era that allows neural networks to work with text, images, video and audio, LLMs are still mostly about text. The specialized single-mode models are much better for professional tasks. In particular, professional text to speech conversion requires variety of voices (male and female ones), intonations, emotional expressions, and sound effects (such as environment and background, accent, speaker age and etc.). That is why we added ElevenLabs API functions, specialized on work with audio, as a subpackage of TelegramBotAPI package. In this subpackage, functions follow the same naming convention as in xAI context. ElevenLabs API function also adopt a postfix "XI". For example, textToSpeechXI[] is the one to be used for converting text to speech using ElevenLabs API. Options in this subpackage are also defined by strings similar to those that can be found on ElevenLabs API documentation.

Package constants

Finally, we shall mention that TelegramBotAPI package feature some symbols that are neither functions not options. They are constants with a usually pre-defined fixed value. An example of such constant can be base url to access Telegram Bot API: https://api.telegram.org/. Such constants follow the naming convention of the Wolfram Language and they all start from $ symbol and have all first letters of each word used in the name of the constant capitalized. Namely, the mentioned based url is stored in the constant $TelegramURL. This convention is used across all subpackages. The base url for the OpenAI API is stored in $OpenAIURL. Similar constants are also used to set API keys for all the functions of the corresponding package or subpackage. For example, by setting

$XaiAPIKey = "your-api-key-here"

one effectively instructs all the functions in the "TelegramBotAPIxAI" context to use this API key. Alternatively, the API key can be provided explicitly via a corresponding option upon every function call:

chatCompletionXai[...,"APIKey"->"your-api-key-here"]

Reinventing the wheel?

Having read the above conventions and subpackage extensions, an experienced user of Wolfram Language may have a valid question why this is all needed if similar connections can be realized via built-in Wolfram Language functions such as LLMSynthesize[] and ImageSynthesize[]. This is indeed true. However, we must notice that all such functions are marked as Experimental and as such do not constitute the standard body of the Wolfram Language yet. This is neither good nor bad and we in fact recommend to use such built-in functions for small not very frequent tasks, when you need to generate an image for yourself or perform a bulky but not repeated task. For other more specialized cases one may find the built-in function performance not satisfactory. This is what happened to us in practice. Thus, the necessity of these new subpackages arose naturally.

Wolfram Language Java Script Notebooks

While Wolfram Language is a licensed product and requires a paywalled graphical user interface Mathematica, a free open-source alternative is available for running Wolfram Engine free of charge. This release includes a special paclet v0.2.1 of TelegramBotAPI that can be used within Wolfram Language Java Script (WLJS) Notebooks run by Electron application. The Electron application Help works in a slightly different manner from that of Wolfram Mathematica. It is realized via autocompletion function that is meant to display short messages with minimal formatting. A string representation of Wolfram Language Boxes used to format fonts and hyperlink are not supported in the Electron application. Hence displaying of TelegramBotAPI usage messages is objectively less aesthetical. We stripped off all the formatting boxes and reduced the lengths of the usage messages to mitigate any displaying issue. Also, we verified that main functions do work as expected when run in a WLJS Notebook. enter image description here
Autocompletion based Help of a WLJS Notebook run by Electron

Final word

With this, we round up this writing and wish you the following.

Put your hands on symbolic programming power combined with AI and show the world innovative meaningful applications!

Many of those must be especially possible with novel models which performance slowly gets recognition by academics or with new usage cases for well known tools.

Quick start tips

Installation guide on GitHub repo: vasilsaroka/TelegramBotAPI: Telegram Bot API for Wolfram Language

How to list all the symbols defined within "TelegramBotAPI`" context:

names = Names["TelegramBotAPI`" ~~ x__ /;Not@StringMatchQ[x, ___ ~~ "Private`" ~~ ___]];

Grid[Table[{i, names[[i]]}, {i, Length[names]}], Background -> {None, {{LightBlue, White}}}, Frame -> All]

Outputs enter image description here
Wolfram Mathematica Notebook

enter image description here
Wolfram Language Java Script Notebook

How to list all the options defined for the given symbol, say for answerCallbackQuery:

Options[answerCallbackQuery]

Installation guide

  • The recommended option in Mathematica 12.1+ PacletInstall["url"] can be used for the installation straight away:
    PacletInstall["https://github.com/vasilsaroka/TelegramBotAPI/releases/download/v<version>/TelegramBotAPI-<version>.paclet"]  

where <version> stands for any existing version of the application. For example,

PacletInstall["https://github.com/vasilsaroka/TelegramBotAPI/releases/download/v0.1.0/TelegramBotAPI-0.1.0.paclet"]
  • An alternative manual intallation option for Mathematica 10.0+ is the following. Download the latest release, distributed as a .paclet file, and install it using the PacletInstall function in Mathematica:

    Needs["PacletManager`"]
    PacletInstall["path2paclet"]
    

Insert path2paclet via Mathematica's Insert → File Path... menu command.

Demo

Basic response loop

  • Evaluate <<TelegramBotAPI` to load the package into the Wolfram Language session.
  • Test TelegramBotAPI using ?getUpdates to invoke help for the given function. Do the same for functions getChatId, getMessageText, sendMessage.
  • Create your own bot and obtain a bot token following BotFather instructions.
  • Set $BotToken constant of TelegramBotAPI` context to the bot token obtained from BotFather in the previous step:

    $BotToken="your bot token here"
    
  • Write "Hi" message to your bot in Telegram.

  • Evaluate the following code to get the update with you "Hi" message in the Wolfram Language session:

    update = Last[getUpdates[]]
    
  • Reply to the "Hi" message from within your Wolfram Language session:

    sendMessage[getChatId[update], "Hi there :) "]
    

Congratulations! You have just implemented the basic bot response loop! Now we can try to run it infinitely long by using available programming loops. ## Running the basic response loop - A simple function for running basic response loop can be defined as follows (N.B. may not work if you have not sent a message to the bot before running it):

    Clear[BotMain];
    BotMain[] := Block[
    {
    update, updateId, chatId, messagetext
    },
    update = Last[getUpdates[Offset->-1]];
    updateId = Lookup[update, "update_id"];
    While[
                  True,
        update = Last[getUpdates[Offset->-1]];
                  If[
                       updateId == Lookup[update, "update_id"],
                       (* new update is available; try to get chat id and message text *)
                       chatId = getChatId[update];
                       messagetext = getMessageText[update];
    (* reply to the message *)
                       Switch[
                                messagetext,
                                "Hi", sendMessage[chatId, "Hi :)"],
                                "Mahal kita", sendMessage[chatId, "Mahal din kita"],
    _, 
    sendMessage[chatId, "Sorry, I do not understand this message :)"]   
                     ](* end Switch *);
                   updateId++ 
                 ](* end If *);
    ](* end While *)
    ](* end Block *)
  • Copy and paste the above function into Wolfram Notebook cell and evaluate it to make the definition of the function known to the current session.

  • Run the above defined function in a separate Notebook cell:

    BotMain[]
    

enter image description here

Congratulations! Now your bot is active and responsive. To terminate the cell evaluation (that is set to run infinitely long!) use Alt+..

More complicated bots including LLMs and functions like SpeechRecognize can be developed with a similar structure in mind. See, for example, our conference virtual secretary Aminat.

WLJS Notebooks - Electron application

The Electron application is an open-source javascript-based cross-platform graphical user interface for running Wolfram Language code via a Wolfram Engine. It is an actively developed project that is getting popularity due to its simplicity and ability to combine Wolfram Language with Javescript and Markdown. While WLJS notebooks are not superior to the original Mathematica notebooks, they do have some features such as gpt-based copilot, powerful command palette system, and enhanced animation capbilitites that may transform them into a useful companion if not a real contender of original notebooks.

We plan to release whenever possible special patches tagged as vX.Y.1, where 'X' and 'Y' are some integers, of TelegramBotAPI that can be installed into the Electron application.
## Installation guide - Install Wolfram Engine (14.0 or higher) - Install Electron application (2.5.6 or higher) - Proceed to an automated installation of TelegramBotAPI:

Copy-paste the below function into a WLSJ notebook cell. Evaluate the cell, for example by pressing Shift+Enter, to make the definition of this function known to the Wolfram Engine. In the next cell, type InstallTelegramBotAPI4Electron[] and evaluate it.

       Options[InstallTelegramBotAPI4Electron]={Method->"Install" (* or "Uninstall" *) };
       InstallTelegramBotAPI4Electron[OptionsPattern[]]:=Block[
       {
          method=OptionValue[Method],
          pacletsrepository, pacletdirectory, message1, message2, jsonreleases, info, pos, url, message, tempfile, 
          version = "v0.2.0" (* TelegramBotAPI version *),
          giturl = "https://api.github.com/repos/vasilsaroka/TelegramBotAPI/releases",
          deletedirectory
       },
       (* auxiliary routine *)
       deletedirectory[dir_,successmessage_,failuremessage_]:=Block[{res},
       If[
             DirectoryQ[dir],
             res = DeleteDirectory[dir,DeleteContents->True];
             If[res===Null, Print[successmessage], Print[failuremessage]]
        ];
        ](* end Block *);
        (* set up directory for the installation *)
        pacletsrepository = FileNameJoin[$InitialDirectory,"wl_packages"];
        pacletdirectory = FileNameJoin[{pacletsrepository,"TelegramBotAPI-"<>StringTake[version,{2,-1}]}];
        (* some general information messages *)
        (* success message *)
        message1 = "TelegramBotAPI has been succefully uninstalled from Electron application.";
        (* failure message *)
        message2 = "Failed to uninstall the existing TelegramBotAPI installation. Probaply due to its current usage by another application.";
        (* select the method *)
        Switch[
                method,
                "Install",
                (* check that an installation folder does not contain TelegramBotAPI version *)
                (* clear the folder from the previously installed TelegramBotAPI version of the same type as is to be installed *)
                deletedirectory[pacletdirectory,message1,message2];       
                (* proceed to the installation/re-installation *)
                jsonreleases = Import[giturl,"JSON"];
                If[
                   jsonreleases === $Failed, 
                   message = "Cannot access GitHub releases: "<>giturl<>". Please, check your internet connection.";
                   Print[message]; Return[$Failed],
                   (* successful access to GitHub releases *)
                   info = "Looking for TelegramBotAPI " <> version;
                   Print[info <> "..."];
                   pos=Position[Lookup[jsonreleases, "tag_name"],version][[1,1]];
                   url=Last@Lookup[Lookup[jsonreleases, "assets"][[pos]],"browser_download_url"];
                   If[
                      $VersionNumber >= 14.0,
                      tempfile = FileNameJoin[{$TemporaryDirectory,FileNameTake[url]}];
                      Check[tempfile = URLDownload[url,tempfile],Return[$Failed]];
                      (* check if the downloaded paclet file still exist on disk and install it *)
                      If[
                         FileExistsQ[tempfile],
                         pacletsrepository=FileNameJoin[$InitialDirectory,"wl_packages"];          
                         Check[ExtractPacletArchive[tempfile,pacletsrepository],Return[$Failed]];
                         DeleteFile[tempfile];
                         message = "TelegramBotAPI is succefully installed into Electron application. It is located at "<>pacletsrepository<>". Now close Electron application and open it again. After this use Needs[''TelegramBotAPI`''], where '' is meant to be \" symbol (double quotation mark, entered without backslash), to activate TelegramBotAPI for the session.";
                         Print[message],
                         message="Installation failed...";
                         Print[message]; Return[$Failed]
                      ],
                      message="It is recommended to use the latest Wolfram Engine that is version 14.0 or higher. Update Wolfram Engine and repeat installation of TelegramBotAPI.";
                      Print[message]; Return[$Failed]
                   ](* end If version *)
                ](* end If GitHub releases*),
                "Uninstall",
                (* clear the folder from the previously installed TelegramBotAPI *)
                deletedirectory[pacletdirectory,message1,message2]; 
        ](* end Switch *)
      ](* end Block *)

  **Note:** After successful installation, you will have to restart Electron application to make TelegramBotAPI visible for ``Needs["TelegramBotAPI`"]``.

 To uninstall the installed TBpack version, evaluate

     InstallTelegramBotAPI4Electron[Mehtod->"Uninstall"]
  • Manual installation of TelegramBotAPI is possible (try only if automated option above has failed):
    • Download .paclet file of the TelegramBotAPI patch released for the Electron application.
    • Extract the paclet file into the installation folder by evaluating in the Electron application cell the following line:

      ExtractPacletArchive["path2paclet",FileNameJoin[$InitialDirectory,"wl_packages"]]
      
    • Restart Electron application to make TelegramBotAPI visible for Needs["TelegramBotAPI`"].

WLJS Notebook Demo

  • Evaluate Needs[TelegramBotAPI`] to load TelegramBotAPI into the Wolfram Engine session run in Electron application.
  • Test TelegramBotAPI trying, for example, ElevenLabs API subpackage function textToSpeechXI: WLJS<em>notebookElevenLabs_zoom
POSTED BY: Vasil Saroka

enter image description here -- you have earned Featured Contributor Badge enter image description here Your exceptional post has been selected for our editorial column Staff Picks http://wolfr.am/StaffPicks and Your Profile is now distinguished by a Featured Contributor Badge and is displayed on the Featured Contributor Board. Thank you!

POSTED BY: EDITORIAL BOARD
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract