<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nikitiusivanov on Medium]]></title>
        <description><![CDATA[Stories by Nikitiusivanov on Medium]]></description>
        <link>https://medium.com/@nikitiusivanov?source=rss-5e2a9fed8dbb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_Xxh2r202-zNPzSF</url>
            <title>Stories by Nikitiusivanov on Medium</title>
            <link>https://medium.com/@nikitiusivanov?source=rss-5e2a9fed8dbb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:09:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikitiusivanov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Production ready Multimodal AI Telegram Bot]]></title>
            <link>https://medium.com/@nikitiusivanov/production-ready-multimodal-ai-telegram-bot-666733f25374?source=rss-5e2a9fed8dbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/666733f25374</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Nikitiusivanov]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 22:47:31 GMT</pubDate>
            <atom:updated>2024-11-16T22:47:31.347Z</atom:updated>
            <content:encoded><![CDATA[<p>Telegram bots are a great way of demonstrating your skills to develop things that work with real user’s data and can grow from pet to mvp or even to an independent web app. I really want to share with you a convenient approach to create your own fullstack bots which are, thanks to serverless computing, fast scalable from zero computing power and costs if there isn’t traffic to potentially high load by demand.</p><p>So here is my step by step tutorial of creating a Telegram AI bot which recognizes nutritional info by food photo and helps users collect and track data about their dietary habits. Following I’ll describe main components of the service and then give detailed instructions on creating them from scratch with code and UI screens. Let’s crush it!</p><h3>Components architecture scheme</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q5fUvJXyy0nHs7l2" /></figure><h3>Tech Stack</h3><ul><li>CI/CD: VS Code, Github, Docker, GC Build — for creating simple but convenient and functional automation deployment pipeline.</li><li>Serverless computing for running our bot’s handlers: Google Cloud (GC) Run, with Python web service that realizes asynchronous data processing and API connectors (Aiogram, SQLAlchemy, AIOHTTP).</li><li>Telegram bot API with setted webhook for redirecting users requests to our GC Run instance’s url.</li><li>Database: GC Compute Engine with an PostgreSQL instance</li><li>AI tasks image recognition, content generation: GC Vertex with multimodal LLM Gemini-1.5-pro.</li></ul><h3>Code and Live Demo</h3><p>The complete working code of this Bot you can find here in my Github: <a href="https://github.com/NikitiusIvanov/nutri-bot">https://github.com/NikitiusIvanov/nutri-bot</a> don’t be shy to add some ⭐</p><p>Live demo in: <a href="https://t.me/nutritional_facts_bot">https://t.me/nutritional_facts_bot</a> also feel free to use it and share with your friends, I’ll be happy to support and develop this project further.</p><h3>CI (continuous integration)</h3><p>This part is really the basement of your app, though it might seem boring but it saves you tons of time and after setting it once it makes your developing process and product improvement much more easy, reproducible and scalable. So our minimal program is:</p><ul><li>CI — this part will be basic but it’ll contain all necessary blocks that you can encounter in production:</li><li>Setup local development environment — VS Code with Python virtual environment</li><li>Code’s versioning — Github</li><li>Automated CI tests — we are going to set up Github Actions to perform Lint and Unit tests which will be triggered by pushing code from our local machine into the Github repository.</li><li>CD — this part is responsible for automatically deploying the code after it has been added to the repository and passed the automated tests:</li><li>Containerization — Docker</li><li>Automated deployment — GC Build that automatically triggered after code passing Github action tests and deploy our Python code in Docker container in serverless service GC Run</li></ul><h3>Code versioning and IDE</h3><p>First of all we’ll create a Github repository and connect it with your local repository.</p><p>You’ll need a laptop with your favorite OS (I use Mac but it is quite translatable to Win too).</p><ul><li>Go to Github and create a new repository, choose the repository name, press check “initialize this repository with readme”, scroll down and press “Create repository”. This opens your repository page, go to the address line and copy the url.</li><li>Go to your local machine and create folder for your project</li></ul><p>Download and install:</p><ul><li>Git — instal latest version from official site <a href="https://git-scm.com/downloads">https://git-scm.com/downloads</a></li><li>Python 3.12 <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></li><li>Visual Studio Code <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></li></ul><p>Open VS Code, and do:</p><ul><li>Press “Open” and navigate to your local folder.</li><li>Navigate to extensions and install Pylance.</li><li>Choose Terminal/New Terminal, and write command:</li></ul><pre>git clone &lt;your Github repository_url&gt;</pre><p>This command creates a git folder in your local repository with the name of your Github repo and clones all content.</p><p>Open terminal and create virtual environments that we create by the running in terminal:</p><pre>python3.12 -m venv venv<br>source venv/bin/activate</pre><p>That says python create and activate virtual environment that allows you encapsulate your project’s dependencies, now all libraries that you’ll install will placed in folder venv in your project</p><ul><li>Install Python libraries and save its versions in requirements.txt, in terminal.</li></ul><pre>python3.12 -m pip install - upgrade pip<br>pip install google vertexai numpy aiogram aiohttp sqlalchemy<br>cd &lt;Github repo name&gt; # go to repo folder<br>pip freeze &gt; requirements.txt # save dependencies</pre><p>And don&#39;t forget to create a .gitignore file that prevents you to upload to github extra files, caches, tmps, etc.</p><pre>cat &gt; .gitignore &lt;&lt; EOF<br># macOS specific files<br>.DS_Store<br><br># Python specific files<br>__pycache__/<br>*.py[cod]<br>*$py.class<br>*.pyo<br><br># Virtual environment<br>venv/<br><br># Logs<br>*.log<br><br># IDE specific files<br>.vscode/<br><br># Build artifacts<br>build/<br>dist/<br>*.egg<br>*.pyc<br><br>EOF</pre><ul><li>Choose File/Save all</li><li>Navigate the source control panel and commit your changes with a message into your Github repository, then press “Sync changes”.</li></ul><p>Or use terminal commands:</p><pre>git add .<br>git commit -m &quot;&lt;Your commit message&gt;&quot;<br>git push</pre><p>This will add all new files in the repository, create and push the commit with changes.</p><ul><li>Check that your changes appear in Github</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KPppklJMB4M_Vgdp" /></figure><h3>Auto Lint tests in Github Actions</h3><p>Now we need to create a Python application with minimal echo bot as a baseline for further work. For our bot we will use the Python asynchronous library for working with the Telegram Bot API named AIOGram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1VNkQQPqEtVg7N-g" /></figure><p>So, let’s return to our VS Code terminal and create a main.py file. I want to clarify upfront that we’ll be writing our bot in a monolithic style, using only one module, main.py. This approach is faster for creating an MVP and more readable for small projects. However, as the project grows and more functionality is added, it may eventually require refactoring and splitting into separate modules. In our example, we’ll simply mark the lines where this splitting might be necessary in the future.</p><p>First of all go to the AIOGram docs search for Webhook and grab some quick start examples. We use Webhook here for setting Telegram Bot API server to forward messages from users to our specified url, these messages that come to our address will trigger starting our Cloud Run service thus we don’t pay for the server without traffic on it.</p><p>At start we just take example from official docs <a href="https://docs.aiogram.dev/en/dev-3.x/dispatcher/webhook.html#examples">https://docs.aiogram.dev/en/dev-3.x/dispatcher/webhook.html#examples</a> with minimal changes:</p><ul><li>Change WEB_SERVER_HOST variable from “127.0.0.1” to “0.0.0.0”</li><li>Change getting BASE_WEBHOOK_URL to os.getenv(‘BASE_WEBHOOK_URL’)</li><li>And we don’t use secret token WEBHOOK_SECRET</li></ul><p>So our initial code fit in less than 100 lines:</p><pre>import logging<br>import sys<br>import os<br>from aiohttp import web<br>from aiogram import Bot, Dispatcher, Router<br>from aiogram.client.default import DefaultBotProperties<br>from aiogram.enums import ParseMode<br>from angiogram.filters import CommandStart<br>from angiogram.types import Message<br>from aiogram.utils.markdown import hbold<br>from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application<br><br><br># Bot token can be obtained via https://t.me/BotFather<br>BOT_TOKEN = os.getenv(&quot;BOT_TOKEN&quot;)<br><br># Web Server settings<br># bind localhost only to prevent any external access<br>WEB_SERVER_HOST = &quot;0.0.0.0&quot;<br># Port for incoming request from reverse proxy. Should be any available port<br>WEB_SERVER_PORT = 8080<br><br># Path to webhook route, on which Telegram will send requests<br>WEBHOOK_PATH = &quot;/webhook&quot;<br># Base URL for webhook will be used to generate webhook URL for Telegram,<br># in this example it is used public DNS with HTTPS support<br>BASE_WEBHOOK_URL = os.getenv(&#39;BASE_WEBHOOK_URL&#39;)<br><br><br>def message_lenght(message_text: str | None):<br>   &quot;&quot;&quot;Returns lenght of the recieved message&quot;&quot;&quot;<br>   if message_text is not None:<br>       return len(message_text)<br>   else:<br>       return None<br><br># All handlers should be attached to the Router (or Dispatcher)<br>router = Router()<br><br><br>@router.message(CommandStart())<br>async def command_start_handler(message: Message) -&gt; None:<br>   &quot;&quot;&quot;<br>   This handler receives messages with `/start` command<br>   &quot;&quot;&quot;<br>   await message.answer(f&quot;Hello, {hbold(message.from_user.full_name)}!&quot;)<br><br><br>@router.message()<br>async def echo_handler(message: Message) -&gt; None:<br>   &quot;&quot;&quot;<br>   Handler will forward receive a message back to the sender<br>   By default, message handlers will handle all message types (like text, photo, sticker etc.)<br>   &quot;&quot;&quot;<br>   try:<br>       # Send a copy of the received message<br>       await message.send_copy(chat_id=message.chat.id)<br>   except TypeError:<br>       # But not all the types is supported to be copied so need to handle it<br>       await message.answer(&quot;Nice try!&quot;)<br><br><br>async def on_startup(bot: Bot) -&gt; None:<br>   # If you have a self-signed SSL certificate, then you will need to send a public<br>   # certificate to Telegram<br>   await bot.set_webhook(f&quot;{BASE_WEBHOOK_URL}{WEBHOOK_PATH}&quot;)<br><br><br>def main() -&gt; None:<br>   # Dispatcher is a root router<br>   dp = Dispatcher()<br>   # ... and all other routers should be attached to Dispatcher<br>   dp.include_router(router)<br>   # Register startup hook to initialize webhook<br>   dp.startup.register(on_startup)<br>   # Initialize Bot instance with default bot properties which will be passed to all API calls<br>   bot = Bot(token=BOT_TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))<br>   # Create aiohttp.web.Application instance<br>   app = web.Application()<br>   <br>   # Create an instance of request handler,<br>   # aiogram has few implementations for different cases of usage<br>   # In this example we use SimpleRequestHandler which is designed to handle simple cases<br>   webhook_requests_handler = SimpleRequestHandler(<br>       dispatcher=dp,<br>       bot=bot<br>   )<br>   # Register webhook handler on application<br>   webhook_requests_handler.register(app, path=WEBHOOK_PATH)<br><br>   # Mount dispatcher startup and shutdown hooks to aiohttp application<br>   setup_application(app, dp, bot=bot)<br><br>   # And finally start webserver<br>   web.run_app(app, host=WEB_SERVER_HOST, port=WEB_SERVER_PORT)<br><br><br>if __name__ == &quot;__main__&quot;:<br>   logging.basicConfig(level=logging.INFO, stream=sys.stdout)<br>   main()<br></pre><p>Now we have our bot code and we can add tests. Here we realize two types of tests: Lint with checking the style of the code and Unit tests that will perform automatically when we push code or create merge/pull requests into the main branch of our repository. For perform Lint tests we need go to github page of our repository click Actions and New workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ohU99HWHKtGBOag2" /></figure><p>Then we need to perform a search with a “Python application” query, choose workflow with corresponding name and click Configure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oiq1C8r3Gj_RiJUL" /></figure><p>So this propose to create a new directory .github/workflows and add a new .yml file which contains a configuration of the our workflow, let’s describe and correct a little this code for our understanding so the first level of our .yml contains four blocks:</p><ul><li>name — name of the our workflow let’s change it to Lint and Unit Tests</li><li>on — this block is set up when workflow is triggered, here we have options to push and pull requests in the main branch, let them as is.</li><li>permissions — only read contents, so that’s ok too.</li><li>jobs — here we have a few minor corrections too, change names of the job inside build to “Run tests”, version of the Python — 3.13, and correct the names of the jobs that run flake8 and pytest to “Lint with flake8” and “Test with Pytest”</li><li>In the Lint with flake8 change last line to:</li></ul><pre>flake8 . --count --exit-zero --max-complexity=10 \<br>--statistics --ignore=E501,E302,E303,F841,W292</pre><p>This command will ignore the following errors:</p><ul><li>E501: Line too long</li><li>E302: Expected 2 blank lines, found 1</li><li>E303: Too many blank lines</li><li>F841: Local variable is assigned to but never used</li><li>W292: No newline at end of file</li></ul><p>So the final .yml is:</p><pre># This workflow will install Python dependencies and run lint and pytest tests with a single version of Python<br># For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python<br><br>name: Lint and Unit Tests<br><br>on:<br>  push:<br>    branches: [ &quot;main&quot; ]<br>  pull_request:<br>    branches: [ &quot;main&quot; ]<br><br>permissions:<br>  contents: read<br><br>jobs:<br>  build:<br>    name: Run tests<br>    runs-on: ubuntu-latest<br><br>    steps:<br>    - uses: actions/checkout@v4<br>    - name: Set up Python 3.12<br>      uses: actions/setup-python@v3<br>      with:<br>        python-version: &quot;3.12&quot;<br>    - name: Install dependencies<br>      run: |<br>        python -m pip install --upgrade pip<br>        pip install flake8 pytest<br>        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi<br>    - name: Lint with flake8<br>      run: |<br>        # stop the build if there are Python syntax errors or undefined names<br>        flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics<br>        # exit-zero treats all errors as warnings.<br>        flake8 . --count --exit-zero --max-complexity=10 --statistics --ignore=E501,E302,E303,F841,W292<br>    - name: Test with Pytest<br>      run: |<br>        python -m pytest</pre><p>Unit tests with Pytest</p><p>Now for running this workflow .yml we need to prepare our Unit tests with Pytest. First let’s run</p><p>pip install pytest</p><p>Then we need to bring into line with Pytest requirements our repository structure:</p><ul><li>add to our repository a new folder named tests</li><li>create inside test folder python file with name starts with test</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EXhzEfRmkBCRzeCa" /></figure><p>Now Pytest can find our tests and run it. So let’s write a simple test for our bot’s function which we previously added in code. Remain the function in the main.py:</p><p>def message_lenght(message_text: str | None):</p><p>“””Returns length of the received message</p><p>“””</p><p>if message_text is not None:</p><p>return len(message_text)</p><p>else:</p><p>return None</p><p>It just takes string or None and returns the length of the string or None. So our Unit test of this function may looks like:</p><p>import main</p><p>def test_message_lenght():</p><p>assert main.message_lenght(None) is None</p><p>assert main.message_lenght(‘’) == 0</p><p>assert main.message_lenght(‘a’) == 1</p><p>Here Pytest must import our module main.py then run the function test_message_lenght() and return an error if any of our assertions were false.</p><p>So save all, and git add, commit and push into our Github repo. Now we can see running our workflow after pushing into the main branch, as we set it in our .yml workflow file. If everything is ok you’ll see in the top of your repo’s file list this green check:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vsjh6zF0jNEjYN_E" /></figure><p>Click on it for looking details:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E-dMvQWNgHIuKtZ9" /></figure><p>Here you can see among others, that Pytest collected and successfully performed our test.</p><h3>CD (continuous deployment)</h3><p>Now, when we already have some tests we are ready to deploy our application and it would be great if deployment performs automatically too but after the code passed the testing. So for achieving this we need to write some instructions again and connect our repository with our Google Cloud project.</p><h3>Create a Telegram Bot</h3><p>Open Telegram messenger, search for BotFather and create a new one Bot and copy Bot Token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*TwQQI_UMcX0FwOqP" /></figure><h3>Docker containerization</h3><p>Start from creating a Dockerfile for our python service which gives instructions to Docker how to run our application.</p><pre># Use a slim Python base image<br>FROM python:3.13-slim<br># Set working directory<br>WORKDIR /app<br># Install dependencies<br>COPY requirements.txt /app/requirements.txt<br>RUN pip install - upgrade pip<br>RUN pip install - no-cache-dir -r requirements.txt<br># Copy the application code<br>COPY . /app<br># Expose the port used by the web server<br>EXPOSE 8080<br># Set the command to run the application<br>CMD [&quot;python&quot;, &quot;main.py&quot;]</pre><p>Save changes in files and push them into github as same as previous.</p><h3>Cloud Build setup</h3><p>Lets go to the Google Cloud platform, assume that we already have an account with a payment account. Then we need to create a new project, enter into it and click in the left menu Cloud Run. Then we choose the Deploy Container/Service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DLPy04_ej8l6sVaJ" /></figure><p>After opens creating service page we need to choose continuously deploying from a repository, then press setup with Cloud Build then in the setup press manage connected repositories and pop up the github window in which we need to choose our repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tGC5yhhMP8ngFqMN" /></figure><p>After we need to setup build configuration choose Github repo’s branch and build type, which are: main and Dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hYEncuLd1blqZXlg" /></figure><h3>Cloud Run setup</h3><p>Now we have to set up our Cloud Run service. The important thing here is to set environment variables, so as we use webhook we need to copy the Endpoint URL which we set as BASE_WEBHOOK_URL in our main.py file. All following settings here leave by default, service auto scaling minimum number of instances set to 0 that means if service has no traffic it removes all instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l_L1a40s-TjbhqMw" /></figure><p>Next scroll down to the Container(s), Volumes, Networking, Security part in which we need to set our environments variables:</p><ul><li>BOT_TOKEN — that we created previously.</li><li>BASE_WEBHOOK_URL — endpoint URL copied above.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6d0Q5ELWnGQwhh0X" /></figure><p>Ok, let’s press “Create” and wait when our building and deployment is finished, it takes a few minutes so you can go for some drinks. You can either check every building’s progress in Github and in the GC Run service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hNumudTZ1TQSJ6rv" /></figure><p>Here as you can see deployment performs only after successfully passing tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9t5DfAaBAgsj-YYq" /></figure><p>Now you can go to your new bot’s URL that Botfather gives you and check if it works. Send any message, and because we previously set the webhook, Telegram API service automatically redirects this message to our GC URL, then when GC Run receives the request with a message it automatically starts Docker with our Telegram Bot python code and then our bot will respond to the same message. So the first response may take a few seconds but the following will respond immediately. If you don’t want to wait for the first response you can change a minimal amount of the instances from 0 to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C2XjcuWa8o4C8ekr" /></figure><p>Congratulations now you have your own automatically deployed, serverless, webhooked, Telegram Bot! For now it just answered with echo but really soon it’ll become much more useful 😀.</p><p>So let’s summarize what we done in this part:</p><ul><li>Setted our local workspace for development.</li><li>Setted full functional CI/CD with:</li><li>Github version control</li><li>Github Actions automated testing</li><li>Automated deployment with Docker and GC Build.</li><li>Created a webhook serverless web app using Google Cloud Run that starts the server if someone sends a message in our Telegram Bot and that automatically runs additional instances of the application if users load increasing.</li></ul><p>Part of the app that we already covered is contoured by red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3_cxhenVoJTzt1-s" /></figure><p>Let’s congratulate yourself, we’ve done the hardest part of work, and the most interesting part is ahead! The next parts we realize bot-users interaction logic. Connect our bot to one of the top modern Multimodal LLM — Gemini 1.5 pro. And add to our service a PostgreSQL database for effectively data processing operations.</p><h3>Telegram Bot logic with Aiogram</h3><p>So let’s create some logic diagrams with basic use cases and realize it step by step. Next we imagine two basic functionalities of our Bot, it can recognize nutrition facts by the photo of the food and track user’s statistics about consumed nutrition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PN2lA5sV5w4PLJ9V" /></figure><h3>Settings for local debugging Telegram Bot</h3><p>For fast debugging the logic we’ll use our local machine for running bot, so we need to set BOT_TOKEN in environment variables for it go to terminal activate our virtual environment and set the variable:</p><p>source .venv/bin/activate</p><p>export BOT_TOKEN=&lt;your bot token&gt;</p><p>Then for local debug we need to decline setting the webhook and use long polling instead, this method creates regular requests for updates to Telegram server, so just correct our main.py:</p><ul><li>Set the variable that signalizes is that local debugging or not with</li></ul><pre>export IS_LOCAL_DEBUG=1</pre><ul><li>Set the getting value of this variable, if variable not setted just init it as False</li></ul><pre>logging.basicConfig(level=logging.INFO, stream=sys.stdout)<br>try:<br>  IS_LOCAL_DEBUG = bool(os.getenv(&#39;IS_LOCAL_DEBUG&#39;))<br>except:<br>  IS_LOCAL_DEBUG = False<br>logging.info(f&#39;IS_LOCAL_DEBUG: {IS_LOCAL_DEBUG}&#39;)</pre><ul><li>Create function that removes webhook on local debugging</li></ul><pre>async def on_local_startup(bot: Bot) -&gt; None:<br>  # delete webhook on local debugging<br>  await bot.delete_webhook()</pre><ul><li>Create a local version main() function with bot runner using long polling instead of webhook, long polling technique is based on Bot continuously sending to the Telegram server requests for receiving updates so we don’t need to register any URL and web application as it requires with using webhooks and we can easily work from local machine.</li></ul><pre>async def local_main() -&gt; None:<br>   # Initialize Bot instance<br>   bot = Bot(BOT_TOKEN)<br><br>   # And the run events dispatching<br>   dp = Dispatcher()<br>   dp.include_router(router)<br><br>   # Register on startup function<br>   dp.startup.register(on_local_startup)<br>   await dp.start_polling(bot)<br><br><br>if __name__ == &quot;__main__&quot;:<br>   if IS_LOCAL_DEBUG:<br>       asyncio.run(local_main())<br>   else:<br>       main()</pre><p>Check if it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KxHzInIkpsUy2tyn" /></figure><h3>Create Bot’s Handlers</h3><p>So now we are about to realize our logic scheme that allows our Bot to handle certain interactions with users. For our realization we take aiogram’s instruments:</p><ul><li>Router — can route updates and Bot responses and can filter different types updates that came from Telegram Bot API.</li><li>FSM — Finite State Machine realization that allows Bot to store in cash users data and run corresponding handlers when certain types of users data is updated.</li></ul><p>The great example of the using these instruments showed in official docs <a href="https://docs.aiogram.dev/en/latest/dispatcher/finite_state_machine/index.html">https://docs.aiogram.dev/en/latest/dispatcher/finite_state_machine/index.html</a> In a nutshell it looks like this:</p><pre>from aiogram import Router<br>from aiogram.types import Message<br>from aiogram.fsm.state import State, StatesGroup<br>from aiogram.fsm.context import FSMContext<br><br><br>class Form(StatesGroup):<br>   name = State() <br>   age = State()<br><br><br>form_router = Router()<br><br><br># Triggers by command /start in bot menu<br>@form_router.message(CommandStart())<br>async def welcome(<br>   message: Message,<br>   state: FSMContext<br>):<br>   first_name = message.from_user.first_name<br>   await message.answer(<br>       text=(<br>           f&#39;👋 *Hey, {first_name}! How old are you?&#39;<br>       )<br>   )<br>   await state.set_state(Form.age)<br><br><br># Triggers by next user&#39;s message after state.set_state(Form.name)<br>@form_router.message(Form.age)<br>async def age_handler(<br>   message: Message,<br>   state: FSMContext<br>):<br>   await state.update_data(age=message.text)<br>   await message.answer(<br>       text=(<br>           &#39;Thank You, for the information!&#39;<br>       )<br>   )<br># Then we have stored data about age in our state and <br># also retrieve it witn state.get_data() in all next handlers inside one user interactions</pre><p>Above we have our Router and State automat, when we set a certain state like in example request of the user’s age, next message from user will contain a mark that it comes from state with age request and can be handled by router with filter Form.age. The user’s answer can be stored in FSM storage in dict format by key that we define in our form as State(): state.update_data(age=message.text) and in the next handlers we can just get this data with state.get_data(). Also FSM supports different types of storage including Redis.</p><p><a href="https://docs.aiogram.dev/en/latest/dispatcher/finite_state_machine/storages.html">https://docs.aiogram.dev/en/latest/dispatcher/finite_state_machine/storages.html</a></p><p>For our use cases we need to code following handlers:</p><ul><li>Command Start handler — welcome message.</li><li>Process photo — activates anytime bot receives message with the photo.</li><li>Send a photo to an multimodal LLM model with a prompt that instructs it to recognize nutrition facts.</li><li>Receive response from model and format it.</li><li>Send back to the user formatted results of the nutrition recognition.</li><li>Correct information by user’s demand.</li><li>Save nutrition to db.</li><li>Set a daily goal — saves the user’s desired daily amount of the consumed calories.</li><li>Get statistics — returns today’s statistics about consumed calories in frame of the setted daily goal.</li></ul><p>Here we don’t dive into details of the Aiogram realizations you can find it in this tutorial github repo, next we will take a closer look at the functions that’s related to AI data generation and Database connections.</p><h3>Vertex Gemini-1.5-pro integration</h3><p>Let’s get to the most interesting part — connecting our bot with a modern multimodal LLM. As you can notice in the previous chapter, we have to add the ability to the Bot to receive photos from users and recognize how many calories and grams of the proteins, oil and carbohydrates contains the food in the photos. For achieving this functionality we’ll use google.vertexai library that gives us a comprehensible API for working with most modern (for November 2024) google’s generative model Gemini-1.5-pro-002. Go to your project, find the products VertexAI click on it, and jump to the Model garden/Gemini, so here we need find a quick start guide with Python:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9MQcyHVMEGIW0XZ9" /></figure><h3>Python Gemini API connector</h3><p>So it looks quite easy, let’s integrate it in our bot. We’ll write a handler which, in case we receive a message with a photo, sends it to the Gemini with a prompt for recognizing nutrition. First of all add imports:</p><pre># Google Generative AI imports<br>import io # for processing images<br>import vertexai<br>from vertexai.generative_models import GenerativeModel, Image<br>from aiogram import F # magic filter<br>from aiogram.fsm.context import FSMContext # class for typehinting</pre><p>Then we need initialize our Gemini API connector:</p><pre># Settings for vertexai initialization<br>PROJECT_ID = os.getenv(&#39;PROJECT_ID&#39;)<br>REGION = os.getenv(&#39;REGION&#39;)<br><br><br>vertexai.init(project=PROJECT_ID, location=REGION)<br>generation_config = {<br>   &#39;temperature&#39;: 0,<br>}<br><br><br>model = GenerativeModel(&quot;gemini-1.5-pro-002&quot;)</pre><h3>Prompt engineering</h3><p>Now let’s think about the Prompt for our task, it might looks like this:</p><pre>PROMPT = &quot;&quot;&quot;<br>You are a helpful AI assistant that helps people collect data about their diets<br>by food photos that they send to you.<br>Recognize food in this picture and give your estimation of the:<br>* total amount of calories in kcal,<br>* mass in grams,<br>* fat in grams,<br>* carbohydrates in grams<br><br><br>If you recognize there is no food in the photo<br>write your answer by following format and nothing more:<br><br><br>no food<br><br><br>If you recognize some food on the photo use low-high borders<br>for you estimation of the nutritional facts<br>and write your answer by following format and nothing more:<br><br><br>dish_name: apple pie<br>calories: 230, 240<br>mass: 340, 350<br>fat: 5.0, 5.5<br>carb: 22, 25<br>protein: 24, 25<br>&quot;&quot;&quot;</pre><p>Now we have the prompt which we send to the Gemini with the photo of the food and we assume that it returns as result text with the setted structure which we can use for reproducible downstream processing.</p><h3>Data handlers</h3><p>So let’s write a simple parser from Gemini response to Python dict with keys correspond nutrition options and values correspond average number between Gemini’s high-low estimation:</p><pre>def response_to_dict(<br>   response: str,<br>) -&gt; dict[str, list[float]] | str:<br>   &quot;&quot;&quot;<br>   transform string like<br>   &quot;dish_name: apple pie<br>   calories: 15, 25<br>   mass: 100, 150<br>   fat: 0.3, 0.5<br>   carb: 2, 4<br>   protein: 2, 3&quot;<br>   -&gt; to dict like = {<br>       calories: 20,<br>       mass: 125,<br>       fat: 0.4,<br>       carb: 3,<br>       protein: 2.5,<br>       name: apple pie,<br>   }<br>   &quot;&quot;&quot;<br>   if response.text == &#39;no food&#39;:<br>       return response.text<br>   else:<br>       try:<br>           result = {<br>               row.split(&#39;: &#39;)[0]: np.mean(<br>                   [<br>                       round(float(row.split(&#39;: &#39;)[1].split(&#39;,&#39;)[0]), 2),<br>                       round(float(row.split(&#39;: &#39;)[1].split(&#39;,&#39;)[1]), 2)<br>                   ]<br>               )<br>               for row in response.text.strip(&#39;\n&#39;).split(&#39;\n&#39;)[1:]<br>           }<br>           result[&#39;dish_name&#39;] = (<br>               response.text<br>               .strip(&#39;\n&#39;)<br>               .split(&#39;\n&#39;)[0]<br>               .split(&#39;: &#39;)[1]<br>           )<br>           assert set(<br>               [<br>                   &#39;dish_name&#39;, &#39;calories&#39;, &#39;mass&#39;, &#39;fat&#39;, &#39;carb&#39;, &#39;protein&#39;<br>               ]<br>           ) == set(result.keys())<br>       except:<br>           result = &#39;not correct result&#39;<br>   return result</pre><p>Then we have to write another parser that takes a dict with results and assemble the output text to the user:</p><pre>def text_from_nutrition_facts(<br>   nutrition_facts: dict[str, str|float],<br>   is_saved: bool=False,<br>) -&gt; str:<br>   text = (<br>       &#39;*Here is my estimation of the nutrition facts about your photo:*\n&#39;<br>       f&#39;🍽 Dish name: *{nutrition_facts[&quot;dish_name&quot;]}*\n&#39;<br>       f&#39;🧮 Total calories: *{round(nutrition_facts[&quot;calories&quot;], 2)}* kcal\n&#39;<br>       f&#39;⚖️ Total mass: *{round(nutrition_facts[&quot;mass&quot;], 2)}* g\n&#39;<br>       f&#39;🍖 Proteins mass: *{round(nutrition_facts[&quot;protein&quot;], 2)}* g\n&#39;<br>       f&#39;🍬 Carbohydrates mass: *{round(nutrition_facts[&quot;carb&quot;], 2)}* g\n&#39;<br>       f&#39;🧈 Fats mass: *{round(nutrition_facts[&quot;fat&quot;], 2)}* g&#39;<br>   )<br>   if is_saved == True:<br>       text+=(<br>           &#39;\n✅ Saved to your meals&#39;<br>       )<br>  <br>   return text.replace(&#39;.&#39;, &#39;\.&#39;)</pre><p>So here we are, next we need useful handler that will do:</p><ul><li>Activates anytime when someone sends a message with a photo to our Bot.</li><li>Extracts the photo from the message and sends it to Gemini with the prompt.</li><li>Parses response from Gemini and sends recognized nutrition facts to the user.</li><li>Stores the data in FSMContext data storage for further processing.</li></ul><pre>@router.message(F.photo) # Trigger for the messages with photo<br>async def handle_photo(message: Message, state: FSMContext):<br>   # Send a response to the user<br>   await message.answer(<br>       &quot;⚡️ Thank you for sending the photo! \n&quot;<br>       &quot;⚙️ It in processing, please wait your results&quot;,<br>       reply_markup=build_reply_keyboard()<br>   )<br><br>   await message.bot.send_chat_action(<br>       message.chat.id,<br>       action=ChatAction.TYPING<br>   )<br><br>   # Get the largest available photo size<br>   photo_file_id = message.photo[-1].file_id<br>  <br>   # Download the photo as bytes<br>   bytes = io.BytesIO()<br>   photo_file = await message.bot.download(<br>       photo_file_id,<br>       destination=bytes<br>   )<br><br>   img = Image.from_bytes(photo_file.read())<br><br>   request_parts = [PROMPT, img]<br>  <br>   response = model.generate_content(<br>       request_parts,<br>       generation_config=generation_config<br>   )<br>   result = response_to_dict(response)<br><br>   if result == &#39;no food&#39; or result == &#39;not correct result&#39;:<br>       await message.answer(<br>           text=(<br>               &#39;😔 Sorry I can not recognize food in your photo\n&#39;<br>               &#39;🙏 Please try once again&#39;<br>           ),<br>           parse_mode=ParseMode.MARKDOWN,<br>           reply_markup=build_reply_keyboard()<br>       )<br>   else:<br>       nutrition_facts = result<br><br>       text=text_from_nutrition_facts(nutrition_facts=nutrition_facts)<br>      <br>       await state.update_data(nutrition_facts=nutrition_facts)<br>       await state.update_data(chat_id=message.chat.id)<br>       await state.update_data(username=message.chat.username)<br>       await state.update_data(first_name=message.from_user.first_name)<br>       await state.update_data(last_name=message.from_user.last_name)<br>       await state.update_data(user_id=message.from_user.id)<br>      <br>       await message.answer(<br>           text=text,<br>           parse_mode=ParseMode.MARKDOWN_V2,<br>           reply_markup=build_inline_keyboard(),<br>       )<br><br></pre><h3>PostgreSQL with GC Compute and SQLAlchemy</h3><p>Now we have our Telegram Bot with handlers and connection with a multimodal LLM that allows it to process user requests and generate responses. Now, in the very final of our fullstack Bot journey, we are gonna connect it to our own Database to write and read all necessary data about users and their meals nutrition facts. Database hosting as a rule is expensive but we kinda hack it and start with one of the cheapest options. We’ll just create a Linux virtual machine on GC Compute Engine service, deploy on it PostgreSQL instance, set connections and finally integrate in our Python code SQL requests performers with AlchemySQL lib. Let’s nail it!</p><h4>GC Compute Engine setting</h4><p>Go to the our GC project and look for Compute Engine/VM instances and press on Create instance, so create an instance with the basic CPU/1GB RAM/10GB storage it’ll be enough at the beginning, then when your project will grow you can edit it and add more space and compute power to handle higher loading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*esBy69VbCtx4CKFF" /></figure><p>Go to Boot disk section, press show advanced configuration and choose deletion rule option — keep boot disk for prevention data losing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yfMFPSkEIEaujjwP" /></figure><p>Let’s scroll down to the “On host maintenance” section and change the value to the “Migrate VM instance” option, then go to the “Firewall” and allow HTTP and HTTPS traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ogGeeblBIakl-WzH" /></figure><p>Next we need to open a 5432 port for connecting our Bot with PostgreSQL. For this we need to create a custom rule in our Firewall, first go to the “Networking” section and add the network tag “allow-5432”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kYUeKhngorGqD_i2" /></figure><p>Then open new tab with your GC project search for “Firewall” and press “Create firewall rule”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3NYrytEtlT_GhYA3" /></figure><p>We need to set here:</p><ul><li>corresponded tag-name for matching — allow-5432</li><li>ip mask for allowed addresses — 0.0.0.0/0</li><li>Protocol and port — TCP, 5432</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y3Fj2qAcdFLMgJQp" /></figure><p>Create this firewall rule, and return to the create VM page and press “Create” it too, and after successful creation we’ll see our vm instance with an external ip address that allows TCP traffic through the 5432 port which we’ll use to connect to our Database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jVcLpINt4xBsZ0N1" /></figure><h3>PostgreSQL deploying and setting</h3><p>Click on SSH connect in our instance and auth the connection, then we need to run:</p><pre>sudo apt update # for updating packages<br>sudo apt install postgresql postgresql-contrib -y # to install the postgresql<br>sudo -i -u postgres # to switch to postgres user (default user that creates by installation)<br>psql # to enter in PostgreSQL shell<br>\password postgres # changing password for default user</pre><p>Next create database and grant privileges to our user</p><pre>CREATE DATABASE nutrition_bot;<br>GRANT ALL PRIVILEGES ON DATABASE nutrition_bot TO postgres;<br>\q # exit the postgre shell<br>exit # return to the root user</pre><p>Next we configure our PostgreSQL instance to allow remote connections</p><pre>sudo nano /etc/postgresql/*/main/postgresql.conf # open to edit the configuration file</pre><ul><li>Change value of the “listen_addresses” to ‘*’ then press ctrl+X save and exit</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Ts6LdD9di82zsoD" /></figure><pre># Open another conf file pg_hba.conf file to allow remote access<br>sudo nano /etc/postgresql/*/main/pg_hba.conf</pre><ul><li>Here we need to add new line: host all all 0.0.0.0/0 scram-sha-256</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yaqI5ieP4ft3Hnoj" /></figure><p>Exit, save, restart the PostgreSQL by:</p><pre>sudo systemctl restart postgresql</pre><h3>Database creation</h3><p>Let’s install the latest version of pgAdmin (<a href="https://www.pgadmin.org/download/">https://www.pgadmin.org/download/</a>) that gives us a convenient user interface for our DB administration. First of all go Object/Register/Server and add a new server with the host as external ip of the our vm instance and password that we setted in postgres shell previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3br5gynm-eWh9mMC" /></figure><p>Press save and if all is ok we’ll see the new server with our database inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cDIOwaMxPIA30OGl" /></figure><p>Now we have to design our database which will consist two tables “users” and “meals” with following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*UTn_kKpIp-oXeCWT" /></figure><p>Here we can store data about users as time series. For example, if a user starts with one daily_calories_goal and weight then changes its weight and calories goal, we can track it in our users table, join with meals by user_id and analyze how it changes during time.</p><p>Now we are ready to create tables, go to our pgAdmin, right click by our database, and select Query Tool, that allows us run SQL code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/0*mRYUH04_3BPrZRiY" /></figure><p>In our SQL code for creating a table, we need:</p><ul><li>Set name of the table.</li><li>Set names of the fields.</li><li>Delegate primary keys.</li><li>Set correct data types and rules for creating default values if it is not passed.</li></ul><p>Here is it:</p><pre>CREATE TABLE IF NOT EXISTS users (<br>    id SERIAL PRIMARY KEY, -- Auto-incrementing primary key<br>    timestamp TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Creation timestamp<br>    user_id INTEGER NOT NULL, -- Unique user identifier<br>    user_name TEXT, -- Optional username<br>    first_name TEXT, -- Optional first name<br>    height INTEGER, -- Height in centimeters (assuming)<br>    weight INTEGER, -- Weight in kilograms (assuming)<br>    age INTEGER, -- Age in years<br>    daily_calories_goal INTEGER -- Daily calorie goal in kcal<br>);<br><br>CREATE TABLE IF NOT EXISTS meals (<br>    id SERIAL PRIMARY KEY, -- Auto-incrementing primary key<br>    timestamp TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Meal creation timestamp<br>    user_id INTEGER NOT NULL REFERENCES users(user_id), -- Foreign key linking to users table<br>    dish_name TEXT, -- Name of the dish<br>    photo_file_id TEXT, -- File ID of the photo (for storage system Telegram API or similar)<br>    calories INTEGER, -- Calories in the meal<br>    mass INTEGER, -- Mass of the dish in grams<br>    protein FLOAT, -- Protein content in grams<br>    carb FLOAT, -- Carbohydrate content in grams<br>    fat FLOAT -- Fat content in grams<br>);</pre><p>Press execute script and after running this you can see your tables in Schemas/Public/Tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B4Ty5bdE68uZjDXF" /></figure><h3>Add data handlers with async SQLAlchemy.</h3><p>Here we already have our own database with all needed tables and we are ready to integrate it into our Bot data processing, for it we’ll use Python SQLAlchemy library so add some imports:</p><pre># SQLAlchemy imports<br>from sqlalchemy.ext.asyncio import (<br>   AsyncSession,<br>   async_sessionmaker,<br>   create_async_engine<br>)<br>from sqlalchemy import sql # for parsing textual sql queries</pre><p>At first let’s create asynchronous session for managing interaction with database:</p><pre># get db credentials<br>POSTGRES_USER=os.getenv(&#39;POSTGRES_USER&#39;) # postgres<br>POSTGRES_DB=os.getenv(&#39;POSTGRES_DB&#39;) # nutrition_bot<br>POSTGRES_PASSWORD=os.getenv(&#39;POSTGRES_PASSWORD&#39;) # your_setted_pass<br>POSTGRES_HOST=os.getenv(&#39;POSTGRES_HOST&#39;) # external ip of your CG Compute engine instance<br>POSTGRES_PORT=&#39;5432&#39;<br><br>DB_URL = (<br>   &#39;postgresql+asyncpg://&#39;<br>   f&#39;{POSTGRES_USER}:{POSTGRES_PASSWORD}&#39;<br>   f&#39;@{POSTGRES_HOST}:{POSTGRES_PORT}/{POSTGRES_DB}&#39;<br>)<br><br># Create async engine and session pool<br>engine = create_async_engine(<br>   DB_URL,<br>   pool_size=20<br>)<br><br>session_maker = async_sessionmaker(<br>   bind=engine,<br>   class_=AsyncSession<br>)</pre><p>Now define an async function that will take recognized nutrition and save it in our database.</p><pre>async def sql_write_nutrition(<br>   session: AsyncSession,<br>   meal_row: dict<br>):<br>   await session.execute(<br>       sql.text(&quot;&quot;&quot;<br>       INSERT INTO meals (<br>           user_id,<br>           dish_name,<br>           calories,<br>           mass,<br>           protein,<br>           carb,<br>           fat<br>       ) VALUES (<br>           :user_id,<br>           :dish_name,<br>           :calories,<br>           :mass,<br>           :protein,<br>           :carb,<br>           :fat<br>       )<br>       &quot;&quot;&quot;),<br>       {<br>           &#39;user_id&#39;: meal_row[&#39;user_id&#39;],<br>           &#39;dish_name&#39;: meal_row[&#39;dish_name&#39;],<br>           &#39;calories&#39;: meal_row[&#39;calories&#39;],<br>           &#39;mass&#39;: meal_row[&#39;mass&#39;],<br>           &#39;protein&#39;: meal_row[&#39;protein&#39;],<br>           &#39;carb&#39;: meal_row[&#39;carb&#39;],<br>           &#39;fat&#39;: meal_row[&#39;fat&#39;]<br>       }<br>   )<br><br><br>   await session.commit()<br><br></pre><p>So here we just write classic SQL query with variables that we pass into template with help sql.text which takes:</p><ul><li>a query template marked variables in format</li></ul><pre>:variable_name</pre><ul><li>a dict that must contain mapping this name to value:</li></ul><pre>{variable_name: variable_value}</pre><p>Let’s write down another example with a function that returns today’s meals summary by calories, proteins, carbs and fat.</p><pre>async def sql_get_user_todays_statistics(<br>   session: AsyncSession,<br>   user_id: int,<br>):<br><br><br>   query_todays_nutrition = sql.text(<br>       &quot;&quot;&quot;<br>       SELECT<br>           SUM(calories),<br>           SUM(protein),<br>           SUM(carb),<br>           SUM(fat)<br>       FROM meals<br>       WHERE<br>           timestamp::date = CURRENT_DATE<br>           AND<br>           user_id = :user_id<br>       GROUP BY user_id;<br>       &quot;&quot;&quot;<br>   )<br><br>   todays_nutrition_result = await session.execute(<br>       query_todays_nutrition,<br>       {&#39;user_id&#39;: user_id}<br>   )<br><br>   todays_nutrition = todays_nutrition_result.first()<br><br>   logging.debug(&#39;nutrition query result&#39;, todays_nutrition)<br><br>   await session.close()<br>  <br>   return todays_nutrition<br></pre><p>The same way as described above we’ll need to write functions</p><p>Sql queries for:</p><ul><li>Check if a user exists in our dbase.</li><li>Write user’s data in users table.</li><li>Getting the latest setted daily calories goal to track limit closeness.</li></ul><p>Handlers that process user’s requests with using sql queries:</p><ul><li>Getting today statistics</li><li>Edit user’s data: daily nutrition goal, height, weight, age, sex</li><li>Edit and save nutrition facts into meals table</li></ul><h3>The final code and Live demo</h3><p>So here we are, remind you once again that the complete working code of this Bot you can find in my Github: <a href="https://github.com/NikitiusIvanov/nutri-bot">https://github.com/NikitiusIvanov/nutri-bot</a> don’t be shy to add some ⭐</p><p>Live demo in: <a href="https://t.me/nutritional_facts_bot">https://t.me/nutritional_facts_bot</a> also feel free to use it and share with your friends, I’ll be happy to support and develop this project further.</p><p>If you find this material helpful please:</p><ul><li>Share it with your friends and colleagues.</li><li>Press star on Github.</li><li>Subscribe to me on here and connect in Linkedin</li></ul><p>It really rewards me and motivates me to make more detailed guides like this.</p><p>Thank you for your attention! I wish you successful and fascinating projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666733f25374" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Good news for meatbags: we are still in the game!]]></title>
            <link>https://medium.com/@nikitiusivanov/good-news-for-meatbags-we-are-still-in-the-game-c94e1280f6a6?source=rss-5e2a9fed8dbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c94e1280f6a6</guid>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Nikitiusivanov]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 22:37:02 GMT</pubDate>
            <atom:updated>2023-11-29T23:05:16.858Z</atom:updated>
            <content:encoded><![CDATA[<p>Good news for meatbags: we are still in the game! I have long been convinced that professions that neural networks will replace last are those related to analytics and research. There is nothing surprising in this thought, but it’s amazing how the most powerful language models, such as GPT-4 Turbo, lag behind humans in solving such tasks — tens of times and more! This was vividly demonstrated by the results [1] obtained by scientists from several leading global groups engaged in research and development of artificial intelligence. They worked well and presented a new dataset GAIA [2] with 466 tasks to assess the quality of General AI Assistants. The GPT-4 and agents working based on them were tested on these tasks, and a comparison was made with humans in solving these same tasks.</p><p>The tasks are divided into three levels of difficulty, and to savor the superiority over machines, let’s go through one task from each level in increasing order of difficulty. I’ll leave it up to you to judge the degree of sophistication of the “natural” intelligence required to answer such questions (personally, I had to strain a bit).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMU54_GGNumONwSUDCmUfQ.png" /><figcaption>Scores and time to answer per method and level. As stated in the main text, GPT4 + plugins score should be seen as an oracle since the plugins were chosen manually depending on the question. Human score refers to the score obtained by our annotators when validating the questions.</figcaption></figure><p>The first level of difficulty, a logic question: “You are Van Helsing, a famous vampire hunter, trying to estimate the number of vampires in a village through a sociological survey. It is reliably known to you that among the 100 villagers, there is at least one vampire. You also know that people always tell the truth, and vampires always lie. You asked each villager one question: ‘How many vampires live in the village?’ and each villager answered the same: ‘At least one of us is human.’ Question: how many villagers have turned into vampires?”</p><p>The correct reasoning here would be: if there is already one confirmed vampire in the village, and if we assume that there is at least one non-vampire among the villagers, and if, as we know, the confirmed vampire was surveyed among the villagers, then if he answers that at least one of the villagers is human, he will tell the truth, contradicting the condition that “vampires always lie.” If all the villagers are vampires, then they will all lie in their answers, and the condition will be met. The correct answer: all 100 villagers have turned into vampires.</p><p>Second level difficulty, a question of searching and analyzing information: “Who was the prime minister of the place mentioned first in the new international version of the Book of Esther in April 1977?”</p><p>To answer this question, you need to do the following: first, find the new international version of the Book of Esther (a book from the Old Testament), open the first chapter, and find the first place mentioned in it (this place will be India). Then you will need to find a list of prime ministers of India with the dates of assuming office, and then simply find the surname and name of the person who held this position on the required date. The correct answer: Morarji Desai.</p><p>The third level, a task requiring some additional knowledge of the physical structure of the world, sounds like this: “What volume in ml will 0.312 kg of freon-12 occupy, placed at the bottom of the Mariana Trench at the maximum temperature of the trench?”</p><p>The logic for finding the correct answer here would be: you need to find the formula relating the volume, pressure, and temperature of an ideal gas. This formula will be PV = nRT; express from it the volume V = nRT/P; find the value of the variable n for freon-12 (how many grams per mole of substance); convert the mass of freon into molar mass; look up the pressure and maximum temperature of the Mariana Trench, bring everything to the same units of measurement, and substitute into the formula.</p><p>If you can easily handle answering such questions, congratulations, you are still cooler than the coolest artificial intelligence. However, how long this superiority will last, no one knows. Perhaps in the next release of the model from OpenAI, the situation will change drastically, or maybe not. In any case, it will be very interesting to observe the development of these events!</p><p>Links:</p><ol><li><a href="https://arxiv.org/abs/2311.12983">https://arxiv.org/abs/2311.12983</a></li><li><a href="https://huggingface.co/datasets/gaia-benchmark/GAIA">https://huggingface.co/datasets/gaia-benchmark/GAIA</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c94e1280f6a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Life and death in data]]></title>
            <link>https://medium.com/@nikitiusivanov/life-and-death-in-data-773cd3f78aef?source=rss-5e2a9fed8dbb------2</link>
            <guid isPermaLink="false">https://medium.com/p/773cd3f78aef</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[longevity]]></category>
            <dc:creator><![CDATA[Nikitiusivanov]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 20:03:45 GMT</pubDate>
            <atom:updated>2023-08-06T20:05:34.830Z</atom:updated>
            <content:encoded><![CDATA[<p>I just turned 37 and it looks like it’s time to think about life expectancy and by the way make an analytical interactive dashboard for the portfolio, isn’t it? So I did, I took open data from one of the largest studies of the influence of risk factors on mortality “Global Burden of Disease 2019” [1] and using them calculated an estimate of the increase in life expectancy, subject to the exclusion of controllable risk factors, taking into account the country of age and gender. The key word here is “managed” because I’m convinced that better than looking at numbers can only be looking at numbers that show something that we can influence. Following more about the data processing process, the source code of the dashboard itself in python, and of course, let’s take a closer look at the results, it’s interesting there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*QPyAIwhFOKpTmYQXMnsa-Q.gif" /></figure><h3>Content:</h3><ul><li>Risk factors and format of work</li><li>Looking at graphs with calculation results</li><li>Popularization of population statistics</li><li>Validation of results and meeting with chaos</li><li>Thinking task</li><li>Links and sources</li></ul><h3>Risk factors and format of work</h3><p>So, the following factors were taken:</p><ul><li>Tobacco (smoking, passive smoking, chewing tobacco)</li><li>Alcohol consumption</li><li>drug use</li><li>Low physical activity</li><li>unsafe sex</li><li>Dietary risks (includes 15 different risk factors)</li><li>High systolic blood pressure</li><li>High body mass index</li><li>High LDL cholesterol</li><li>High fasting plasma glucose</li></ul><p>I designed the results with a calculated estimate of the increase in life expectancy with the exclusion of the above factors in the form of an interactive dashboard and posted it in the public domain <a href="https://life-extension-3oyids3kha-uc.a.run.app/">https://life-extension-3oyids3kha-uc.a.run.app</a></p><p>You can follow the link to the dashboard page, select a country, age, mark risk factors and see how many years will be added to life expectancy if the selected risk factors are excluded. You can immediately see how the increase in life expectancy with the selected parameters is distributed by individual risk factors, by country, by gender and by age. I also tried to be able to see something from a mobile phone, but in layout, of course, I have room to grow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xnu-Ra-OfFNzSeqM5nE2Zg.png" /><figcaption>Dashboard web interface on desktop and mobile screen sizes</figcaption></figure><p>Also, the source code and data processing code are publicly available on github [2, 3]. Everything is implemented in python, using the Plotly and Dash libraries, to create interactive dashboards, in my opinion, a very simple and flexible solution. Everything good is packaged in a docker container and deployed using Google Cloud Run — this is the so-called serverless hosting, it allows you to save money by using computing resources only when someone clicks on the link, an ideal solution for services that you do for a small audience or for a portfolio to show to someone on occasion. (by the way, write in the comments if you would like me to make detailed instructions for developing and deploying such an application)</p><h3>Results and Graphs</h3><p>The results turned out to be quite interesting, if you are a middle-aged man living in one of the post-Soviet countries, I have good and bad news for you. The bad news is that your country is likely to lead in male mortality by controllable risk factors, the good news is that the increase in life expectancy when these risk factors are excluded is also one of the highest in the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_aFMRikw9eo-LXgGzlwobQ.png" /><figcaption>Distribution of increase in life expectancy by country for men aged 37 years and distribution by risk factors of increase in life expectancy for Russia</figcaption></figure><p>In general, the estimate of the increase in life expectancy for both men and women varies greatly depending on the country and age, but in the first 40 years of life it does not change much, being in the interval of 5.87 (q05=4.09, q95=8.09) years, but starting from age 40 rapidly begins to fall, declining more than twice to 2.51 by the age of 80, (q05=1.68, q95=3.43), respectively. Which is generally logical because people who have risk factors associated with bad habits and an unhealthy lifestyle to this age live much less. Conclusion, if you are 40 years old — it’s time to “close with a profit” and start living a healthy lifestyle right now, later it may be too late.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VNGdeg00MGjf7V-fG_ajbw.png" /><figcaption>Distribution of increases in life expectancy by age</figcaption></figure><p>Interesting graphs are also obtained if we add to the data the labeling of countries by income level from the World Bank and display each country in coordinates, where the horizontal line will be the current life expectancy at birth, and the vertical line will be the estimated increase in life expectancy with the exclusion of manageable risk factors. Another illustration of the classic “All happy families are alike, and each unhappy family is unhappy in its own way.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*xsCPSttsQm1YC6mPM5RcNg.png" /><figcaption>Life expectancy versus increase in life expectancy at birth for countries color-coded by income level.</figcaption></figure><p>The spread of values ​​in the estimate of the increase in life expectancy is quite small in countries with the highest life expectancy, and vice versa, the lower the life expectancy, the greater the spread along the vertical axis becomes. It is interesting that the highest value of the increase in life expectancy is obtained in lower middle and upper middle income countries, as a rule, these are developing countries, perhaps such high values ​​can be explained by the fact that in these countries people already have the opportunity to lead an unhealthy lifestyle, but there is not yet such a good one. medicine as in the richest and most developed countries.</p><p>On the other end of life expectancy are usually the most laggard countries with weak economies and their estimate of life expectancy increase when managing risk factors are eliminated is even lower than in the richest countries, of course, not because everyone there goes to the gym every day, but rather because that mortality in these countries is more related to factors that each individual can influence rather weakly, something like the lack of hygiene of clean drinking water and basic medical services.</p><p>Let’s also look at the comparison between global average men and women on the contributions of risk factors to estimated life expectancy gains. In general, in both sexes, the main and approximately equal share is occupied by metabolic and nutritional risk factors, but in women there is a much larger contribution from the exclusion of unsafe sex — 7% versus 3.2% for men, and in men, many times larger contributions to the exclusion of alcohol consumption are striking and tobacco — 7.9% vs. 2.1% and 16% vs. 6.4%, respectively. Draw your own conclusions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*7khsZpIm4q9MSVSHH0BnGg.png" /></figure><h3>Data processing and some popular population statistics</h3><p>First, we need an intuition about how the estimate of “life expectancy” is constructed, in fact, this is the average number of years that hypothetical people who are in the same sex and age group will live, assuming that mortality rates remain the same as we observed them on moment of data collection.</p><p>We say, as it were: let’s calculate the ratio of population by age to mortality at these ages for the current year and imagine that these ratios will not change in the future, and then we will model a population of imaginary statistical creatures on which we will conduct a completely inhumane experiment. These statistical people will have to be born all at once in the amount of say 100,000, and then their only task will be to live with the same death rates as in our real world.</p><p>Then we immediately move on to that sad moment when the last representative of our simulated world died and begin our ruthless calculations. We need to calculate for each year of the life of this population how many years those statistical people who survived to this age managed to live.</p><p>For example, simplistically, let’s assume that mortality rates start at 0.01 and increase by 0.01 over 100 years. Thus, if at the age of 0 years we had 100,000 people, then 100,000 will live to age 1 — (100,000 * 0.01) = 99,000, then 99,000 will live to the next age — (99,000 * 0.02) = 97,020 and so on until the age of 101 until which exactly 0 statistical creatures will not survive. the death rate in 100 years will be equal to 1.</p><p>Next, we count how many person-years have been lived in each age group, for example, 1000 people died from 0 to 1 year, which means 99,000 people lived a full year at this age, and out of a thousand of those who were unlucky, we will assume that they died during year evenly and on average then it turns out that they lived at this age for half a year (someone died at the beginning of the year, and someone at the end, we find the average) total 99,000 + 1000 / 2 = 99,500 person-years for age 0. So repeat for each age.</p><p>Now, to calculate life expectancy at any age, we take the selected age group, look at how many people there were at the start, and find the sum of years lived from this age to the very last, and then find the average, that is, divide the sum of years by the number people — we get the average number of years that our imaginary statistical person will live at this age.</p><p>Well, in order to calculate the increase in life expectancy, it is enough to recalculate all of the above items with adjusted mortality rates, from which we removed deaths associated with a risk factor. Here, too, everything is simple, the lower the mortality rate, the more hypothetical people live for more years. Then we subtract the original life expectancy from the result obtained and get an increase.</p><p>That is, the main part of the task is to calculate how much the mortality rate will decrease at each age when the risk factor is excluded. And here there is one difficulty: if you take the mortality rate for each risk factor and add it up, you get a number several times greater than the number of people who died in general, this is because each death can be associated with several factors.</p><p>That is, if we directly subtract the mortality associated with the risk factor, it will turn out that we are saying okay, those people whose death was associated, for example, with smoking and high blood pressure, they would not all die if they excluded smoking, but it seems that this statement is unlikely to be true. To get a more plausible estimate, we can add the deaths for each risk factor, calculate the share of each risk factor in the total, and then take the number of deaths from the All risks factors column, which simply records any death that was associated with one or more risk factors, and calculate the contribution of each risk factor to this number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IaqVJTwUf3M3Lc2P84UQA.png" /><figcaption>Visual representation of the difference between detailed and aggregated mortality statistics by risk factors</figcaption></figure><h3>Validation of results and meeting with chaos</h3><p>To check if the results of my calculations coincide with the life expectancy already calculated by the authors of the study, I took the original data from the site that provides access to the Global Burden of Disease study data <a href="https://vizhub.healthdata.org/gbd-results/">https://vizhub.healthdata.org/gbd-results/</a> Taking the mortality by sex and age for 204 countries, I recalculated life expectancy. When I built a histogram of the distribution of the mean absolute error by country and by gender between the value I calculated and the original value, I was puzzled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cFgKr0s7riOxr_NT.png" /></figure><p>That is, on average, the error is rather small, about 0.07 years, in terms of days, about 25 days. Everything would be fine if it were not for two barely noticeable columns at the values ​​of 1.5 and 2.59 years, it turned out that the height of these columns is equal to units. But when I found out that these columns corresponded to the values ​​​​that I calculated for men and women in the country of Ukraine, I was simply discouraged. Then I looked at the comparison of the calculated and loaded values ​​by age for men in Ukraine and saw the following picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2qDM6DSJ-S1cxbv1KWmO_g.png" /></figure><p>That is, the value calculated using mortality and population turned out to be much lower than that loaded from the same site. And since for all other countries the values ​​are practically the same, it is possible to make the most probable assumption that after calculating the life expectancy for Ukraine, the mortality data were either increased or the population data were reduced. In general, here I sadly realized once again that war is absolute chaos that seeps everywhere.</p><h3>Conclusion</h3><p>In parting, an interesting thought experiment to think about, we know that progress is not just going, but moving with acceleration. Until a couple of years ago, we could not have imagined that GPT chat would appear and that it would be so powerful, and every year new treatments appear that allow people to live longer and feel better. Imagine that in 5 years there will be a way to roll back biological age by 5 years, and over the next 5 years, medicine will learn how to roll back by another 10 years, and so on. Now think how many years of life can be lost before the first life-extending therapy!</p><p>By the way, if you are interested in the topic of life extension, join the community of activists <a href="https://openlongevity.org/">https://openlongevity.org/</a> promoting this direction at all levels from scientific research to attracting investments and preparing public opinion.</p><p>Well, if you liked this article, share it on social networks, subscribe to me here, put a star on the project on <a href="https://github-com.translate.goog/NikitiusIvanov">github</a> or add to <a href="https://www.linkedin.com/in/nikitiusivanov/">linkedin</a> , this will be a good addition to my motivation to make new interesting publications.</p><h3>Links</h3><ol><li>Global Burden of Disease Study <a href="https://www.thelancet.com/journals/lancet/article/PIIS0140-6736(20)30925-9/fulltext">https://www.thelancet.com/journals/lancet/article/PIIS0140-6736(20)30925-9/fulltext</a></li><li>Repository with dashboard code: <a href="https://github.com/NikitiusIvanov/life_extension_dashboard">https://github.com/NikitiusIvanov/life_extension_dashboard</a></li><li>Repository with data processing code and chart debugging: <a href="https://github.com/NikitiusIvanov/life_extension_dashboard_data_processing">https://github.com/NikitiusIvanov/life_extension_dashboard_data_processing</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=773cd3f78aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>