<?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 Andre Botta on Medium]]></title>
        <description><![CDATA[Stories by Andre Botta on Medium]]></description>
        <link>https://medium.com/@alcbotta?source=rss-3f3d85e722b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7JXTh-NPDD8QWBzk.jpg</url>
            <title>Stories by Andre Botta on Medium</title>
            <link>https://medium.com/@alcbotta?source=rss-3f3d85e722b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:43:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alcbotta/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[Running an MCP Server and Client locally with Ollama]]></title>
            <link>https://medium.com/@alcbotta/running-an-mcp-server-and-client-locally-with-ollama-b8b4c098c7fb?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8b4c098c7fb</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 07:17:55 GMT</pubDate>
            <atom:updated>2025-08-11T07:20:26.882Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re into AI, you’ve probably heard of MCP, the <strong>Model Context Protocol</strong>. It’s an open standard that lets large language models connect to external tools and data sources in a consistent way, much like USB-C does for hardware devices. An MCP Server is simply an application that speaks this protocol, exposing resources and tools an AI can use.</p><p>When I first looked into MCP, I struggled to see the point. What could I actually <em>do</em> with it? How would it integrate with my own services? Most examples I found stopped short of showing a complete, working setup.</p><p>So in this tutorial, we’ll build an end-to-end example:</p><ol><li>A Spring Boot REST API serving a list of reports.</li><li>An MCP Server that exposes that API to an AI agent.</li><li>An Ollama-powered AI agent running locally, using the MCP Server to query those reports.</li></ol><p>The following diagram shows how each part will interact with each other at the end:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq5KC_nbGdKRZT-DnZbaPw.png" /></figure><p>Everything will run on your local machine, no expensive tools, no external services, so you can understand exactly how the pieces fit together.</p><h3>Spring Boot Application</h3><p>Our REST API is a very simple Spring Boot application. This application simulates a service that holds information about multiple reports. It has a single endpoint: /api/v1/reports; which will return a list of reports. The report object has 3 searchable properties: priority, title and description. For demonstration purposes, we have a set of sample reports with mixed priorities and descriptions, enough to test filtering and pagination later:</p><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;priority&quot;: &quot;High&quot;,<br>        &quot;title&quot;: &quot;Database outage in production&quot;,<br>        &quot;description&quot;: &quot;Critical production database is down, affecting all customer transactions.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;priority&quot;: &quot;Medium&quot;,<br>        &quot;title&quot;: &quot;Scheduled maintenance notice&quot;,<br>        &quot;description&quot;: &quot;Planned system downtime for maintenance to upgrade core services and security patches.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 3,<br>        &quot;priority&quot;: &quot;Low&quot;,<br>        &quot;title&quot;: &quot;Weekly analytics summary&quot;,<br>        &quot;description&quot;: &quot;Summary of weekly performance metrics including traffic, conversions, and user engagement.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 4,<br>        &quot;priority&quot;: &quot;High&quot;,<br>        &quot;title&quot;: &quot;Security vulnerability found&quot;,<br>        &quot;description&quot;: &quot;Urgent patch required to address a security vulnerability in authentication service.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 5,<br>        &quot;priority&quot;: &quot;Medium&quot;,<br>        &quot;title&quot;: &quot;Feature deployment update&quot;,<br>        &quot;description&quot;: &quot;Deployment of the new dashboard feature completed, minor bugs being monitored.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 6,<br>        &quot;priority&quot;: &quot;Low&quot;,<br>        &quot;title&quot;: &quot;Internal training session&quot;,<br>        &quot;description&quot;: &quot;Details of the upcoming staff training session on the updated reporting tool.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 7,<br>        &quot;priority&quot;: &quot;High&quot;,<br>        &quot;title&quot;: &quot;Payment processing delays&quot;,<br>        &quot;description&quot;: &quot;Intermittent payment gateway delays causing occasional transaction timeouts.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 8,<br>        &quot;priority&quot;: &quot;Medium&quot;,<br>        &quot;title&quot;: &quot;API rate limit changes&quot;,<br>        &quot;description&quot;: &quot;API rate limits have been updated to improve service stability and prevent abuse.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 9,<br>        &quot;priority&quot;: &quot;Low&quot;,<br>        &quot;title&quot;: &quot;Office relocation update&quot;,<br>        &quot;description&quot;: &quot;Facilities team confirms move to the new office space will occur next month.&quot;<br>    },<br>    {<br>        &quot;id&quot;: 10,<br>        &quot;priority&quot;: &quot;High&quot;,<br>        &quot;title&quot;: &quot;System performance degradation&quot;,<br>        &quot;description&quot;: &quot;Increased load times reported on key customer-facing applications during peak hours.&quot;<br>    }<br>]</pre><p>If you wanted to see only high-priority reports, you could query:</p><pre>/api/v1/reports?priority=high</pre><p>You could easily script these requests, but in this tutorial we’ll go a step further. We’ll expose the same API through an MCP Server so an AI agent can query it directly.</p><h3>MCP Server</h3><p>Next, we will build an MCP Server that acts as a bridge between our Spring Boot API and the AI agent. It will have one <strong>resource</strong>, which explains how the API works, and one <strong>tool</strong>, which allows the agent to query the API.</p><p>The resource is simply documentation the agent can read to understand what the API does. The tool is an actual callable function that lets the agent request filtered reports and receive the results.</p><p>Below is the main.py file for the MCP Server. It defines the resource, the tool, and the logic to call our API. The server uses httpx to make HTTP requests and formats the results so the AI agent can understand them.</p><pre>import sys<br>import os<br>from typing import Any, Dict, List, Optional<br><br>import httpx<br>from mcp.server import Server<br>import mcp.types as types<br>from mcp.server import stdio<br><br>sys.path.insert (0, os.path.dirname(os.path.abspath(__file__)))<br><br>BASE_URL = os.getenv(&quot;REPORTS_API_BASE_URL&quot;, &quot;http://localhost:8087/api/v1/reports&quot;)<br>TIMEOUT_SECS = float(os.getenv(&quot;REPORTS_API_TIMEOUT&quot;, &quot;10&quot;))<br><br>server = Server(&quot;Reports API Server&quot;)<br><br>def _http_client() -&gt; httpx.Client:<br>    return httpx.Client(timeout=TIMEOUT_SECS)<br><br>def _build_params(priority: Optional[str], title: Optional[str], description: Optional[str], page: int, size: int, sort: Optional[str]) -&gt; Dict[str, str]:<br>    params: Dict[str, str] = {}<br>    if priority:<br>        params[&quot;priority&quot;] = priority<br>    if title:<br>        params[&quot;title&quot;] = title<br>    if description:<br>        params[&quot;description&quot;] = description<br>    params[&quot;page&quot;] = str(page)<br>    params[&quot;size&quot;] = str(size)<br>    if sort:<br>        params[&quot;sort&quot;] = sort<br>    return params<br><br>def _query_reports_impl(priority: Optional[str] = None, <br>                        title: Optional[str] = None, description: Optional[str] = None, <br>                        page: int = 0, size: int = 20, sort: Optional[str] = None) -&gt; Dict[str, Any]:<br>    url = BASE_URL<br>    params = _build_params(priority, title, description, page, size, sort)<br>    with _http_client() as client:<br>        resp = client.get(url, params=params)<br>        resp.raise_for_status()<br>        data = resp.json()<br>    content = data.get(&quot;content&quot;, [])<br>    items = [{&quot;id&quot;: item.get(&quot;id&quot;), &quot;priority&quot;: item.get(&quot;priority&quot;), &quot;title&quot;: item.get(&quot;title&quot;), &quot;description&quot;: item.get(&quot;description&quot;)} for item in content]<br>    page_summary = {&quot;page&quot;: int(data.get(&quot;number&quot;, 0)), &quot;size&quot;: int(data.get(&quot;size&quot;, len(items))), &quot;total_elements&quot;: int(data.get(&quot;totalElements&quot;, len(items))), &quot;total_pages&quot;: int(data.get(&quot;totalPages&quot;, 1)), &quot;number_of_elements&quot;: int(data.get(&quot;numberOfElements&quot;, len(items))), &quot;first&quot;: bool(data.get(&quot;first&quot;, True)), &quot;last&quot;: bool(data.get(&quot;last&quot;, True))}<br>    return {&quot;items&quot;: items, &quot;page&quot;: page_summary, &quot;raw&quot;: data}<br><br>_QUERY_REPORTS_SCHEMA: Dict[str, Any] = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;priority&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;Filter by priority (contains, case-insensitive).&quot;},<br>        &quot;title&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;Filter by title (contains, case-insensitive).&quot;},<br>        &quot;description&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;Filter by description (contains, case-insensitive).&quot;},<br>        &quot;page&quot;: {&quot;type&quot;: &quot;integer&quot;, &quot;minimum&quot;: 0, &quot;default&quot;: 0},<br>        &quot;size&quot;: {&quot;type&quot;: &quot;integer&quot;, &quot;minimum&quot;: 1, &quot;default&quot;: 20},<br>        &quot;sort&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;Spring sort: field,asc|desc&quot;},<br>    },<br>    &quot;additionalProperties&quot;: False,<br>}<br><br>@server.list_tools()<br>async def list_tools() -&gt; List[types.Tool]:<br>    return [types.Tool(name=&quot;query_reports&quot;, description=&quot;Query the Reports API with QueryDSL-backed filters and pagination.&quot;, inputSchema=_QUERY_REPORTS_SCHEMA)]<br><br>@server.call_tool()<br>async def call_tool(name: str, arguments: Any) -&gt; List[types.TextContent]:<br>    if name != &quot;query_reports&quot;:<br>        raise ValueError (f&quot;Unknown tool: {name}&quot;)<br><br>    args = arguments or {}<br>    result = _query_reports_impl(priority=args.get(&quot;priority&quot;), title=args.get(&quot;title&quot;), <br>                                 description=args.get(&quot;description&quot;), page=int(args.get(&quot;page&quot;, 0)), <br>                                 size=int(args.get(&quot;size&quot;, 20)), sort=args.get(&quot;sort&quot;))<br>    return [types.TextContent (type=&quot;text&quot;, text=str (result))]<br><br><br>@server.list_resources()<br>async def list_resources() -&gt; List[types.Resource]:<br>    return [types.Resource(name=&quot;Reports API Usage&quot;, uri=&quot;reports://usage&quot;, mimeType=&quot;text/markdown&quot;, description=&quot;Usage instructions for Reports API MCP server&quot;)]<br><br>@server.read_resource()<br>async def read_resource(uri: str) -&gt; str:<br>    uri_str = str (uri)<br>    if uri_str == &quot;reports://usage&quot;:<br>        try:<br>            with open (os.path.join (os.path.dirname(__file__), &quot;resources&quot;, &quot;ReportsApiUsage.md&quot;), &quot;r&quot;) as f:<br>                return f.read()<br>        except Exception as e:<br>            raise ValueError (f&quot;Error reading ReportsApiUsage: {str (e)}&quot;)<br>    raise ValueError (f&quot;Unknown resource: {uri}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    import asyncio<br>    async def main() -&gt; None:<br>        async with stdio.stdio_server() as (read_stream, write_stream):<br>            await server.run(read_stream, write_stream, server.create_initialization_options())<br>    asyncio.run(main())</pre><p>With this setup, the MCP Server can both describe and execute queries against our Reports API. Once it is running, any MCP-compatible AI agent will be able to ask questions such as <em>“Show me all high-priority reports sorted by title”</em> and get structured results directly from the backend.</p><p>The resource file is a small Markdown document that explains how to use the query_reports tool. It serves as in-context documentation for the AI agent, so it knows what parameters are available and how to format a request.</p><p>Example (ReportsApiUsage.md):</p><pre># Reports API MCP Server Usage<br><br><br>## Tool: `query_reports`<br>Input JSON (all fields optional unless specified):<br>```<br>{{ &quot;priority&quot;: &quot;high|medium|low&quot;, &quot;title&quot;: &quot;outage&quot;, &quot;description&quot;: null, &quot;page&quot;: 0, &quot;size&quot;: 10, &quot;sort&quot;: &quot;title,desc&quot;}}<br>```<br><br>### Examples<br>- Title contains &quot;outage&quot;:<br>  ```<br>  query_reports {{&quot;title&quot;: &quot;outage&quot;}}<br>  ```<br>- Priority filter + sort:<br>  ```<br>  query_reports {{&quot;priority&quot;: &quot;high&quot;, &quot;sort&quot;: &quot;title,desc&quot;}}<br>  ```<br>- Pagination (page index starts at 0):<br>  ```<br>  query_reports {{&quot;page&quot;: 1, &quot;size&quot;: 5}}<br>  ```<br><br>**Notes**<br>- Your Spring Data QuerydslBinder maps all `String` fields to `containsIgnoreCase`.<br>- Sorting uses Spring Data syntax: `sort=field,asc|desc`.<br>- The tool returns `items`, `page`, and `raw` (full Spring page object).</pre><p>With this file in place, the AI agent will have everything it needs to construct valid queries without guesswork.</p><p><strong>Note</strong>: if you are interested in testing your MCP Server integration with the REST API, you can use the node tool: modelcontextprotocol/inspector to do so, like the following:</p><pre>npx @modelcontextprotocol/inspector uv run main.py</pre><p>To make it easier to integrate the MCP Server with the AI Agent, we will build a docker image, I won’t copy-paste the Dockerfile here since I will share the full code later, but keep in mind that you will need to build the docker image and name it “mcp-server-reports”</p><h3>AI Agent with Ollama</h3><p>Now that our MCP Server is ready, we can connect it to a local AI agent using <a href="https://ollama.ai/">Ollama</a> and <a href="https://github.com/mark3labs/mcphost">MCPHost</a>. This will allow the model to query our Reports API through the MCP Server.</p><p><strong>Step 1 — Install Ollama</strong><br> Download and install Ollama from <a href="https://ollama.ai/">ollama.ai</a>.<br> Pull the Qwen3 model:</p><pre>ollama pull qwen3</pre><p>Qwen3 is a general-purpose language model. It doesn’t know about our API yet — that’s what the MCP Server will provide.</p><p><strong>Step 2 — Install Go</strong><br> Follow the instructions at <a href="https://go.dev/doc/install">go.dev/doc/install</a> to install the latest version of Go.</p><p><strong>Step 3 — Install MCPHost</strong><br> MCPHost is the runtime that will launch our MCP Server and connect it to the AI model. Install it with:</p><pre>go install github.com/mark3labs/mcphost@latest</pre><p>You may need to add &quot;$GOPATH/bin&quot; (often ~/go/bin) to your PATH.</p><p><strong>Step 4 — Create the MCP configuration file</strong><br> Create a file named mcp-servers.config.json with the following content:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;reports&quot;: {<br>      &quot;command&quot;: &quot;docker&quot;,<br>      &quot;args&quot;: [<br>        &quot;run&quot;,<br>        &quot;--rm&quot;,<br>        &quot;-i&quot;,<br>        &quot;--add-host&quot;,<br>        &quot;host.docker.internal:host-gateway&quot;,<br>        &quot;-e&quot;,<br>        &quot;REPORTS_API_BASE_URL=http://host.docker.internal:8087/api/v1/reports&quot;,<br>        &quot;mcp-server-reports&quot;<br>      ]<br>    }<br>  }<br>}</pre><p>This tells MCPHost how to start our Reports MCP Server in Docker.<br> <em>Note:</em> On Linux, you may need the --add-host option above. On Windows and macOS, host.docker.internal usually works without it.</p><p><strong>Step 5 — Run the AI Agent</strong><br> Start the agent with:</p><pre>mcphost -m ollama:qwen3 --config ./mcp-servers.config.json</pre><p>You should see a message showing that the reports MCP Server has loaded successfully:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0aEs8MfVRCyLkkyAKBCJjQ.png" /></figure><p><strong>Step 6 — Ask a question</strong><br> Try asking:</p><pre>how many reports are of high priority and what is their title?</pre><p>Since our dataset is static, the model should respond with the four high-priority reports we defined earlier. The following images show an example response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mTc-UpjUUVBkra2UkKggA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSk7BOOcKI7HozwDUP4Uyg.png" /></figure><p>There you go! You just created an MCP Server that can interact with your API!</p><h3>Final Considerations</h3><p>While there are many things that could be improved, this example has all the parts necessary for you to understand how the pieces connect to each other. You could extend this by adding more tools, connecting to databases, or integrating with external APIs, all still running locally.</p><h3>Source Code</h3><p>All the files used in this article can be found <a href="https://github.com/alcbotta/mcp-report">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8b4c098c7fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating the creation of your own RAG System with Terraform, AWS Kendra and AWS Sagemaker (Part…]]></title>
            <link>https://medium.com/@alcbotta/automating-the-creation-of-your-own-rag-system-with-terraform-aws-kendra-and-aws-sagemaker-part-51171cfd406a?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/51171cfd406a</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 08:12:29 GMT</pubDate>
            <atom:updated>2024-07-08T08:37:22.406Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating the creation of your own RAG System with Terraform, AWS Kendra and AWS Sagemaker (Part Three)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jgU_z6yvcwB3P2nSuSq7Q.png" /></figure><p>We are finally at the third and last part of this series on how to deploy your own RAG system to AWS using terraform. In this article, I will cover how we can deploy a python lambda function that will use <a href="https://python.langchain.com/v0.2/docs/introduction/">langchain</a> library to combine our AWS Kendra Index and our AWS Sagemaker model and allow us to interact with them by asking questions.</p><h4>Python Code</h4><p>Let’s go over the code for our lambda function:</p><pre>import json<br>import boto3<br>import os<br>from langchain.chains import ConversationalRetrievalChain <br>from langchain_community.llms import SagemakerEndpoint<br>from langchain_community.llms.sagemaker_endpoint import LLMContentHandler<br>from langchain_core.prompts import PromptTemplate<br>from langchain_community.retrievers import AmazonKendraRetriever<br>from langchain.schema import Document<br><br>kendra_index_id = os.getenv(&#39;KENDRA_INDEX&#39;)<br>sm_endpoint_name = os.getenv(&#39;LLM_ENDPOINT&#39;)<br><br>def lambda_handler(event, context):<br>    question = event[&#39;question&#39;]<br>    chat_history = [tuple(item) for item in event.get (&#39;chat_history&#39;, [])]<br>    model_parameters = {<br>        &quot;max_new_tokens&quot;: 450, <br>        &quot;return_full_text&quot;: False,<br>        &quot;top_p&quot;: 0.6,<br>        &quot;temperature&quot;: 0.9,<br>        &quot;top_k&quot;: 50,<br>        &quot;stop&quot;: [&quot;&lt;/s&gt;&quot;],<br>        &quot;repetition_penalty&quot;: 1.1,<br>    }<br>    <br>    prompt_template = &quot;&quot;&quot;<br>    Use the following pieces of context to answer the question at the end.<br>    If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br>    Be as detailed as you can.<br><br>    {context}<br><br>    Question: {question}<br><br>    Helpful Answer:<br>    &quot;&quot;&quot;<br>    PROMPT = PromptTemplate(<br>        template=prompt_template, input_variables=[&quot;context&quot;, &quot;question&quot;],<br>    )<br>    condense_qa_template = &quot;&quot;&quot;<br>    Given the following conversation and a follow up question, rephrase the follow up question <br>    to be a standalone question.<br><br>    Chat History:<br>    {chat_history}<br>    Follow Up Input: {question}<br><br>    Standalone question:<br>    &quot;&quot;&quot;<br>    standalone_question_prompt = PromptTemplate.from_template(condense_qa_template)<br>    <br>    kendra_client = boto3.client(&#39;kendra&#39;)<br>    retriever = AmazonKendraRetriever(client=kendra_client, index_id=kendra_index_id, top_k=6)<br>    <br>    class ContentHandler(LLMContentHandler):<br>        content_type = &quot;application/json&quot;<br>        accepts = &quot;application/json&quot;<br><br>        def transform_input(self, prompt: str, model_kwargs: dict) -&gt; bytes:<br>            input_str = json.dumps({&quot;inputs&quot;: prompt, &quot;parameters&quot;: {**model_kwargs}})  <br>            return input_str.encode(&#39;utf-8&#39;)<br>        <br>        def transform_output(self, output: bytes) -&gt; str:<br>            response_json = json.loads(output.read().decode(&quot;utf-8&quot;)) <br>            return response_json[0][&#39;generated_text&#39;]<br><br>    content_handler = ContentHandler()<br>    sagemaker_client = boto3.client(&quot;sagemaker-runtime&quot;)<br>    llm = SagemakerEndpoint(<br>            endpoint_name=sm_endpoint_name,<br>            client=sagemaker_client,<br>            model_kwargs=model_parameters, <br>            content_handler=content_handler,<br>        )<br>    chain = ConversationalRetrievalChain.from_llm(<br>        llm=llm,<br>        retriever=retriever,<br>        condense_question_prompt=standalone_question_prompt,<br>        return_source_documents=True,<br>        combine_docs_chain_kwargs={&quot;prompt&quot;: PROMPT},<br>        verbose=False<br>        )<br>    <br>    result = chain({&quot;question&quot;: question, &quot;chat_history&quot;: chat_history})<br>    def custom_serializer(obj):<br>        if isinstance(obj, Document):<br>            return {<br>                &quot;content&quot;: obj.page_content,<br>                &quot;metadata&quot;: obj.metadata<br>            }<br>        return obj<br><br>    return json.dumps(result, default=custom_serializer)</pre><p>From the code, you can see that we start by defining our Kendra Index ID and Sagemaker Endpoint. Both variables will come from the terraform script when deploying the lambda function. We are expecting to receive a request in the form:</p><pre>  payload = {<br>      &quot;question&quot;: &quot;my question&quot;,<br>      &#39;chat_history&#39;: [(&quot;previous question&quot;, &quot;previous answer&quot;)]<br>  }</pre><p>We then define a few custom parameters for our models. Also, notice how we define a ContentHandler class, that is a necessary step for the SagemakerEndpoint class. For this simple example we do define a custom serializer to be able to return the Documents returned by the Kendra Index.</p><p>This file should be saved under a folder called src in the root of your project folder. For this example, I have named the file: lambda_function.py</p><p>In the same src folder we can define the requirements.txt file as:</p><pre>langchain==0.1.17<br>langchain-community==0.0.36<br>boto3&gt;=1.28.27</pre><h4>Terraform Set Up</h4><p>I am going to skip the backend.tf and provider.tf files since they are the same as <a href="https://medium.com/@alcbotta/automating-the-creation-of-your-own-rag-system-with-terraform-aws-kendra-and-aws-sagemaker-part-5744baf8caee">Part One</a> and <a href="https://medium.com/@alcbotta/automating-the-creation-of-your-own-rag-system-with-terraform-aws-kendra-and-aws-sagemaker-part-4b533b70beb0">Part Two</a>. Our variables.tf file will define the ECR URI, where the docker image containing the python code and its dependencies, and the Kendra Index ID as well as the Sagemaker LLM Endpoint:</p><pre>variable &quot;aws_region&quot; {<br>  type = string<br>}<br><br>variable &quot;IMAGE_ECR_URI&quot;{<br>  type = string<br>}<br><br>variable &quot;KENDRA_INDEX_ID&quot;{<br>  type = string<br>  default = &quot;myindexid&quot;<br>}<br><br>variable &quot;LLM_ENDPOINT&quot;{<br>  type = string<br>  default = &quot;myllmendpoint&quot;<br>}</pre><p>And this is the main.tf . The main point here is of course the lambda_handler where we define the image URI and pass the necessary environment variables that our python code needs. We also define the execution role that our lambda function will assume giving it access to Kendra and Sagemaker.</p><pre><br>resource &quot;aws_lambda_function&quot; &quot;lambda_handler&quot; {<br>  function_name = &quot;MyLambdaFunction&quot;<br>  package_type = &quot;Image&quot;<br>  image_uri    = &quot;${var.IMAGE_ECR_URI}&quot;<br><br>  role = aws_iam_role.lambda_exec_role.arn<br><br>  timeout = 300<br>  memory_size = 1024<br><br>  environment {<br>    variables = {<br>      KENDRA_INDEX = &quot;${var.KENDRA_INDEX_ID}&quot;<br>      LLM_ENDPOINT = &quot;${var.LLM_ENDPOINT}&quot;<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;lambda_exec_role&quot; {<br>  name = &quot;lambda_execution_role&quot;<br><br>  assume_role_policy = &lt;&lt;EOF<br>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Action&quot;: &quot;sts:AssumeRole&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;<br>      },<br>      &quot;Effect&quot;: &quot;Allow&quot;<br>    }<br>  ]<br>}<br>EOF<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;lambda_logging&quot; {<br>  name        = &quot;lambda_logging_policy&quot;<br>  description = &quot;IAM policy for logging from Lambda to CloudWatch&quot;<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;,<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;,<br>        Action = [<br>          &quot;logs:CreateLogGroup&quot;,<br>          &quot;logs:CreateLogStream&quot;,<br>          &quot;logs:PutLogEvents&quot;<br>        ],<br>        Resource = &quot;arn:aws:logs:*:*:*&quot;<br>      }<br>    ]<br>  })<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_logs_attachment&quot; {<br>  role       = aws_iam_role.lambda_exec_role.name<br>  policy_arn = aws_iam_policy.lambda_logging.arn<br>}<br><br><br>resource &quot;aws_iam_policy&quot; &quot;lambda_kendra_policy&quot; {<br>  name        = &quot;lambda_kendra_access&quot;<br>  description = &quot;Allow Lambda to access Kendra&quot;<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;,<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;,<br>        Action = [<br>          &quot;kendra:Query&quot;,<br>          &quot;kendra:BatchPutDocument&quot;,<br>          &quot;kendra:DescribeIndex&quot;,<br>          &quot;kendra:Retrieve&quot;<br>        ],<br>        Resource = &quot;*&quot; <br>      }<br>    ]<br>  })<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;lambda_sagemaker_policy&quot; {<br>  name        = &quot;lambda_sagemaker_access&quot;<br>  description = &quot;Allow Lambda to invoke SageMaker endpoints&quot;<br><br>  policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;,<br>    Statement = [<br>      {<br>        Effect = &quot;Allow&quot;,<br>        Action = [<br>          &quot;sagemaker:InvokeEndpoint&quot;,<br>        ],<br>        Resource = &quot;*&quot; <br>      }<br>    ]<br>  })<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_kendra_attachment&quot; {<br>  role       = aws_iam_role.lambda_exec_role.name<br>  policy_arn = aws_iam_policy.lambda_kendra_policy.arn<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_sagemaker_attachment&quot; {<br>  role       = aws_iam_role.lambda_exec_role.name<br>  policy_arn = aws_iam_policy.lambda_sagemaker_policy.arn<br>}</pre><h4>Gitlab Pipeline</h4><p>Our gitlab pipeline is similar to the previous ones, the stages naming might be slightly different, but we have four main stages related to terraform: prepare, validate, plan and deploy but we are going to use the build stage to build our docker image containing the python code and dependencies for our lambda function:</p><pre>image: registry.gitlab.com/gitlab-org/terraform-images/stable:latest<br><br><br>variables:<br>  STATE_NAME: lambda<br>  TF_ROOT: ${CI_PROJECT_DIR}<br>  TF_ADDRESS: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/terraform/state/${STATE_NAME}_state<br>  TF_VAR_aws_region: ${AWS_DEFAULT_REGION}<br>cache:<br>  key: ${STATE_NAME}_state<br>  paths:<br>    - ${TF_ROOT}/.terraform<br><br><br>before_script:<br>  - cd ${TF_ROOT}<br><br><br>stages:<br>  - prepare<br>  - build<br>  - validate<br>  - plan<br>  - deploy<br><br><br>init:<br>  stage: prepare<br>  script:<br>    - gitlab-terraform init <br><br>build:<br>  image: registry.gitlab.com/gitlab-org/cloud-deploy/aws-base:latest<br>  variables:<br>    DOCKER_DRIVER: overlay2<br>    DOCKER_HOST: tcp://docker:2375<br>    DOCKER_TLS_CERTDIR: &quot;&quot;<br>  stage: build<br>  services:<br>    - name: &lt;private ecr&gt;/docker:dind<br>      alias: docker<br>  before_script: <br>    - export DOCKER_HOST=tcp://docker:2375<br>    - aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID<br>    - aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY<br>    - aws configure set default.region $AWS_DEFAULT_REGION<br>    - cd src<br>  script:<br>    - chmod +x ./build_docker_image.sh<br>    - source ./build_docker_image.sh<br>    - cd ..<br>    - echo $LAMBDA_ECR_URI<br>    - echo $LAMBDA_ECR_URI &gt;&gt; build.env<br>  artifacts:<br>    reports:<br>      dotenv: build.env<br><br><br>validate:<br>  stage: validate<br>  script:<br>    - gitlab-terraform validate<br>  dependencies:<br>    - build<br>  needs:<br>    - job: build<br>      artifacts: true <br><br><br>plan:<br>  stage: plan<br>  variables:<br>    TF_VAR_IMAGE_ECR_URI: $LAMBDA_ECR_URI<br>  script:<br>    - gitlab-terraform plan<br>    - gitlab-terraform plan-json<br>  dependencies:<br>    - validate<br>    - build<br>  needs:<br>    - job: validate<br>    - job: build<br>      artifacts: true <br>  artifacts:<br>    name: plan<br>    paths:<br>      - ${TF_ROOT}/plan.cache<br>    reports:<br>      terraform:  ${TF_ROOT}/plan.json<br><br>apply:<br>  stage: deploy<br>  script:<br>    - gitlab-terraform apply<br>  dependencies:<br>    - plan<br>    - build<br>  when: manual<br><br>destroy:<br>  stage: deploy<br>  script:<br>    - gitlab-terraform destroy<br>  dependencies:<br>    - plan<br>    - build<br>  when: manual</pre><p>Let’s deep dive into the build job. You might have noticed that we have a service called docker for this job. In my case, I have access to a private repo that contains the docker:dind image, so if you want to replicate this example, you might need to adjust the job for your case. We also use a simple bash script to build and push the image to an AWS ECR which in this case is pre-existing, so no need to create it via terraform. This is the bash script that creates and pushed the image:</p><p><strong>build_docker_image.sh</strong></p><pre><br>REQUIREMENTS_FILE=&quot;requirements.txt&quot;<br>LAMBDA_FILE=&quot;lambda_function.py&quot;<br>ECR_REPOSITORY_URI=&quot;repo_uri&quot;<br>IMAGE_NAME=&quot;myimage&quot;<br><br>HASH=$IMAGE_NAME.$(cat $REQUIREMENTS_FILE $LAMBDA_FILE | sha256sum | awk &#39;{ print $1 }&#39;)<br>aws ecr get-login-password --region ap-southeast-2 | docker login --username AWS --password-stdin $ECR_REPOSITORY_URI<br>docker build --platform linux/amd64 -t $ECR_REPOSITORY_URI:$HASH .<br>docker push $ECR_REPOSITORY_URI:$HASH</pre><p>And the <strong>Dockerfile</strong> used is:</p><pre>FROM public.ecr.aws/lambda/python:3.12<br>COPY requirements.txt ${LAMBDA_TASK_ROOT}<br>RUN pip install -r requirements.txt<br>COPY lambda_function.py ${LAMBDA_TASK_ROOT}<br>CMD [ &quot;lambda_function.lambda_handler&quot; ]</pre><p>The expected folder structure is that under the root folder, there is going to be a src folder that contains the files: build_docker_image.sh , Dockerfile , lambda_function.py and requirements.txt</p><p>Upon execution, the build job will create and push a docker image to your AWS ECR and export the image URI allowing the plan and apply jobs to deploy our lambda function.</p><h3>End-to-End Testing</h3><p>Our last step is, with no doubt, to test if everything is working as expected. There are many ways to invoke the lambda function, using the aws cli , using the sdk with the many supported programming or even just invoking the function through the AWS Console. For this example, I will be using the aws sdk for python invoking the function from my machine. Also, for this sample my AWS Kendra Index is using some documents related to Roads and Maritimes rules in Australia.</p><p>We start by defining a helper function that will actually call the lambda function:</p><pre>def invokeLambdaHelper (client, question, chat_history):<br>    payload = {<br>        &quot;question&quot;: question,<br>        &#39;chat_history&#39;: chat_history<br>    }<br>    response = client.invoke(<br>        FunctionName=functionName,<br>        InvocationType=&#39;RequestResponse&#39;,<br>        Payload=json.dumps(payload)<br>    )<br><br>    response_payload = json.loads(response[&#39;Payload&#39;].read())<br>    return json.loads(response_payload)</pre><p>We can now invoke this function like this:</p><pre>  config = botocore.config.Config(connect_timeout=300, read_timeout=300)<br>  session = boto3.Session(profile_name=aws_profile)<br>  client = session.client(&#39;lambda&#39;, config=config)<br>  chat_history = []<br>  question = &quot;what is the minimum age to get a driver license?&quot;<br>  response = invokeLambdaHelper (client, question, chat_history)<br>  print (response [&#39;answer&#39;])</pre><p>I got this reply from my RAG System:</p><blockquote>According to the provided documents, the minimum age to take the Driver Knowledge Test (DKT) is 16 years old. Additionally, the minimum age to take the Driving Test is 17 years old. However, it’s important to note that there might be additional requirements or restrictions depending on individual circumstances. For example, some licenses may require medical clearance or proof of residency.</blockquote><p>And now let’s make use of the history feature, but adding this question-response to our next request:</p><pre>  chat_history.append ((question, response [&#39;answer&#39;]))<br>  question = &quot;does that mean I can&#39;t get a driver license if I am under 16 years old?&quot;<br>  response = invokeLambdaHelper (client, question, chat_history)<br>  print (response [&#39;answer&#39;])</pre><p>Giving me back the following answser:</p><blockquote>No, according to the provided document excerpt, the minimum age to obtain a learner’s licence is 16 years old, but it does not specify whether someone under 16 years old can get a driver’s licence. In fact, the excerpt mentions “be aged 16 or over” as a requirement to get a driver licence. Therefore, it is unlikely that someone under 16 years old can get a driver’s licence.</blockquote><p>And that is it! We are finally done with this series.</p><p>References:</p><p><a href="https://github.com/aws-samples/amazon-kendra-langchain-extensions/blob/main/kendra_retriever_samples/kendra_chat_llama_2.py">https://github.com/aws-samples/amazon-kendra-langchain-extensions/blob/main/kendra_retriever_samples/kendra_chat_llama_2.py</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51171cfd406a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating the creation of your own RAG System with Terraform, AWS Kendra and AWS Sagemaker (Part…]]></title>
            <link>https://medium.com/@alcbotta/automating-the-creation-of-your-own-rag-system-with-terraform-aws-kendra-and-aws-sagemaker-part-4b533b70beb0?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b533b70beb0</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[sagemaker]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 10:09:22 GMT</pubDate>
            <atom:updated>2024-07-08T08:34:46.864Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating the creation of your own RAG System with Terraform, AWS Kendra and AWS Sagemaker (Part Two)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jgU_z6yvcwB3P2nSuSq7Q.png" /></figure><p>So this is Part two of a three parts series that I will walk though how to use AWS Kendra and Sagemaker to deploy a RAG system. You can find <a href="https://medium.com/@alcbotta/automating-the-creation-of-your-own-rag-system-with-terraform-aws-kendra-and-aws-sagemaker-part-5744baf8caee">Part One here</a>.</p><p>On this article, I will be covering how we can can use AWS Sagemaker to deploy a <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct">Llama3 model from Huggingface</a>.</p><p>AWS Sagemaker is a cloud-based machine learning platform that enables developers to create, train, and deploy machine learning models on the cloud. It also supports the deployment of ML models on embedded systems and edge devices [<a href="https://aws.amazon.com/sagemaker/">source</a>].</p><p>Basically, we will leverage Sagemaker capabilities to easily deploy a production ready Large Language Model.</p><h3>AWS Sagemaker Set Up</h3><p>Let’s start with the variables necessary for the terraform scripts:</p><h4>variables.tf</h4><p>Again, we will have a variable to define the aws region that our infrascructure will be deployed to. This time we also define a hf_api_token which is the <a href="https://huggingface.co/docs/hub/en/security-tokens">Access Token</a> from the Huggingface, if you want to follow through, the account associated with the hf_api_token used also needs to have access to the the <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct">Llama 3 Instruct model</a>.</p><pre>variable &quot;aws_region&quot; {<br>  type = string<br>}<br><br>variable &quot;hf_api_token&quot; {<br>  type = string<br>}</pre><h4>provider.tf</h4><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.0&quot;<br>    }<br>  }<br>}</pre><h4>backend.tf</h4><pre>terraform {<br>  backend &quot;http&quot; {<br>  }<br>}</pre><h4>main.tf</h4><pre>resource &quot;aws_sagemaker_model&quot; &quot;hf_model&quot; {<br>  name               = &quot;hfmodel&quot;<br>  execution_role_arn = aws_iam_role.sagemaker_iam_role.arn<br><br>  primary_container {<br>    image = &quot;763104351884.dkr.ecr.ap-southeast-2.amazonaws.com/huggingface-pytorch-tgi-inference:2.1.1-tgi2.0.0-gpu-py310-cu121-ubuntu22.04-v2.0&quot;<br>    environment = {<br>      HF_TASK           = &quot;text-generation&quot;<br>      HF_MODEL_ID       = &quot;meta-llama/Meta-Llama-3-8B-Instruct&quot;<br>      HF_API_TOKEN      = var.hf_api_token<br>    }<br>  }<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;sagemaker_iam_role&quot; {<br>  name = &quot;sagemaker_iam_role&quot;<br>  assume_role_policy = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Action = &quot;sts:AssumeRole&quot;<br>        Effect = &quot;Allow&quot;<br>        Principal = {<br>          Service = &quot;sagemaker.amazonaws.com&quot;<br>        }<br>      },<br>    ]<br>  })<br><br>  inline_policy {<br>    name = &quot;terraform-inferences-policy&quot;<br>    policy = jsonencode({<br>      Version = &quot;2012-10-17&quot;<br>      Statement = [<br>        {<br>          Effect = &quot;Allow&quot;,<br>          Action = [<br>            &quot;cloudwatch:PutMetricData&quot;,<br>            &quot;logs:CreateLogStream&quot;,<br>            &quot;logs:PutLogEvents&quot;,<br>            &quot;logs:CreateLogGroup&quot;,<br>            &quot;logs:DescribeLogStreams&quot;,<br>            &quot;s3:GetObject&quot;,<br>            &quot;s3:PutObject&quot;,<br>            &quot;s3:ListBucket&quot;,<br>            &quot;ecr:GetAuthorizationToken&quot;,<br>            &quot;ecr:BatchCheckLayerAvailability&quot;,<br>            &quot;ecr:GetDownloadUrlForLayer&quot;,<br>            &quot;ecr:BatchGetImage&quot;<br>          ],<br>          Resource = &quot;*&quot;<br>        }<br>      ]<br>    })<br>  }<br>}</pre><p>On our aws_sagemaker_model’s primary container configuration we define the image that will be used to deploy our model. Here, we are using <a href="https://huggingface.co/docs/text-generation-inference/en/index">Huggingface’s Text Generation Inference toolkit</a> which let us deploy production ready Large Language Models. We also define our model, the task (or pipeline) and our personal access token.</p><pre>resource &quot;aws_sagemaker_endpoint_configuration&quot; &quot;huggingface_endpoint_conf&quot; {<br>  name  = &quot;hf-model-endpoint-conf&quot;<br>  production_variants {<br>    variant_name = &quot;AllTraffic&quot;<br>    model_name   = aws_sagemaker_model.hf_model.name<br><br>    initial_instance_count = 1<br>    instance_type          = &quot;ml.g5.2xlarge&quot;<br>  }<br>}<br><br>resource &quot;aws_sagemaker_endpoint&quot; &quot;huggingface&quot; {<br>  name = &quot;myendpoint&quot;<br>  endpoint_config_name = aws_sagemaker_endpoint_configuration.huggingface_endpoint_conf.name<br>}</pre><p>We then create the endpoint for our model. This is the instance that will be used to run our model. We can define the instance type as well as the number of instances necessary.</p><p>And that is it for our model’s terraform configuration.</p><p>So now, as the last step, we will define our .gitlab-ci.yml file that will create our gitlab pipeline:</p><pre>image: registry.gitlab.com/gitlab-org/terraform-images/stable:latest<br><br>variables:<br>  STATE_NAME: sagemaker<br>  TF_ROOT: ${CI_PROJECT_DIR}<br>  TF_ADDRESS: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/terraform/state/${STATE_NAME}_state<br>  TF_VAR_aws_region: ${AWS_DEFAULT_REGION}<br>  TF_VAR_hf_api_token: ${HF_TOKEN}<br><br>cache:<br>  key: ${STATE_NAME}_state<br>  paths:<br>    - ${TF_ROOT}/.terraform<br><br>before_script:<br>  - cd ${TF_ROOT}<br><br>stages:<br>  - prepare<br>  - validate<br>  - build<br>  - deploy<br><br>init:<br>  stage: prepare<br>  script:<br>    - gitlab-terraform init <br><br>validate:<br>  stage: validate<br>  script:<br>    - gitlab-terraform validate<br><br>plan:<br>  stage: build<br>  script:<br>    - gitlab-terraform plan<br>    - gitlab-terraform plan-json<br>  artifacts:<br>    name: plan<br>    paths:<br>      - ${TF_ROOT}/plan.cache<br>    reports:<br>      terraform:  ${TF_ROOT}/plan.json<br><br>apply:<br>  stage: deploy<br>  script:<br>    - gitlab-terraform apply<br>  dependencies:<br>    - plan<br>  when: manual<br><br>destroy:<br>  stage: deploy<br>  script:<br>    - gitlab-terraform destroy<br>  dependencies:<br>    - plan<br>  when: manual</pre><p>Not much to say about, since this is even simpler than the pipeline from Part One. We are simply validating the terraform scripts and then calling apply to create the resources in AWS.</p><p>Once completed, your model should be ready to start making inferences.</p><p>We are almost there now, just one more step to go. In <a href="https://medium.com/@alcbotta/automating-the-creation-of-your-own-rag-system-with-terraform-aws-kendra-and-aws-sagemaker-part-51171cfd406a">Part Three</a> of this series, I will show you how to deploy an AWS lambda function that uses <a href="https://www.langchain.com/">langchain </a>to combine both services, the kendra index and the LLM model, so you can start querying your internal documentation with easy.</p><p>Resources: There are two particular resources that really helped me when setting up this part of the project, so a big thanks to Philipp Schmid:</p><p><a href="https://github.com/philschmid/terraform-aws-sagemaker-huggingface/blob/v0.9.0/main.tf">https://github.com/philschmid/terraform-aws-sagemaker-huggingface/blob/v0.9.0/main.tf</a></p><p><a href="https://www.philschmid.de/sagemaker-llama-llm">https://www.philschmid.de/sagemaker-llama-llm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b533b70beb0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating the creation of your own RAG System with Terraform, AWS Kendra and AWS Sagemaker (Part…]]></title>
            <link>https://medium.com/@alcbotta/automating-the-creation-of-your-own-rag-system-with-terraform-aws-kendra-and-aws-sagemaker-part-5744baf8caee?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5744baf8caee</guid>
            <category><![CDATA[sagemaker]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 07:11:03 GMT</pubDate>
            <atom:updated>2024-07-06T10:09:49.171Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating the creation of your own RAG System with Terraform, AWS Kendra and AWS Sagemaker (Part One)</h3><p>Like most companies, it’s very likely that your company also has lots of internal documentation. Now, with the advent of Generative AI, it has never been easier to search those internal documents. With RAG, Retrieval Augmented Generation, we can build entire chatbots relying on state-of-the-art Large Language Models like Llama3. And using services like AWS Kendra and AWS Sagemaker we can easily deploy these solutions to the cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jgU_z6yvcwB3P2nSuSq7Q.png" /></figure><p>Now, while we could do all these steps manually, I am a big fan of having all of your infrastructure set up as code. Using tools like terraform, we can easily create/modify/destroy our infrastructure as necessary. I will also be using Gitlab and its Managed Terraform State feature to easily integrate my code repository with my terraform state. I will not go into much details regarding these steps, since I already covered similar things in one of my previous articles: <a href="https://medium.com/@alcbotta/using-gitlab-to-manage-multi-environment-terraform-state-554f126e61cf">Using Gitlab to manage Multi Environment Terraform State</a></p><p>I have split the set up for this article into three parts:</p><ul><li>kendra</li><li>sagemaker</li><li>lambda</li></ul><p>So let’s start with Part One.</p><h3>AWS Kendra Set Up</h3><p>From <a href="https://aws.amazon.com/kendra/">AWS</a>:</p><blockquote>Kendra is an intelligent enterprise search service that helps you search across different content repositories with built-in connectors</blockquote><p>So AWS Kendra will be responsible for indexing our internal documents.</p><p>Let’s start the terraform set up</p><h4>backend.tf</h4><pre>terraform {<br>  backend &quot;http&quot; {<br>  }<br>}</pre><p>The configuration of the backend will be done later by the gitlab pipeline.</p><h4>provider.tf</h4><pre>terraform {<br>  required_providers {<br>    aws = {<br>      source  = &quot;hashicorp/aws&quot;<br>      version = &quot;~&gt; 5.56.1&quot;<br>    }<br>    awscc = {<br>      source  = &quot;hashicorp/awscc&quot;<br>      version = &quot;~&gt; 1.4.0&quot;<br>    }<br>  }<br>}</pre><h4>variables.tf</h4><pre>variable &quot;files&quot; {<br>  type = list(string)<br>  default = []<br>}<br><br>variable &quot;aws_region&quot; {<br>  type = string<br>}</pre><p>Also, let’s define two variables: the aws region and a variable called files that will be used later to automatically upload data to S3 (this approach serves only as an example, since AWS Kendra provides multiple <a href="https://docs.aws.amazon.com/kendra/latest/dg/hiw-data-source.html">data sources</a>).</p><h4>main.tf</h4><p>We start by creating a S3 Bucket and uploading some files to it. Again, this serves only as an example, since you might have more complex scenarios with different data sources.</p><pre>resource &quot;aws_s3_bucket&quot; &quot;resources-bucket&quot; {<br>  bucket = &quot;s3-kendra-resources&quot;<br>}<br><br>resource &quot;aws_s3_object&quot; &quot;object&quot; {<br>  for_each = { for f in var.files : f =&gt; f }<br>  bucket = aws_s3_bucket.resources-bucket.id<br>  key      = basename(each.value)<br>  source = each.value<br><br>  etag = filemd5(each.value)<br>}</pre><p>Next, let define the AWS Kendra Index and respective IAM roles and policies:</p><pre>resource &quot;awscc_kendra_index&quot; &quot;kendra_index&quot; {<br>  edition     = &quot;ENTERPRISE_EDITION&quot;<br>  name        = &quot;kendra-index&quot;<br>  role_arn    = awscc_iam_role.kendra_iam_role.arn<br>  description = &quot;Kendra index&quot;<br>}<br><br>resource &quot;awscc_iam_role&quot; &quot;kendra_iam_role&quot; {<br>  role_name   = &quot;kendra_iam_role&quot;<br>  assume_role_policy_document = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Action = &quot;sts:AssumeRole&quot;<br>        Effect = &quot;Allow&quot;<br>        Principal = {<br>          Service = &quot;kendra.amazonaws.com&quot;<br>        }<br>      }<br>    ]<br>  })<br>  max_session_duration = 7200<br>}<br><br>resource &quot;awscc_iam_role_policy&quot; &quot;kendra_iam_role_policy&quot; {<br>  policy_name = &quot;kendra_role_policy&quot;<br>  role_name   = awscc_iam_role.kendra_iam_role.id<br><br>  policy_document = jsonencode({<br>    Version = &quot;2012-10-17&quot;<br>    Statement = [<br>      {<br>        Effect   = &quot;Allow&quot;<br>        Action   = &quot;cloudwatch:PutMetricData&quot;<br>        Resource = &quot;*&quot;<br>        Condition = {<br>          &quot;StringEquals&quot; : {<br>            &quot;cloudwatch:namespace&quot; : &quot;AWS/Kendra&quot;<br>          }<br>        }<br>      },<br>      {<br>        Effect   = &quot;Allow&quot;<br>        Action   = &quot;logs:DescribeLogGroups&quot;<br>        Resource = &quot;*&quot;<br>      },<br>      {<br>        Effect   = &quot;Allow&quot;<br>        Action   = &quot;kendra:BatchDeleteDocument&quot;,<br>        Resource = &quot;${awscc_kendra_index.kendra_index.arn}&quot;<br>      },<br>      {<br>        Effect   = &quot;Allow&quot;<br>        Action   = &quot;logs:CreateLogGroup&quot;,<br>        Resource = &quot;arn:aws:logs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*&quot;<br>      },<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [<br>          &quot;logs:DescribeLogStreams&quot;,<br>          &quot;logs:CreateLogStream&quot;,<br>          &quot;logs:PutLogEvents&quot;<br>        ],<br>        Resource = &quot;arn:aws:logs:${var.aws_region}:${data.aws_caller_identity.current.account_id}:log-group:/aws/kendra/*:log-stream:*&quot;<br>      },<br>      {<br>        Effect = &quot;Allow&quot;<br>        Action = [<br>          &quot;s3:GetObject&quot;,<br>          &quot;s3:ListBucket&quot;<br>        ],<br>        Resource = [<br>          aws_s3_bucket.resources-bucket.arn,<br>          &quot;${aws_s3_bucket.resources-bucket.arn}/*&quot;<br>        ]<br>      },<br>    ]<br>  })<br>}<br><br>data &quot;aws_caller_identity&quot; &quot;current&quot; {}</pre><p>Finally, let’s create our data source which, for this example, will be of type S3 . We will also generate two outputs that will be used later on our gitlab pipeline to automatically trigger the sync job of the of AWS Kendra Data source:</p><pre>resource &quot;awscc_kendra_data_source&quot; &quot;kendra_datasource_s3&quot; {<br>  index_id        = awscc_kendra_index.kendra_index.id<br>  name            = &quot;kendra-datasource-s3&quot;<br>  role_arn        = awscc_iam_role.kendra_iam_role.arn<br>  type            = &quot;S3&quot;<br><br>  data_source_configuration = {<br>    s3_configuration = {<br>      bucket_name = aws_s3_bucket.resources-bucket.bucket<br>    }<br>  }<br>}<br><br><br>output &quot;kendra_index_id&quot; {<br>  value = awscc_kendra_index.kendra_index.id<br>}<br><br>output &quot;kendra_datasource_s3_id&quot; {<br>  value = awscc_kendra_data_source.kendra_datasource_s3.id<br>}</pre><p>So now, to finish Part One, let’s define our gitlab pipeline file: .gitlab-ci.yml</p><pre>image: registry.gitlab.com/gitlab-org/terraform-images/stable:latest<br><br>variables:<br>  STATE_NAME: kendra<br>  TF_ROOT: ${CI_PROJECT_DIR}<br>  TF_ADDRESS: ${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/terraform/state/${STATE_NAME}_state<br>  TF_VAR_aws_region: ${AWS_DEFAULT_REGION}<br><br>cache:<br>  key: ${STATE_NAME}_state<br>  paths:<br>    - ${TF_ROOT}/.terraform<br><br>before_script:<br>  - cd ${TF_ROOT}<br><br>stages:<br>  - prepare<br>  - validate<br>  - build<br>  - deploy<br>  - post-deploy<br><br>init:<br>  stage: prepare<br>  script:<br>    - gitlab-terraform init <br><br>validate:<br>  stage: validate<br>  script:<br>    - gitlab-terraform validate<br><br>plan:<br>  stage: build<br>  script:<br>    - chmod +x ./list_files.sh<br>    - export TF_VAR_files=$(./list_files.sh)<br>    - gitlab-terraform plan<br>    - gitlab-terraform plan-json<br>  artifacts:<br>    name: plan<br>    paths:<br>      - ${TF_ROOT}/plan.cache<br>    reports:<br>      terraform:  ${TF_ROOT}/plan.json<br><br>apply:<br>  stage: deploy<br>  script:<br>    - gitlab-terraform apply<br>    - echo &quot;KENDRA_INDEX_ID=$(gitlab-terraform  output -raw kendra_index_id)&quot; &gt;&gt; build.env<br>    - echo &quot;KENDRA_DATASOURCE_S3_ID=$(gitlab-terraform output -raw kendra_datasource_s3_id | cut -d&#39;|&#39; -f1)&quot; &gt;&gt; build.env<br>  artifacts:<br>    reports:<br>      dotenv: build.env<br>  dependencies:<br>    - plan<br>  when: manual<br><br>destroy:<br>  stage: deploy<br>  script:<br>    - gitlab-terraform destroy<br>  dependencies:<br>    - plan<br>  when: manual<br><br>sync:<br>  stage: post-deploy<br>  image: registry.gitlab.com/gitlab-org/cloud-deploy/aws-base:latest<br>  before_script: <br>    - aws configure set aws_access_key_id $AWS_ACCESS_KEY_ID<br>    - aws configure set aws_secret_access_key $AWS_SECRET_ACCESS_KEY<br>    - aws configure set default.region $AWS_DEFAULT_REGION<br>  script:<br>    - aws kendra start-data-source-sync-job --id $KENDRA_DATASOURCE_S3_ID --index-id $KENDRA_INDEX_ID<br>  needs:<br>    - job: apply<br>      artifacts: true <br>  when: manual<br></pre><p>We start by defining a couple of variables including the state address for our infrastructure which can be built upon default environment variables set by gitlab. We also set the aws_region terraform variable based on an environment variable AWS_DEFAULT_REGION. The init and validate jobs are straightforward, so let’s skip them and go to the plan job, where we are using a simple script to set the TF_VAR_files (assuming your files are under a folder named resources ):</p><pre>#!/bin/sh<br>directory=&quot;./resources&quot;<br>files=$(find $directory -type f | jq -R -s -c &#39;split(&quot;\n&quot;)[:-1]&#39;)<br>echo $files</pre><p>After the plan job, the apply job executes apply and exports the KENDRA_INDEX_ID and KENDRA_DATASOURCE_S3_ID to any other job that may need it. Finally, our sync job will use those two variables to trigger an AWS Kendra Datasource sync job. After the job completion, our AWS Kendra index will be ready to be used.</p><p>In <a href="https://medium.com/@alcbotta/automating-the-creation-of-your-own-rag-system-with-terraform-aws-kendra-and-aws-sagemaker-part-4b533b70beb0">Part two</a> of this series, we will create and deploy a <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct">Llama3 model</a> from Huggingface to AWS Sagemaker.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5744baf8caee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Your Golang Application with New Relic One]]></title>
            <link>https://blog.stackademic.com/monitoring-your-golang-application-with-new-relic-one-525a56a30e4b?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/525a56a30e4b</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[new-relic]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 10:31:44 GMT</pubDate>
            <atom:updated>2024-07-04T03:49:48.228Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometime ago I wrote the article: <a href="https://medium.com/@alcbotta/monitoring-you-golang-server-with-prometheus-and-grafana-97e64bb1d0e9"><strong>Monitoring you Golang server with Prometheus and Grafana</strong></a><strong>. </strong>Today, I will show you another fantastic tool you can use to monitor your application: <a href="https://newrelic.com/">New Relic One</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sO9mCQlNt7CZb1W0" /><figcaption>Photo by <a href="https://unsplash.com/@tobiastu?utm_source=medium&amp;utm_medium=referral">Tobias Tullius</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The application</h3><p>The application that we will monitor is a simple http server written in Golang which uses the Gin Web Framework. We will only have one endpoint: <em>/users/:userId/report</em></p><p>To make things a little bit more interesting, we will randomly delay responses or generate errors based on certain http headers. The full code for the application is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0b4a45b866726c66edc10fdd2e6da67/href">https://medium.com/media/e0b4a45b866726c66edc10fdd2e6da67/href</a></iframe><p>As you can see, the backend is quite simple and easy to follow. The important points for New Relic configuration are:</p><ul><li>lines 22–26: we declare a new instance of newrelic.NewApplication and set the license based on a environment variable (you will need your own license for this)</li><li>In line 40, after defining our Gin Engine called mux, we add a middleware to it: nrgin.Middleware(nrApp) , this middleware is responsible for creating a transaction for every new request received and then sending stats to New Relic</li><li>In line 60, you can see how to retrieve the current transaction from the Gin context. This is useful if you need the transaction, for example, when you want to record a specific error</li></ul><h4>Consumer</h4><p>To test our application and to have data in New Relic, we need to generate some request to the backend. We will use the following code to generate some random request to the reports endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a30b20bcf0c94e232ab9d1b3e83cf724/href">https://medium.com/media/a30b20bcf0c94e232ab9d1b3e83cf724/href</a></iframe><p>We will randomly define a simulated user and also randomly define headers that in time will add a delay to the response or even trigger an error.</p><p>After running the consumer for a while, you should be able to go to New Relic and see some statistics and information about the backend application.</p><h3>New Relic</h3><h4>Exploring the data</h4><p>Navigate to <a href="https://one.newrelic.com/">New Relic</a> and then click on Query Your Datayou should see this screen. We can now start exploring our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oW58RJXEGWdPPGlp2XQnhw.png" /></figure><p>Try running the following query:</p><pre>SELECT * from Transaction where appName=&#39;test-newrelic-go&#39; since 5 minutes ago</pre><p>You should see something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*hZmE8M_8D5yZUhNOfYDjSQ.png" /></figure><p>If you scroll to the right, you will notice that there is quite a lot of information for just a few lines of code. You can get the status code from the response, the request uri , and other.</p><p>We could check the number of requests be http code:</p><pre>SELECT count(*) from Transaction FACET httpResponseCode where appName=&#39;test-newrelic-go&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ctW_jqPtMjnSJaxX1uy4zg.png" /></figure><h4>Dashboards</h4><p>Going one step further, we can create dashboards for our application. An easier way to monitor our application without having to write those queries every time.</p><p>While we can create dashboards manually, I will show you how you can automate that with terraform . The following script will create a dashboard called <em>Medium Article Dashboard </em>with a single page and on this page we will have two widgets:</p><ul><li>max duration per user: early in the article you might have noticed that our backend could randomly delay some request. On this widget, we will display the max duration for each user</li><li>count by http response: on this widget, we will group the responses by http response code and count the total amount</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb1093c20f873fbedb6cba96556ff2bc/href">https://medium.com/media/bb1093c20f873fbedb6cba96556ff2bc/href</a></iframe><p>To run the script, you will need to configure two environment variables: TF_VAR_NEW_RELIC_ACCOUNT_ID and TF_VAR_NEW_RELIC_API_KEY, both based on your New Relic account information.</p><p>After running the terraform file, assuming you have some data in New Relic, you should see something similar to the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xZcKCd46SOYjFddBGcpuQ.png" /></figure><p>If you use Gitlab, you can easily deploy this terraform script using the steps described in my article: <a href="https://medium.com/@alcbotta/using-gitlab-to-manage-multi-environment-terraform-state-554f126e61cf">Using Gitlab to manage Multi Environment Terraform State</a></p><p>The full code for this example can be found <a href="https://github.com/alcbotta/medium_go_new_relic_terraform">here</a>.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=525a56a30e4b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/monitoring-your-golang-application-with-new-relic-one-525a56a30e4b">Monitoring Your Golang Application with New Relic One</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Gitlab to manage Multi Environment Terraform State]]></title>
            <link>https://medium.com/@alcbotta/using-gitlab-to-manage-multi-environment-terraform-state-554f126e61cf?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/554f126e61cf</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Sat, 22 Oct 2022 06:58:28 GMT</pubDate>
            <atom:updated>2022-10-24T00:24:51.571Z</atom:updated>
            <content:encoded><![CDATA[<p>Gitlab allows you to store the state from your terraform files on the same repository of your project. This feature is quite useful because you can then use Gilab CICD pipelines to automatically deploy changes to your infrastructure. However, if you need to deploy your infrastructure to different environments, you might need to have a separate state for each environment. So, I will show you one way of achieving that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3PvxqBzo-pQjC_xK" /><figcaption>Photo by <a href="https://unsplash.com/@qwitka?utm_source=medium&amp;utm_medium=referral">Maksym Kaharlytskyi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What we want to do</h4><p>For the sake of this example, let’s say we have two environments: <em>dev </em>and <em>prod</em>. And our infrastructure is simply an AWS Queue that has a different name and delay property based on the environment.</p><p>We start defining the backend:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d77f3b6e2d6ced5bccc4dc52603e455e/href">https://medium.com/media/d77f3b6e2d6ced5bccc4dc52603e455e/href</a></iframe><p>Quite simple, we will configure the address for the backend later in our gitlab-ci.yml file.</p><p>Our main.tf defines our AWS SQS Queue. Notice that we have the var.env and var.delay properties that are based on the environment context:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/756bbf4e8bc83e413da7bf25dda9c1e5/href">https://medium.com/media/756bbf4e8bc83e413da7bf25dda9c1e5/href</a></iframe><p>Now, the most important part of our project: the gitlab-ci.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/546898606045c133a28f6ac62f6a4076/href">https://medium.com/media/546898606045c133a28f6ac62f6a4076/href</a></iframe><p>At the start, the workflow section will define which environment we will build/deploy our changes based on the commit branch.</p><p>On the variables section, the TF_ADDRESS variable defines the address to be used for our <a href="https://www.terraform.io/language/settings/backends/http">http backend</a> in terraform. Some of environment variables in the TF_ADDRESS are automatically defined by the gitlab runner, such as: CI_API_V4_URL and CI_PROJECT_ID. However, the ENV variable that is used to define the state is the one previously defined in the workflow</p><p>On the plan job from the build stage, we will generate the plan file and use the respective tfvars file based on the current environment.</p><h4>Results</h4><p>Once you push your changes to the develop/main branch, your pipeline on gitlab should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9R8PrETkN_2qDoE37IQpQ.png" /></figure><p>And if you navigate to Infrastructure -&gt; Terraform , you should see two state files (assuming that you run the pipeline in both, develop and main, branches to completion):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*M2M_z5zhtR-tkPy23nREog.png" /></figure><p>On the AWS side, you should see the two AWS Queues:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*lK_pF4zFxU6eAthstFgx7A.png" /></figure><p>The full code can be found <a href="https://github.com/alcbotta/gitlab-terraform-medium">here</a></p><h4>References:</h4><ul><li><a href="https://docs.gitlab.com/ee/user/infrastructure/iac/terraform_state.html#help-and-feedback">GitLab-managed Terraform state | GitLab</a></li><li><a href="https://docs.gitlab.com/ee/user/infrastructure/iac/mr_integration.html">Terraform integration in merge requests | GitLab</a></li></ul><figure><a href="https://www.buymeacoffee.com/alcbotta"><img alt="Buy Me A Coffee" src="https://cdn-images-1.medium.com/max/545/1*iHZOhor4dAtQ15LbGzMUMw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=554f126e61cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring how much time I spend sitting: An Overview]]></title>
            <link>https://medium.com/@alcbotta/monitoring-how-much-time-i-spend-sitting-an-overview-b297ee2f4bf1?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b297ee2f4bf1</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Thu, 21 Jul 2022 07:22:19 GMT</pubDate>
            <atom:updated>2024-07-17T06:18:50.207Z</atom:updated>
            <content:encoded><![CDATA[<p>A while ago, I read an article highlighting how sitting for too long can be harmful to your health, unfortunately I didn’t find the original article, but a quick google search for the topic will give you an idea of the severity of the issue (for example: this <a href="https://edition.cnn.com/2017/09/11/health/sitting-increases-risk-of-death-study/index.html">article </a>from CNN or this other <a href="https://www.betterhealth.vic.gov.au/health/healthyliving/the-dangers-of-sitting">article </a>that compares sitting for too long to <strong>smoking</strong>).</p><p>All of that got me thinking: how much time am I spending sitting? Considering that I am a Software Engineer, you can guess that is a lot. But I wanted to get more insights of it and maybe even create a way to remember myself that it’s time for me to get up and stretch for a bit.</p><p><strong>Note</strong>: this article does not show implementation details of my solution, hence the “An Overview“ in the title. In the future I might break down each different component into their own article and deep dive on how I approached the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LDNQnE8sgTNScqjG.jpg" /><figcaption><a href="https://www.sconeadvocate.com.au/images/transform/v1/crop/frm/eV5wxSqxRk6zfLmD5bhc9J/6a2c40cd-7b06-455e-b684-2c53a6213b1c.jpg/r551_564_4325_2843_w1200_h678_fmax.jpg">source</a></figcaption></figure><h3>How to detect if I am sitting?</h3><p>The first issue that I thought was: if I am sitting for too long I need to get up, but how do I even know if I am sitting or standing? I had a couple of ideas on how to do that, however, I wanted to work with something that has been a bit of time since the last time I used it: Computer vision and Deep learning!</p><h4>Pytorch to the rescue!</h4><p>I have been reading quite a few articles that use the Pytorch framework, so I decided to give it a go. For my surprise: it was incredibly easy to go from nothing to a working model and, even better, just using the pytorch’s own documentation. I started with a very simple <a href="https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html">article</a> on how to train a classifier, after that I started exploring how to train a custom classifier. Meanwhile, I also stated using my webcam to take pictures of myself randomly throughout the day.</p><p>Once I had gathered enough data, I started training my custom model, which was quite easy and straightforward. In the end, I defined three classes: sitting, standing and away (since sometimes I might be away from my computer). Here is a sample of the images that I used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*uIM_IAh9MmKbiJ_nNOgbnw.png" /><figcaption>From the left to the right: away, sitting and standing</figcaption></figure><h3>Tracking if I have been sitting for too long and alerting</h3><h4>Processing and storing data</h4><p>The next step was creating the pipeline to process the data that my Custom Pytorch model was producing. Every prediction was being sent to a kafka server and in time it would be processed by a flink job. In the flink side, it would keep track of how long I was sitting continuously. For every new payload, it would process it and then send the result to a ElasticSearch cluster, used as the datastore for the application. But when it detected that I went over a certain threshold (of sitting), it would then also send a message to a RabbitMq, used as an alert queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qd6Wl9n_dqVoO_V10nnXTQ.png" /></figure><h4>Backend: Displaying alerts and Aggregating data</h4><p>The backend was written in Golang and had two main jobs:</p><ul><li>to subscribe to the Alert Queue (RabbitMQ) and;</li><li>to provide a REST API to search and aggregate the data in the ElasticSearch cluster.</li></ul><p>Basically, the backend dealt with receiving alerts from RabbitMQ and, in this case, displaying an on-screen alert:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*tEoGjst8Tesy1lqPudTqQg.png" /></figure><p>and also served as a simple REST API to interface with ElasticSearch, making it simpler to request data.</p><h4>Visualising the data</h4><p>Finally, I also created a web application to easily visualise the data in a web browser and see how many minutes per hour I was spending away, sitting or standing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdOWVoBkiGOG8kdh3GFObg.png" /></figure><p>I still need to work on a few details and improve some other things, but in a first moment I am quite surprised with the results. Very keen to keep working on this project to help reducing how much time I am sitting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b297ee2f4bf1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging your golang application to ElasticSearch with Filebeat]]></title>
            <link>https://medium.com/@alcbotta/logging-your-golang-application-to-elasticsearch-with-filebeat-12197a776ade?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/12197a776ade</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kibana]]></category>
            <category><![CDATA[filebeat]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Sat, 14 Aug 2021 04:11:50 GMT</pubDate>
            <atom:updated>2021-08-16T01:25:33.471Z</atom:updated>
            <content:encoded><![CDATA[<p>Logging is, without a doubt, one of the most important aspects of any application. When things go wrong, and they will, we need to know what happened. To achieve this, we could set up Filebeat to collect logs from our dockerized applications and then ship them to ElasticSearch. Finally, using Kibana we can visualise those logs and perform complex queries on them.</p><h3>How to reproduce this tutorial and run the code</h3><p>To make it easy to reproduce this tutorial, we will use <a href="https://docs.docker.com/get-docker/">Docker</a>, <a href="https://docs.docker.com/compose/install/">Docker-Compose</a> and <a href="https://code.visualstudio.com/docs/remote/containers">VS Code Remote Container</a>. I will not go into details on how to install those tools, but by simply following the documentation you should be fine.</p><p>You can find the full source code <a href="https://github.com/alcbotta/go-filebeat-elastic">here</a>.</p><h4>Application</h4><p>The application generating the logs is a very simple golang app. Our logs will be structured logs produced with the help of the <a href="https://github.com/uber-go/zap">Uber Zap library</a> and they will follow the <a href="https://www.elastic.co/guide/en/ecs/current/ecs-reference.html">ECS specification</a> by using the <a href="https://github.com/elastic/ecs-logging-go-zap">ecs-logging-go-zap</a> library. They will look like the following:</p><p>{“log.level”:”info”,”@timestamp”:”2021–08–14T01:11:41.420Z”,”log.origin”:{“file.name”:”project/main.go”,”file.line”:26},”message”:”everything is fine”,”app”:”myapp”,”environment”:”psm”,”count”:0,”ecs.version”:”1.6.0&quot;}</p><p>Here is the full code for the application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9484d7e098af6be6f2ffc6a4148bfc1d/href">https://medium.com/media/9484d7e098af6be6f2ffc6a4148bfc1d/href</a></iframe><h4>Filebeat</h4><p>We will configure Filebeat with the auto-discover option for docker. This will allow Filebeat to monitor any container running in our system. However, we can also filter which containers we want to monitor by setting the option <em>hints.default_config.enabled</em> to <em>false</em>. Now, when we want a container to have its logs collected, we will need to explicitly set the container’s label property <em>co.elastic.logs/enabled </em>to <em>true.</em></p><p>For this example, we are not going to use <a href="https://www.elastic.co/logstash/">Logstash</a>, since we don’t need to do any advanced processing or transformation of our data. We are simply going to output our logs to ElasticSearch. The Filebeat configuration file is as follow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b8e05db92f3e731199a0cb5918edad2/href">https://medium.com/media/7b8e05db92f3e731199a0cb5918edad2/href</a></iframe><h4>Elastic Stack</h4><p>Together with Filebeat, we are also going to spin up two other services: ElasticSearch and Kibana. Filebeat will output the logs that it collects from our application container to ElasticSearch. Kibana is then used to visualise our logs with a simple yet porwerfull GUI. Here is the docker-compose to start all three services:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/114ca3bd47dfd320e0987df5bc057d28/href">https://medium.com/media/114ca3bd47dfd320e0987df5bc057d28/href</a></iframe><h4>Running the application as a docker container</h4><p>The final set up step is to start our application inside a container. To do so, we will use the bellow docker-compose. Pay attention to the labels. We set the <em>co.elastic.logs/enabled </em>to <em>true</em>, which tells Filebeat that we want this container to have its logs collected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e6534ee0ca2de0eb1b7415d26079d7/href">https://medium.com/media/f4e6534ee0ca2de0eb1b7415d26079d7/href</a></iframe><h4>Kibana GUI</h4><p>Start the previous two docker-compose files and then go to <a href="http://localhost:5601/">http://localhost:5601/</a>. On the left-hand side menu, click on Observability/Logs and you should start seeing the logs coming in. Something like the bellow image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EGSx_OL-v0rmQ6nT4I-Bw.png" /></figure><p>Currently, there are only three columns being displayed. We can select more columns to be displayed by going to settings (at the top-right side of the screen):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPkaWWLN1yRdl_MA-9mFJg.png" /></figure><p>As we can see, we have the option to add more columns to our log stream. For our example, let’s add the four extra columns that our application is generating: app, environment, count and error.message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbaEixtPLZsPlvAfLrB5dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Uvq4GhkcujgKrLLxZtv6A.png" /></figure><p>If we go back to the Logs/Stream page, we should now see all attributes that our application is generating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OK9hxlO2HyoOzIR7q6itA.png" /></figure><p>That’s all for this example. The source code can be found at github:</p><p><a href="https://github.com/alcbotta/go-filebeat-elastic">GitHub - alcbotta/go-filebeat-elastic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12197a776ade" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring you Golang server with Prometheus and Grafana]]></title>
            <link>https://medium.com/@alcbotta/monitoring-you-golang-server-with-prometheus-and-grafana-97e64bb1d0e9?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e64bb1d0e9</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Sat, 31 Jul 2021 03:49:58 GMT</pubDate>
            <atom:updated>2021-07-31T03:49:58.218Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently became very interested on how you can learn insights from your application by monitoring it. Once I started searching about monitoring tools, it didn’t take too long to find out about <a href="https://prometheus.io/">Prometheus</a>, which will collect metrics from your application, and <a href="https://grafana.com/">Grafana</a>, which will display the collected metrics.</p><h4>How to reproduce this tutorial and run the code</h4><p>To make it easy to reproduce this tutorial, we will use <a href="https://docs.docker.com/get-docker/">Docker</a>, <a href="https://docs.docker.com/compose/install/">Docker-Compose</a> and <a href="https://code.visualstudio.com/docs/remote/containers">VS Code Remote Container</a>. I will not go into details on how to install those tools, but by simply following the documentation you should be fine.</p><p>You can find the full source code <a href="https://github.com/alcbotta/go-prometheus-grafana">here</a>.</p><p>Open the source code on VSCode and then click on <strong>Reopen in Container. </strong>Once the initialisation is finished, you should have three containers running under the service name of go-prometheus-grafana. You can now start the application by the GUI of VSCode or running the following command on the terminal: <em>go run main.go</em></p><h4>The user_status custom metric and the data being generated</h4><p>Once you start the application (specifically, the <em>main.go</em> file), it will create a custom counter metric called <em>http_request_get_user_status_count</em> and register it on the prometheus client. Both server and producer will be initialised. The producer will send messages to the server containing a random user name. The server then generates a random status for that request and then adds the response to the prometheus counter. We register an additional endpoint for Prometheus under the path “<em>/metrics</em>”. The code can be seen below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d5bade2cab83689fe711c528a8111fa/href">https://medium.com/media/3d5bade2cab83689fe711c528a8111fa/href</a></iframe><h4>Prometheus</h4><p>During initialisation, the prometheus service was configured to scrape for data every <em>5s</em> on the “<em>/metrics</em>” path having the server’s name as the target (since all services are running under the same nertwork, each service can discover the other by using the other service’s name):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d2216dd3aae274beee9c41f1b207f1c/href">https://medium.com/media/7d2216dd3aae274beee9c41f1b207f1c/href</a></iframe><p>Prometheus should be running on <a href="http://localhost:9090.">http://localhost:9090.</a> On the search expression, if you type <em>http_request_get_user_status_count</em>, you should see the data generated so far. Something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80tbDcU5c4S_IMj0l2eBSg.png" /></figure><h4>Grafana</h4><p>Now, to visualise the data in Prometheus, we will use Grafana. Grafana should be running on <a href="http://localhost:3000.">http://localhost:3000.</a> The default credentials are: <em>admin/admin.</em></p><p>The first thing we need to do is to add prometheus as a data source. To do so, on the left side panel, click on the <em>gear icon</em> and then on D<em>ata Sources </em>and finally <em>Add Data Source. </em>Select Prometheus and on the URL, enter: prometheus:9090, like the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*QgpQTvbpsenLA9PKTQQ8qA.png" /></figure><p>Scroll down, and click on <em>Save and Test,</em> you should see a message saying: “Data source is working”.</p><p>Now, on the left side panel, click on the “+” <em>icon </em>and then <em>Import.</em> On the new page, copy and paste the below json (or upload the file <em>grafana/panel.json </em>from the source code) and click <em>Load.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e0d3d1e7d095ef474b9b95462a7b227/href">https://medium.com/media/4e0d3d1e7d095ef474b9b95462a7b227/href</a></iframe><p>You should see something similar to the below on the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*i7GeGonEkxF1GubUn7xC0A.png" /></figure><p>It should be all. Of course, this is a extremely over simplified example that I used to understand how all parts connect to each other. Again, you can find the full code here:</p><p><a href="https://github.com/alcbotta/go-prometheus-grafana">GitHub - alcbotta/go-prometheus-grafana</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e64bb1d0e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event-Driven stream pipeline with Kafka, Flink and ElasticSearch]]></title>
            <link>https://medium.com/@alcbotta/event-driven-stream-pipeline-with-kafka-flink-and-elasticsearch-ed666aabeb1?source=rss-3f3d85e722b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed666aabeb1</guid>
            <category><![CDATA[flink]]></category>
            <category><![CDATA[data-processing]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Andre Botta]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 10:47:40 GMT</pubDate>
            <atom:updated>2020-08-26T10:47:40.114Z</atom:updated>
            <content:encoded><![CDATA[<p>How nice would be if you could “automagically” go from raw data to a ready to use database. Even better, what if your solution could handle different inputs in different forms. In this article I will try to show you how you can do that using Kafka, Flink and ElasticSearch.</p><p>The full code for this tutorial can be found <a href="https://github.com/alcbotta/event-driven-kafka-flink-es">here</a>.</p><h4>How to reproduce this tutorial</h4><p>To make it easy to reproduce this tutorial, we will use <a href="https://docs.docker.com/get-docker/">Docker</a>, <a href="https://docs.docker.com/compose/install/">Docker-Compose</a> and <a href="https://code.visualstudio.com/docs/remote/containers">VS Code Remote Container</a>. I will not go into details on how to install those tools, but by simply following the documentation you should be fine.</p><p>Once you have docker installed, we will create a network to be shared across all the services that we will be using. Just run the following command on a console:</p><pre>docker network create --attachable eventdriven --scope swarm -d overlay</pre><h4><strong>Kafka Setup</strong></h4><p>For this example, we will use <a href="https://docs.docker.com/compose/">docker-compose </a>to have a single node Kafka cluster. Use the following code to start your local cluster:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4be16a92e0570ceb187a7bbe957d23d4/href">https://medium.com/media/4be16a92e0570ceb187a7bbe957d23d4/href</a></iframe><h4>ElasticSearch Cluster</h4><p>Similarly to Kafka, we will use the following docker-compose file to start a single node ElasticSearch cluster. We will also start a <a href="https://www.elastic.co/kibana">Kibana</a> service, which will allows us to check the different indexes created after running the whole application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ab953f74fa697ad6ee65ab01f78fc98/href">https://medium.com/media/9ab953f74fa697ad6ee65ab01f78fc98/href</a></iframe><h4>Producer</h4><p>Our producer (the part of the application that is generating data) is a very simple Go application. We will pull data from <a href="https://github.com/abhionlyone/us-car-models-data">this</a> very nice repository that gives us data from cars produced in the USA from the year of 1992 to 2021! Here is a sample of what we are getting back:</p><pre>year,make,model,body_styles<br>1992,Acura,Integra,&quot;[&quot;&quot;Sedan&quot;&quot;, &quot;&quot;Hatchback&quot;&quot;]&quot;<br>1992,Acura,Legend,&quot;[&quot;&quot;Sedan&quot;&quot;, &quot;&quot;Coupe&quot;&quot;]&quot;<br>1992,Acura,NSX,&quot;[&quot;&quot;Coupe&quot;&quot;]&quot;<br>1992,Acura,Vigor,&quot;[&quot;&quot;Sedan&quot;&quot;]&quot;<br>1992,Alfa Romeo,164,&quot;[&quot;&quot;Sedan&quot;&quot;]&quot;<br>1992,Alfa Romeo,Spider,&quot;[&quot;&quot;Convertible&quot;&quot;]&quot;<br>1992,Audi,100,&quot;[&quot;&quot;Sedan&quot;&quot;, &quot;&quot;Wagon&quot;&quot;]&quot;</pre><p>Basically, we iterate over each year, download the csv file and process each of the lines of it and then publish a json string to the Kafka topic “car-makers”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39742144d97fcf536abf5553dc3ed0ac/href">https://medium.com/media/39742144d97fcf536abf5553dc3ed0ac/href</a></iframe><p>The json string is like the following:</p><pre>{</pre><pre>  &quot;year&quot;: 1992,</pre><pre>  &quot;maker&quot;: &quot;Acura&quot;,</pre><pre>  &quot;model&quot;: &quot;Integra&quot;,</pre><pre>  &quot;body_style&quot;: [</pre><pre>    &quot;Sedan&quot;,</pre><pre>    &quot;Hatchback&quot;</pre><pre>  ]</pre><pre>}</pre><h4>Flink Job — Consumer</h4><p>What is the desired output from our flink job: one index on ElasticSearch for each car maker. In other words: every time a new maker is found, flink will automatically create a new index on ElasticSearch.</p><p>To achieve that, we have three main steps in the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/887130ce121dc85ff34f221df2bac3ae/href">https://medium.com/media/887130ce121dc85ff34f221df2bac3ae/href</a></iframe><p>The first stream <em>jsonStream </em>subscribes to the <em>car-makers</em> topic to receive messages from Kafka. Given a few restrictions in regards to naming indexes on ElasticSearch, we do a very simple data processing on this step: we transform the maker string to lower case and then replace spaces for “_”. For example, if the maker is “Alfa Romeo”, after processing, the new maker will be “alfa_romeo”.</p><p>The second step, “keyedStream”, simply splits the single stream into multiple streams by the key “maker”.</p><p>Finally, “esSinkBuilder” is a <a href="https://ci.apache.org/projects/flink/flink-docs-release-1.11/dev/connectors/elasticsearch.html">sink </a>responsible for creating a index and adding data to that index for each of the keyed streams.</p><h4>Running the multiple services</h4><p>Now that we have everything in place, it is time to start the services. We can start the Kafka cluster and then the ElasticSearch cluster. Make sure that those containers are running! Now, we can use VS Code Remote to run the flink job. Again, if you don’t want to install anything in your computer, you can use VS Code Remote to start the producer. Once the producer is finished (it may take some time given the amount of data to process, you can reduce the number of years to process to speed things up).</p><p>Next, if you go to:</p><pre><a href="http://localhost:5601/app/kibana#/dev_tools/console">http://localhost:5601/app/kibana#/dev_tools/console</a></pre><p>You should see the Kibana dev tools console. Run:</p><pre>GET /_aliases</pre><p>and you should see the multiple indexes created, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*5uauAKKIkjLW4stk5pI-aA.png" /></figure><p>This tutorial is very simple, but this approach could be applied to other domains. You could, for example, process a stream of data from different types of sensors and then create a index for each sensor type :)</p><p>The code used for this tutorial can be found at <a href="https://github.com/alcbotta/event-driven-kafka-flink-es">github</a>.</p><p><a href="https://github.com/alcbotta/event-driven-kafka-flink-es">alcbotta/event-driven-kafka-flink-es</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed666aabeb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>