<?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 Dan Beladev on Medium]]></title>
        <description><![CDATA[Stories by Dan Beladev on Medium]]></description>
        <link>https://medium.com/@danbeladev?source=rss-aedd6ce1d649------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JL4mEr39sB1CPkPnbpBqWg.jpeg</url>
            <title>Stories by Dan Beladev on Medium</title>
            <link>https://medium.com/@danbeladev?source=rss-aedd6ce1d649------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:14:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danbeladev/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[Building a Serverless LangChain-Powered Telegram Q&A Bot: A Step-by-Step Guide]]></title>
            <link>https://medium.com/cyberark-engineering/building-a-serverless-langchain-powered-telegram-q-a-bot-a-step-by-step-guide-fcfcdfa35910?source=rss-aedd6ce1d649------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcfcdfa35910</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Dan Beladev]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 15:13:45 GMT</pubDate>
            <atom:updated>2024-02-21T15:13:45.147Z</atom:updated>
            <content:encoded><![CDATA[<h3>How To Build a Serverless LangChain-Powered Telegram Q&amp;A Bot</h3><p>LangChain is a framework for developing applications powered by language models that you can use to create your own LangChain-based Telegram bot<em>.<br></em>I will share some personal insights I have learned from creating my own Telegram bot, along with a template for creating a Serverless application using AWS CDK and LangChain. You can use the template in its entirety or in parts. We will also introduce a private Telegram channel that you can use to ask questions and receive answers from an AI model customized to suit your needs.</p><h4><strong>Create a Serverless Application Using AWS CDK as IaC</strong></h4><p>For this purposes of this post, we focus on implementing a Serverless application using AWS CDK as infrastructure as code (IaC), rather than the design or handling of all security issues.</p><figure><img alt="An flow diagram and architecture" src="https://cdn-images-1.medium.com/max/781/1*H2HBoFdlW6VBSi-Nmn2lAg.png" /></figure><p>Before we get started on this, however, you’ll need:</p><ul><li>An <a href="https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html">AWS account</a></li><li><a href="https://docs.aws.amazon.com/cdk/v2/guide/cli.html">The AWS CDK</a> Toolkit (for this post, I used version 2.118.0)</li><li><a href="https://www.python.org/downloads/">Python 3.11 or above</a></li><li>An <a href="https://platform.openai.com/api-keys">OpenAI API key</a></li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html">Configure AWS account with credentials</a></li><li><a href="https://sendpulse.com/knowledge-base/chatbot/telegram/create-telegram-chatbot">Create a Telegram bot</a> and save the token and chat id for later use of the API</li></ul><p>To investigate the Chat ID, you can use your token to <a href="https://api.telegram.org/bot&lt;API-access-token&gt;/getUpdates?offset=0">get Telegram updates</a>.</p><p>Send a text message of your choice to your bot in the Telegram application. After one message in you chat history, you’ll receive your chat ID</p><p>Then, refresh your browser.<br>Identify the numerical chat ID by finding the ID inside the chat JSON object. In the example below, the chat ID is “123456789”</p><pre>{<br>    &quot;ok&quot;: true,<br>    &quot;result&quot;: [<br>        {<br>            &quot;update_id&quot;: 123456789,<br>            &quot;message&quot;: {<br>                &quot;message_id&quot;: 1,<br>                &quot;from&quot;: {<br>         ....<br>                },<br>                &quot;chat&quot;: {<br>                    &quot;id&quot;: 123456789,<br>          ....<br>                },<br>       ....<br>            }<br>        }<br>    ]<br>}</pre><h3>Let’s Get Started</h3><p>Here’s how to get started creating your own generative AI bot:</p><ul><li>Check out the template code from the following<a href="https://github.com/DanBeladev/GenAIServerless"> Sample GitHub repository</a>.</li><li>Create an <strong>.env</strong> file in the root directory of your project with the secrets you created earlier.</li></ul><p>This file should contain the following variables:</p><p><strong>OPENAI_API_KEY</strong>: Your OpenAI API key.</p><p><strong>TELEGRAM_BOT_TOKEN</strong>: Your Telegram bot token.</p><p><strong>TELEGRAM_CHAT_ID</strong>: The chat ID of your Telegram channel.</p><ul><li>Please note that the <strong>.env</strong> file should not be committed to your version control system, as it contains sensitive information.</li></ul><h3>Diving into the CDK Code</h3><p>In the following “GenaiServerlessStack” stack, we instantiate two Lambda functions: one dedicated to managing client questions and another responsible for configuring the Telegram webhook.</p><p>We then complete the following steps:</p><ol><li>Establish a Telegram webhook to facilitate the transmission of messages from the Telegram client to our Lambda function URL using a custom resource.</li><li>Generate a role endowed with invoke permissions tailored for the custom resource.</li><li>Construct a Layer encompassing essential dependencies and integrate it seamlessly with the Lambda functions.</li></ol><pre># genai_serverless_stack.py<br><br>import json<br>import os<br>from aws_cdk import (<br>    Stack,<br>    aws_lambda as _lambda,<br>    Duration, custom_resources as cr, aws_iam as iam<br>)<br><br>from constructs import Construct<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br><br>class GenaiServerlessStack(Stack):<br><br>    def __init__(self, scope: Construct, construct_id: str, **kwargs) -&gt; None:<br>        super().__init__(scope, construct_id, **kwargs)<br>        self.layer = _lambda.LayerVersion(<br>            self, &#39;MyLambdaLayer&#39;,<br>            compatible_runtimes=[_lambda.Runtime.PYTHON_3_11],<br>            code=_lambda.Code.from_asset(&#39;genai_serverless/layer&#39;),<br>            description=&#39;LLM Layer includes libs for using llm logic&#39;<br>        )<br><br>        # Define Lambda function for handling chat<br>        self.chat_handler = self.create_lambda_function(<br>            &#39;MyLambdaFunction&#39;,<br>            &#39;lambda_handler.handler&#39;,<br>            [&#39;OPENAI_API_KEY&#39;, &#39;TELEGRAM_TOKEN&#39;, &#39;TELEGRAM_CHAT_ID&#39;],<br>            Duration.minutes(3)<br>        )<br>        fn_url = self.chat_handler.add_function_url(https://medium.com/auth_type=_lambda.FunctionUrlAuthType.NONE)<br><br>        # Define Lambda function for setting the Telegram webhook<br>        self.set_webhook_function = self.create_lambda_function(<br>            &#39;SetWebhookFunction&#39;,<br>            &#39;set_telegram_webhook.handler&#39;,<br>            [&#39;TELEGRAM_TOKEN&#39;],<br>            Duration.seconds(30)<br>        )<br><br>        # Create IAM role for Lambda function<br>        role = self.create_lambda_role(self.set_webhook_function)<br><br>        # Add the custom resource<br>        cr.AwsCustomResource(<br>            self, &#39;SetWebhook&#39;,<br>            on_create={<br>                &#39;service&#39;: &#39;Lambda&#39;,<br>                &#39;action&#39;: &#39;invoke&#39;,<br>                &#39;parameters&#39;: {<br>                    &#39;FunctionName&#39;: self.set_webhook_function.function_name,<br>                    &#39;Payload&#39;: json.dumps({<br>                        &#39;ResourceProperties&#39;: {<br>                            &#39;FunctionUrl&#39;: fn_url.url<br>                        }<br>                    })<br>                },<br>                &#39;physical_resource_id&#39;: cr.PhysicalResourceId.of(&#39;SetWebhook&#39;)<br>            },<br>            policy=cr.AwsCustomResourcePolicy.from_sdk_calls(resources=cr.AwsCustomResourcePolicy.ANY_RESOURCE),<br>            role=role<br>        )<br><br>    def create_lambda_function(self, function_id, handler, environment_variables, timeout):<br>        return _lambda.Function(<br>            self,<br>            function_id,<br>            runtime=_lambda.Runtime.PYTHON_3_11,<br>            handler=handler,<br>            code=_lambda.Code.from_asset(&#39;genai_serverless/lambda&#39;),<br>            environment={env: os.environ.get(env) for env in environment_variables},<br>            timeout=timeout,<br>            layers=[self.layer]<br>        )<br><br>    def create_lambda_role(self, lambda_function):<br>        role = iam.Role(<br>            self,<br>            &#39;CustomResourceRole&#39;,<br>            assumed_by=iam.ServicePrincipal(&#39;lambda.amazonaws.com&#39;)<br>        )<br>        role.add_to_policy(<br>            iam.PolicyStatement(<br>                actions=[&#39;lambda:InvokeFunction&#39;],<br>                resources=[lambda_function.function_arn]<br>            )<br>        )<br>        return role</pre><h3>Using Lambda Layer</h3><p>AWS Lambda enforces a strict 50 MB deployment limit for zipped packages. This constraint includes both your function code and its dependencies (e.g., libraries, frameworks, etc). Exceeding this limit leads to deployment issues. Lambda Layers allow you to separate your core function logic from dependencies. By creating a Lambda Layer, you keep your function code lightweight while moving larger dependencies (such as AI frameworks like LangChain) into the layer. Lambda Layers provide up to 250 MB of storage space, making it an ideal solution for managing substantial dependencies.</p><p>With Lambda Layers, your core function code remains small, and only necessary dependencies load at runtime. It also enables dependency reuse across multiple Lambda functions within the same AWS account.</p><h3>Implementing Lambda Functions Code</h3><p>Our Lambda Function handler catches the webhook event and extracts the question from the schema. It is important to note that we are saving the memory conversation in the Lambda context while the Lambda is running to make the conversation with the chatbot more engaging and to maintain a history of the conversation. Each Lambda works with only one channel to avoid confusion between conversations. Finally, the Lambda asks the LLM about the question and responds to the user by sending a message to the Telegram channel using the Telegram API.</p><pre># lambda_handler.py<br><br>import json<br>import os<br>from urllib import parse<br><br>import requests<br>from langchain_openai.llms import OpenAI<br>from langchain.prompts import PromptTemplate<br>from langchain.chains import LLMChain<br>from langchain.memory import ConversationBufferMemory<br><br>memory = ConversationBufferMemory(memory_key=&quot;chat_history&quot;)<br><br><br>def extract_message(event: dict) -&gt; str:<br>    body = json.loads(event[&#39;body&#39;])<br>    return body.get(&quot;message&quot;, {}).get(&quot;text&quot;, &quot;&quot;)<br><br><br>def invoke_model(question: str) -&gt; str:<br>    &quot;&quot;&quot;Invokes the language model.&quot;&quot;&quot;<br>    llm = OpenAI(temperature=0)<br>    template = &quot;&quot;&quot;You are a nice chatbot having a conversation with a human.<br><br>    Previous conversation:<br>    {chat_history}<br><br>    New human question: {question}<br>    Response:&quot;&quot;&quot;<br>    prompt = PromptTemplate.from_template(template)<br>    conversation = LLMChain(<br>        llm=llm,<br>        prompt=prompt,<br>        verbose=True,<br>        memory=memory<br>    )<br>    model_response = conversation({&quot;question&quot;: question})<br>    return model_response[&quot;text&quot;]<br><br><br>def create_response(message: str) -&gt; dict:<br>    &quot;&quot;&quot;Creates HTTP response object.&quot;&quot;&quot;<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps({&#39;message&#39;: message})<br>    }<br><br><br>def send_telegram_message(message: str) -&gt; None:<br>    &quot;&quot;&quot;Sends message to Telegram.&quot;&quot;&quot;<br>    print(f&#39;sending message to Telegram: {message}&#39;)<br>    token = os.environ.get(&quot;TELEGRAM_TOKEN&quot;)<br>    chat_id = os.environ.get(&quot;TELEGRAM_CHAT_ID&quot;)<br>    # Split the response into chunks of 4096 characters<br>    message_chunks = [message[i:i + 4096] for i in range(0, len(message), 4096)]<br>    for chunk in message_chunks:<br>        if chunk.strip():<br>            encoded_chunk = parse.quote_plus(chunk)<br>            print(f&#39;encoded chunk: {encoded_chunk}&#39;)<br>            api_url = f&#39;https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&gt;&amp;text={encoded_chunk}&#39;<br>            print(f&#39;api =&gt; {api_url}&#39;)<br>            send_message_response = requests.post(api_url)<br>            print(f&#39;send_message_response: {send_message_response.text}&#39;)<br><br><br>def handler(event, context):<br>    try:<br>        message: str = extract_message(event)<br>        model_response: str = invoke_model(message)<br>        send_telegram_message(model_response)<br>        response: dict = create_response(model_response)<br>        return response<br>    except Exception as e:<br>        error_message = str(e)<br>        print(f&quot;Error: {error_message}&quot;)<br>        send_telegram_message(error_message)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: json.dumps({&#39;message&#39;: error_message})<br>        }</pre><pre># set_telegram_webhook.py<br><br>import os<br>import requests<br><br><br>def handler(event, context):<br>    try:<br>        function_url = event[&#39;ResourceProperties&#39;][&#39;FunctionUrl&#39;]<br>        telegram_token = os.environ.get(&quot;TELEGRAM_TOKEN&quot;)<br>        response = requests.get(f&#39;https://api.telegram.org/bot{telegram_token}/setWebhook?url={function_url}&#39;)<br>        print(f&quot;response: {response}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: response<br>        }<br>    except Exception as e:<br>        error_message = str(e)<br>        print(f&quot;Error: {error_message}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: error_message<br>        }</pre><h3>Deployment</h3><p>To deploy your stack:</p><ul><li>Create a virtual environment and install the development requirements using the following command:</li></ul><p><strong><em>pip install -r requirements-dev.txt</em></strong></p><ul><li>Configure your AWS credentials and set up the <strong>.env</strong> file with your secrets.</li><li>Run the <strong>deploy.py</strong> file from your project directory:<br>This will install the dependencies required for the layer and deploy your. stack with all the resources.</li><li>After a successful deployment, you can access the stack resources inside the CloudFormation service.</li></ul><figure><img alt="AWS Cloudformation stack resources view" src="https://cdn-images-1.medium.com/max/1024/1*AuAWOSYUdispgewk895b5Q.png" /></figure><figure><img alt="Running “deploy.py” and then run cdk synth and deploy and the resource created." src="https://cdn-images-1.medium.com/max/629/1*OTxnlyASCzVH4tLGRsflVw.png" /></figure><h3>Introducing Our New Digital Friend</h3><p>Your Serverless application bot is now up and running! You can test it out by asking questions in your Telegram channel and receiving answers from the AI model. I hope you found our dive into a GenAI application, using serverless technology in parallel with third-party frameworks such as LangChain, enlightening and that it this has piqued your interest in exploring the creation of your own custom chatbot app.</p><figure><img alt="chat with ai bot in telegram conversation" src="https://cdn-images-1.medium.com/max/600/1*D7g47VzGgTIggy5yaiucYA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcfcdfa35910" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cyberark-engineering/building-a-serverless-langchain-powered-telegram-q-a-bot-a-step-by-step-guide-fcfcdfa35910">Building a Serverless LangChain-Powered Telegram Q&amp;A Bot: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/cyberark-engineering">CyberArk Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>