<?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 Brian Mwangi on Medium]]></title>
        <description><![CDATA[Stories by Brian Mwangi on Medium]]></description>
        <link>https://medium.com/@brianmwangi_dev?source=rss-28225805d05b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ojv8Byt4X4Fm1XyC4LArZA.jpeg</url>
            <title>Stories by Brian Mwangi on Medium</title>
            <link>https://medium.com/@brianmwangi_dev?source=rss-28225805d05b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:18:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brianmwangi_dev/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[The problem with the internet right now]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@brianmwangi_dev/the-problem-with-the-internet-right-now-16052b492628?source=rss-28225805d05b------2"><img src="https://cdn-images-1.medium.com/max/2600/0*yxI4LmLFYCu7Ku4a" width="5760"></a></p><p class="medium-feed-snippet">Imagine you&#x2019;re at a concert with thousands of people.</p><p class="medium-feed-link"><a href="https://medium.com/@brianmwangi_dev/the-problem-with-the-internet-right-now-16052b492628?source=rss-28225805d05b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@brianmwangi_dev/the-problem-with-the-internet-right-now-16052b492628?source=rss-28225805d05b------2</link>
            <guid isPermaLink="false">https://medium.com/p/16052b492628</guid>
            <category><![CDATA[chatting]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Brian Mwangi]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 19:52:21 GMT</pubDate>
            <atom:updated>2026-09-10T19:52:21.322Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[I Stopped Looking for App Ideas and Started Reading 1-Star Reviews]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@brianmwangi_dev/i-stopped-looking-for-app-ideas-and-started-reading-1-star-reviews-f0dde619e10b?source=rss-28225805d05b------2"><img src="https://cdn-images-1.medium.com/max/2600/0*j4XsN_Zyx1VQh6C6" width="4032"></a></p><p class="medium-feed-snippet">For the longest time I used to have friends who would come to me with a weird idea like an uber service for dogs, a chat place for old&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@brianmwangi_dev/i-stopped-looking-for-app-ideas-and-started-reading-1-star-reviews-f0dde619e10b?source=rss-28225805d05b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@brianmwangi_dev/i-stopped-looking-for-app-ideas-and-started-reading-1-star-reviews-f0dde619e10b?source=rss-28225805d05b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0dde619e10b</guid>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[founders]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Brian Mwangi]]></dc:creator>
            <pubDate>Sat, 29 Aug 2026 08:09:23 GMT</pubDate>
            <atom:updated>2026-08-29T08:09:23.573Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Livekit and Azure AKS; A Match made in Heaven]]></title>
            <link>https://medium.com/@brianmwangi_dev/livekit-and-azure-aks-a-match-made-in-heaven-c75e83c18b77?source=rss-28225805d05b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c75e83c18b77</guid>
            <category><![CDATA[freeswitch]]></category>
            <category><![CDATA[freeswitch-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[livekit]]></category>
            <dc:creator><![CDATA[Brian Mwangi]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 14:45:00 GMT</pubDate>
            <atom:updated>2025-07-18T14:45:00.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ubT9Bc1r2hBc_9eb" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Self host your Livekit Freeswitch server easily with guided steps</p><p>So in a past <a href="https://medium.com/@brianmwangi_dev/voice-assistant-agent-livekit-firebase-and-freeswitch-efaedf34757e">article</a> I built a restaurant ordering and service that serves to allow people make reservations and make orders. I did this via Livekit and firebase and freeswitch. Now this was all done via my laptop but I needed to know this could work in production. Based on a request from a friend deploying this on Azure is a great idea since they offer a $200 credit.</p><h3>Introduction</h3><p>Don’t blame me but this is just what I needed to test out this application and make performance improvement and maybe showcase it to people that I can actually help them out in their project but most importantly do something without AI vibe coding through the entire app.</p><p>No offense to anyone I do use AI but I loved the grind of doing things without it and being able to ask people for answers and getting it even if it was after a week 😑.</p><p>So this are the steps that I made to deploy the app to Azure AKS (Kubernetes service on Azure). Please note I did get some help for some of the commands due to the vast documentation.</p><p>So the first step is create a resource group. Resource Groups allow us to containeraze the entire application in Azure. And allow for easy management of all resource used by the project. This makes it reduces getting lost in the vast Azure landscape.</p><p>This article assumes that you have installed <strong><em>azure cli. </em></strong>If you haven’t you can follow <a href="https://learn.microsoft.com/en-us/cli/azure/get-started-with-azure-cli?view=azure-cli-latest">this</a> article by Azure on how to do it.</p><p>Okay cool 😎, let’s create the resource group. The name has to be unique and we are starting with eastus since its cheaper. Please choose the <strong>region</strong> you need, you won’t change this later on.</p><pre>az group create --name vocare-restaurant-ar --location eastus</pre><p>Okay great. Now our app runs on Docker, we need a way to host our image and a way for it to be built. Azure’s Container registry will handle this. Please note the resource name its extremely important. Since its the container for the entire app.</p><pre>az acr create --resource-group vocare-restaurant-ar --name vocareacr --sku Basic<br><br># Remember to run this to enable Container Services otherwise AKS cluster won&#39;t create<br>az provider register --namespace Microsoft.ContainerService --wait</pre><p>It will take a while to complete but once its done. We can move to the next step. Here is how the response will look like</p><pre>{<br>  &quot;adminUserEnabled&quot;: false,<br>  &quot;anonymousPullEnabled&quot;: false,<br>  &quot;autoGeneratedDomainNameLabelScope&quot;: &quot;Unsecure&quot;,<br>  &quot;creationDate&quot;: &quot;2025-07-17T09:38:10.432906+00:00&quot;,<br>  &quot;dataEndpointEnabled&quot;: false,<br>  &quot;dataEndpointHostNames&quot;: [],<br>  &quot;encryption&quot;: {<br>    &quot;keyVaultProperties&quot;: null,<br>    &quot;status&quot;: &quot;disabled&quot;<br>  },<br>  &quot;id&quot;: &quot;/subscriptions/{{yourunique_id}}&quot;,<br>  &quot;identity&quot;: null,<br>  &quot;location&quot;: &quot;eastus&quot;,<br>  &quot;loginServer&quot;: &quot;vocareacr.azurecr.io&quot;,<br>  &quot;metadataSearch&quot;: &quot;Disabled&quot;,<br>  &quot;name&quot;: &quot;vocareacr&quot;,<br>  &quot;networkRuleBypassOptions&quot;: &quot;AzureServices&quot;,<br>  &quot;networkRuleSet&quot;: null,<br>  &quot;policies&quot;: {<br>    &quot;azureAdAuthenticationAsArmPolicy&quot;: {<br>      &quot;status&quot;: &quot;enabled&quot;<br>    },<br>    &quot;exportPolicy&quot;: {<br>      &quot;status&quot;: &quot;enabled&quot;<br>    },<br>    &quot;quarantinePolicy&quot;: {<br>      &quot;status&quot;: &quot;disabled&quot;<br>    },<br>    &quot;retentionPolicy&quot;: {<br>      &quot;days&quot;: 7,<br>      &quot;lastUpdatedTime&quot;: &quot;2025-07-17T09:38:17.753155+00:00&quot;,<br>      &quot;status&quot;: &quot;disabled&quot;<br>    },<br>    &quot;softDeletePolicy&quot;: {<br>      &quot;lastUpdatedTime&quot;: &quot;2025-07-17T09:38:17.753201+00:00&quot;,<br>      &quot;retentionDays&quot;: 7,<br>      &quot;status&quot;: &quot;disabled&quot;<br>    },<br>    &quot;trustPolicy&quot;: {<br>      &quot;status&quot;: &quot;disabled&quot;,<br>      &quot;type&quot;: &quot;Notary&quot;<br>    }<br>  },<br>  &quot;privateEndpointConnections&quot;: [],<br>  &quot;provisioningState&quot;: &quot;Succeeded&quot;,<br>  &quot;publicNetworkAccess&quot;: &quot;Enabled&quot;,<br>  &quot;resourceGroup&quot;: &quot;vocare-restaurant-rg&quot;,<br>  &quot;roleAssignmentMode&quot;: &quot;LegacyRegistryPermissions&quot;,<br>  &quot;sku&quot;: {<br>    &quot;name&quot;: &quot;Basic&quot;,<br>    &quot;tier&quot;: &quot;Basic&quot;<br>  },<br>  &quot;status&quot;: null,<br>  &quot;systemData&quot;: {<br>    &quot;createdAt&quot;: &quot;2025-07-17T09:38:10.432906+00:00&quot;,<br>    &quot;createdBy&quot;: &quot;youremail&quot;,<br>    &quot;createdByType&quot;: &quot;User&quot;,<br>    &quot;lastModifiedAt&quot;: &quot;2025-07-17T09:38:10.432906+00:00&quot;,<br>    &quot;lastModifiedBy&quot;: &quot;youremail&quot;,<br>    &quot;lastModifiedByType&quot;: &quot;User&quot;<br>  },<br>  &quot;tags&quot;: {},<br>  &quot;type&quot;: &quot;Microsoft.ContainerRegistry/registries&quot;,<br>  &quot;zoneRedundancy&quot;: &quot;Disabled&quot;<br>}</pre><blockquote>So the most important part is “provisioningState”: “Succeeded”,</blockquote><p>So now we need to create the AKS Cluster. This is the main service that handles Kubernetes; mainly Control plane and the nodes. The control plane is what handles the service and the nodes are like the Virtual machines.</p><pre>az aks create --resource-group vocare-restaurant-rg --name vocare-aks --node-count 3 --node-vm-siz<br>e Standard_D2s_v3 --enable-addons monitoring --attach-acr vocareacr --generate-ssh-keys</pre><p>So this is very important and my advice is to start simple and then scale it to prevent setting unreasonable properties. You can definitely change it later.</p><p>So I got an error on <strong>OperationalInsights</strong></p><p>And what this is that we have enabled monitoring. The monitoring addon for AKS uses Azure Monitor Container Insights which in turn relies on Azure Log Analytics Workspace.</p><p>So lets enable it.</p><pre>az provider register --namespace Microsoft.OperationalInsights --wait<br>az provider register --namespace Microsoft.Insights --wait</pre><p>We start with a basic 3 nodes, even though few. It will allow us to test this out and keep costs low in the meantime. So is the vm size, <strong>Standard_D2s_v3 </strong>this is pretty basic for a production workload since its only a 8gb RAM and 2 vCPUs<strong>.</strong></p><p>So this command will take some time so you can take a coffee break or play a game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*timbUhDPDDF9mEZK.gif" /></figure><p>Once its done we need to be able to communicate with the cluster from our terminal using the cli. Even though we are logged in we need to be able to connect securely and not have jut anyone connect. You can do this via the web app.</p><pre>az aks get-credentials --resource-group vocare-restaurant-rg --name vocare-aks</pre><p>We need to be able to use kubectl securely so this cmd will download the necessary files to allow for that in our kube config. For vocare we do:</p><pre>az aks get-credentials --resource-group vocare-restaurant-rg --name vocare-aks</pre><p>Great now we can run <strong>kubectl</strong> and get info. 🔥</p><pre>kubectl get nodes<br>NAME                                STATUS   ROLES    AGE     VERSION<br>aks-nodepool1-18571546-vmss000000   Ready    &lt;none&gt;   9m13s   v1.33.1<br>aks-nodepool1-18571546-vmss000001   Ready    &lt;none&gt;   8m59s   v1.33.1</pre><p>Okay good. Since we are deploying to production we need to handle securely API keys and secrets such as OPENAI and others like DeepGram for Voice. Azure provide the keyvault so let’s create it. We can then reference the secrets when deploying.</p><pre>az keyvault create \<br>    --name vocare-kv \<br>    --resource-group vocare-restaurant-rg \<br>    --location eastus</pre><p>If you hit a resource provider error just enable it.</p><pre>az provider register --namespace Microsoft.KeyVault --wait</pre><p>Also we need to securely access the keyvault, that is our backend running on AKS. We run the following command which enables the <strong>Azure Key Vault Secrets Provider Container Storage Interface (CSI) driver. </strong>We will then define a SecretProviderClass resource which will allow us to know which KeyVault instance to use, which secrets to use and how the same secrets should be mounted.</p><pre>az aks enable-addons --addons azure-keyvault-secrets-provider --name vocare-aks --resource-gro<br>up vocare-restaurant-rg</pre><p>We need to give AKS access to the KeyVault. First we get the identity, and assign it the value.</p><pre>AKS_IDENTITY=$(az aks show --name vocare-aks --resource-group vocare-restaurant-rg --query &quot;identityProfile.kubeletidentity.clientId&quot; -o tsv)</pre><p>After this we need to get the Key Vault’s full Azure Resource ID. Same this assign it the value which we will use later on.</p><pre>KEYVAULT_ID=$(az keyvault show --name &quot;vocate-aks&quot; --resource-group &quot;vocare-restaurant-rg&quot; --query id -o tsv)</pre><p>We finally assign the role to AKS identity at the Key Vault scope.</p><pre>az role assignment create \<br>    --assignee $AKS_IDENTITY \<br>    --role &quot;Key Vault Secrets User&quot; \<br>    --scope &quot;$KEYVAULT_ID&quot;</pre><p>Finally! the initial set up is complete and we can build our image and set the secrets that our backend needs.</p><p>Building and pushing the image to container registry. So for this to work you need to upgrade your subscription, the free credits won’t allow for this to work. Don’t worry you won’t be charged for this. They just need your details 🙈</p><pre># Make sure you are in the parent directory. Change the name to your project name<br>az acr build --registry vocareacr --image vocare-backend:latest .</pre><p>So we set up our secrets. For best results on SIP trunking provider, SignalWire is the best candidate. Because they are the original creators of freeswitch. They offer a very solid foundation and the latency won’t be a problem, their APIs are very developer friendly too. Am not paid to say this so.. TRUST ME BRO 😂</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J8jrVE2ItMmQi68zLGV73w.png" /><figcaption>FreeSwitch Dashboard</figcaption></figure><p>Example setting up.</p><pre># Set up example for keyvault. Do this for all your secrets and you&#39;ll reference them later on in deployment and service scripts.<br>az keyvault secret set --vault-name $YOUR_KEYVAULT_NAME --name openai-api-key --value &#39;YOUR_OPENAI_KEY&#39;&quot;</pre><p>Now after adding all the secrets to keyvault. We need two set up the namespace for our cluster and then configure the secrets to tell AKS not just where to access but what to access. So we will use kubectl to handle this. Set up the following yaml file with the namespace and the secrets. The namespace is required to securely scope the secrets and know which services have access to them. Manages user access really.</p><p>So we create the namespace and deploy it.</p><pre>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: YOUR_NAMESPACE_NAME<br>  labels:<br>    app: vocare-restaurant<br>    environment: production</pre><p>we also set up the secrets and reference the namespace and tenant id.</p><pre>apiVersion: secrets-store.csi.x-k8s.io/v1<br>kind: SecretProviderClass<br>metadata:<br>  name: vocare-keyvault-secrets<br>  namespace: YOUR_NAMESPACE<br>spec:<br>  provider: azure<br>  parameters:<br>    usePodIdentity: &quot;false&quot;<br>    useVMManagedIdentity: &quot;true&quot;<br>    userAssignedIdentityID: &quot;&quot;  # Will be populated by setup script<br>    keyvaultName: &quot;YOUR_KEYVAULT_NAME&quot;<br>    cloudName: &quot;&quot;<br>    objects: |<br>      array:<br>        - |<br>          objectName: openai-api-key<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: deepgram-api-key<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: cartesia-api-key<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: livekit-api-key<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: livekit-api-secret<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: sip-username<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: sip-password<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: sip-realm<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: sip-proxy<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: freeswitch-default-password<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>        - |<br>          objectName: firebase-service-account-json<br>          objectType: secret<br>          objectVersion: &quot;&quot;<br>    tenantId: &quot;YOUR_TENANT_ID&quot;<br>  secretObjects:<br>  - secretName: vocare-api-secrets<br>    type: Opaque<br>    data:<br>    - objectName: openai-api-key<br>      key: openai-api-key<br>    - objectName: deepgram-api-key<br>      key: deepgram-api-key<br>    - objectName: cartesia-api-key<br>      key: cartesia-api-key<br>    - objectName: livekit-api-key<br>      key: livekit-api-key<br>    - objectName: livekit-api-secret<br>      key: livekit-api-secret<br>  - secretName: vocare-sip-secrets<br>    type: Opaque<br>    data:<br>    - objectName: sip-username<br>      key: sip-username<br>    - objectName: sip-password<br>      key: sip-password<br>    - objectName: sip-realm<br>      key: sip-realm<br>    - objectName: sip-proxy<br>      key: sip-proxy<br>  - secretName: vocare-freeswitch-secrets<br>    type: Opaque<br>    data:<br>    - objectName: freeswitch-default-password<br>      key: default-password<br>  - secretName: vocare-firebase-secret<br>    type: Opaque<br>    data:<br>    - objectName: firebase-service-account-json<br>      key: service-account-json</pre><p>Cool now you can simple deploy them via kubectl. In my case</p><pre> kubectl apply -f k8s/shared/namespace.yaml <br> kubectl apply -f k8s/shared/secret-provider-class.yaml</pre><p>Also key detail, to ensure you have deployed well. You can check whether all your secrets have deployed well using this.</p><pre>az keyvault secret list --vault-name vocare-kv --output table</pre><p>After this we deploy our image to ACR. To do that we need to login, this is mosty for security reasons. Also this command has access to the registry and needs careful attention to keep any malware or bots from accessing. Make sure you have Docker running else its going to fail.</p><pre>az acr login --name $YOUR_ACR_NAME<br># After this passes build and push the image<br>az acr build --registry $YOUR_ACR_NAME --image $IMAGE_NAME:$VERSION --file Dockerfile .</pre><p>Once that is done, make sure you copy the name of the image location. We will use it later. Great!</p><p>So now that everything is set up well in KeyVault. We need to securely secure access to the keyvault. Don’t ask I know 😏</p><p>Azure provides a service called, workload identity. Which verifies if a certain service is allowed to access the keyvault data. Its the guy with them keys.</p><p>Okay we need to set it up real quick. Ensure you have the OIDC(OpenID Connect) issuer URL. This URL acts as a trusted identity provider for your Kubernetes cluster.</p><pre># Have these in place or create an sh script to make it easier. They are simply names we can use later on in the cmd calls<br>MANAGED_IDENTITY_NAME=&quot;vocare-workload-identity&quot;<br>SERVICE_ACCOUNT_NAME=&quot;vocare-workload-identity&quot;<br>SERVICE_ACCOUNT_NAMESPACE=&quot;vocare-restaurant&quot;<br><br># Get the issuer URL<br>az aks show --name $AKS_CLUSTER_NAME --resource-group $RESOURCE_GROUP --query &quot;oidcIssuerProfile.issuerUrl&quot; -o tsv<br><br># Create the managed identity<br>az identity create --name $MANAGED_IDENTITY_NAME --resource-group $RESOURCE_GROUP<br><br># After the creation get the client and principal id. These are separate CMDs we are assigning their values to a variable.<br># THE CLIENT ID IS EXTREMELY IMPORTANT YOU WILL USE IT ELSEWHERE IN THE DEPLOYMENT<br>MANAGED_IDENTITY_CLIENT_ID=$(az identity show --name $MANAGED_IDENTITY_NAME --resource-group $RESOURCE_GROUP --query &quot;clientId&quot; -o tsv)<br>MANAGED_IDENTITY_OBJECT_ID=$(az identity show --name $MANAGED_IDENTITY_NAME --resource-group $RESOURCE_GROUP --query &quot;principalId&quot; -o tsv)</pre><p>After that is complete you can grant keyvault access to managed identity</p><pre>az keyvault set-policy \<br>    --name $KEYVAULT_NAME \<br>    --object-id $MANAGED_IDENTITY_OBJECT_ID \<br>    --secret-permissions get list</pre><p>Workload Identity leverages this OIDC Issuer URL to enable your Kubernetes service accounts to act as federated identities with Azure Active Directory</p><pre><br># This is the entire sh script. PS. I had a little help<br><br>set -e<br><br># Load Azure configuration<br>if [ -f &quot;azure-config.env&quot; ]; then<br>    source azure-config.env<br>else<br>    echo &quot;❌ Azure configuration not found. Please run setup-azure.sh first.&quot;<br>    exit 1<br>fi<br><br># Configuration<br>MANAGED_IDENTITY_NAME=&quot;vocare-workload-identity&quot;<br>SERVICE_ACCOUNT_NAME=&quot;vocare-workload-identity&quot;<br>SERVICE_ACCOUNT_NAMESPACE=&quot;vocare-restaurant&quot;<br><br>echo &quot;🔐 Setting up Azure Workload Identity...&quot;<br>echo &quot;Resource Group: $RESOURCE_GROUP&quot;<br>echo &quot;AKS Cluster: $AKS_CLUSTER_NAME&quot;<br>echo &quot;Key Vault: $KEYVAULT_NAME&quot;<br>echo &quot;Managed Identity: $MANAGED_IDENTITY_NAME&quot;<br>echo &quot;&quot;<br><br># Get AKS OIDC issuer URL<br>echo &quot;🔍 Getting AKS OIDC issuer URL...&quot;<br>AKS_OIDC_ISSUER=$(az aks show --name $AKS_CLUSTER_NAME --resource-group $RESOURCE_GROUP --query &quot;oidcIssuerProfile.issuerUrl&quot; -o tsv)<br><br>if [ -z &quot;$AKS_OIDC_ISSUER&quot; ]; then<br>    echo &quot;❌ OIDC issuer not found. Enabling OIDC issuer on AKS cluster...&quot;<br>    az aks update --resource-group $RESOURCE_GROUP --name $AKS_CLUSTER_NAME --enable-oidc-issuer<br>    AKS_OIDC_ISSUER=$(az aks show --name $AKS_CLUSTER_NAME --resource-group $RESOURCE_GROUP --query &quot;oidcIssuerProfile.issuerUrl&quot; -o tsv)<br>fi<br><br>echo &quot;OIDC Issuer: $AKS_OIDC_ISSUER&quot;<br><br># Create managed identity<br>echo &quot;🆔 Creating managed identity...&quot;<br>az identity create --name $MANAGED_IDENTITY_NAME --resource-group $RESOURCE_GROUP<br><br># Get managed identity details<br>MANAGED_IDENTITY_CLIENT_ID=$(az identity show --name $MANAGED_IDENTITY_NAME --resource-group $RESOURCE_GROUP --query &quot;clientId&quot; -o tsv)<br>MANAGED_IDENTITY_OBJECT_ID=$(az identity show --name $MANAGED_IDENTITY_NAME --resource-group $RESOURCE_GROUP --query &quot;principalId&quot; -o tsv)<br><br>echo &quot;Managed Identity Client ID: $MANAGED_IDENTITY_CLIENT_ID&quot;<br>echo &quot;Managed Identity Object ID: $MANAGED_IDENTITY_OBJECT_ID&quot;<br><br># Grant Key Vault access to managed identity<br>echo &quot;🔑 Granting Key Vault access to managed identity using RBAC...&quot;<br># Get the Key Vault&#39;s resource ID<br>KEYVAULT_RESOURCE_ID=$(az keyvault show --name $KEYVAULT_NAME --resource-group $RESOURCE_GROUP --query id -o tsv)<br><br># Assign the &quot;Key Vault Secrets User&quot; role<br>az role assignment create \<br>    --assignee $MANAGED_IDENTITY_OBJECT_ID \<br>    --role &quot;Key Vault Secrets User&quot; \<br>    --scope &quot;$KEYVAULT_RESOURCE_ID&quot;<br><br># Create federated identity credential<br>echo &quot;🔗 Creating federated identity credential...&quot;<br>az identity federated-credential create \<br>    --name &quot;vocare-federated-credential&quot; \<br>    --identity-name $MANAGED_IDENTITY_NAME \<br>    --resource-group $RESOURCE_GROUP \<br>    --issuer $AKS_OIDC_ISSUER \<br>    --subject &quot;system:serviceaccount:$SERVICE_ACCOUNT_NAMESPACE:$SERVICE_ACCOUNT_NAME&quot;<br></pre><p>Now we need to update our service account script to use the details.</p><pre># Service Account for Azure Workload Identity<br># This enables secure access to Azure Key Vault without storing credentials<br><br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: vocare-workload-identity<br>  namespace: vocare-restaurant<br>  annotations:<br>    azure.workload.identity/client-id: &quot;REPLACE_WITH_MANAGED_IDENTITY_CLIENT_ID&quot; # Please Note<br>  labels:<br>    azure.workload.identity/use: &quot;true&quot;<br><br>---<br># ClusterRole for accessing secrets<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRole<br>metadata:<br>  name: vocare-secret-reader<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;secrets&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;configmaps&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]<br><br>---<br># ClusterRoleBinding<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: ClusterRoleBinding<br>metadata:<br>  name: vocare-secret-reader-binding<br>subjects:<br>- kind: ServiceAccount<br>  name: vocare-workload-identity<br>  namespace: vocare-restaurant<br>roleRef:<br>  kind: ClusterRole<br>  name: vocare-secret-reader<br>  apiGroup: rbac.authorization.k8s.io</pre><p>Apply it by running it with kubectl.</p><pre>kubectl apply -f service-account.yaml<br>--  serviceaccount/vocare-workload-identity created<br>--  clusterrole.rbac.authorization.k8s.io/vocare-secret-reader created<br>--  clusterrolebinding.rbac.authorization.k8s.io/vocare-secret-reader-binding created</pre><p>To keep our app organized in kubernetes we need to organise the secrets and non sensitive configs like livekit configurations, AI models and all that in a way that is clear and manageable. This is also best practice according to creators of K8s. You can get more details here</p><p><a href="https://kubernetes.io/docs/concepts/configuration/configmap/">ConfigMaps</a></p><p>So this is what we will have now. So its simple to ensure this article doesn’t get any bigger than it should be. Please note the Keys since we will reference them in the deployment scripts.</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: vocare-config<br>  namespace: vocare-restaurant<br>data:<br>  # Application configuration<br>  OPENAI_MODEL: &quot;gpt-4o-mini&quot;<br>  FIREBASE_SERVICE_ACCOUNT_PATH: &quot;/app/secrets/service-account.json&quot;<br><br>  # LiveKit configuration<br>  LIVEKIT_URL: &quot;ws://livekit-service:7880&quot;<br><br>  # Restaurant configuration<br>  RESTAURANT_NAME: &quot;Vocare Restaurant&quot;<br>  FREESWITCH_DOMAIN: &quot;vocare.local&quot;<br>  FREESWITCH_HOLD_MUSIC: &quot;local_stream://moh&quot;<br><br>  # Network configuration<br>  FREESWITCH_EXTERNAL_RTP_PORT_MIN: &quot;30000&quot;<br>  FREESWITCH_EXTERNAL_RTP_PORT_MAX: &quot;30010&quot;<br><br>  # Logging<br>  FREESWITCH_LOG_LEVEL: &quot;INFO&quot;<br><br>---<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: livekit-config<br>  namespace: vocare-restaurant<br>data:<br>  livekit.yaml: |<br>    # Production LiveKit configuration<br>    keys:<br>      # Will be overridden by environment variables<br>      prodkey: secret<br><br>    # Network settings<br>    port: 7880<br>    bind_addresses:<br>      - &quot;&quot;<br><br>    # WebSocket settings<br>    rtc:<br>      tcp_port: 7881<br>      port_range_start: 16384<br>      port_range_end: 16394<br>      use_external_ip: true<br><br>    turn:<br>      enabled: true<br>      domain: &quot;&quot;<br>      cert_file: &quot;&quot;<br>      key_file: &quot;&quot;<br><br>    # Room settings<br>    room:<br>      auto_create: true<br>      max_participants: 10<br>      empty_timeout: 300<br>      departure_timeout: 20<br><br>    # Webhook settings<br>    webhook:<br>      api_key: prodkey<br>      urls:<br>        - http://backend-service:8000/webhook<br><br>    # Logging<br>    logging:<br>      level: info<br>      pion_level: warn<br><br>    # Production mode<br>    development: false</pre><p>Make sure to apply it.</p><pre>kubectl apply -f configmap.yaml</pre><h3>Deployment</h3><p>So now the best part starts. We will begin deploying the app starting with freeswitch then go to self hosting LiveKit then lastly our backend. This is based on dependency hierarchy and prevent any build failures caused by any of missing configurations.</p><p><strong>FreeSwitch</strong></p><p>Since we have learned about the reason for config maps. They will be well suited for freeswitch many ports and tight configurations. So create a folder under <strong>freeswitch</strong> mainly for k8s deployment. In this case a <em>configmap.yaml</em>. Make sure to give it a unique name specific to where it will be used.</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: freeswitch-config<br>  namespace: vocare-restaurant<br>data:<br>  freeswitch.xml: |<br>    &lt;?xml version=&quot;1.0&quot;?&gt;<br>    &lt;document type=&quot;freeswitch/xml&quot;&gt;<br><br>      &lt;section name=&quot;configuration&quot; description=&quot;Various Configuration&quot;&gt;<br><br>        &lt;!-- Event Socket (for LiveKit integration) --&gt;<br>        &lt;configuration name=&quot;event_socket.conf&quot; description=&quot;Socket Client&quot;&gt;<br>          &lt;settings&gt;<br>            &lt;param name=&quot;nat-map&quot; value=&quot;false&quot;/&gt;<br>            &lt;param name=&quot;listen-ip&quot; value=&quot;0.0.0.0&quot;/&gt;<br>            &lt;param name=&quot;listen-port&quot; value=&quot;8021&quot;/&gt;<br>            &lt;param name=&quot;password&quot; value=&quot;ClueCon&quot;/&gt;<br>            &lt;param name=&quot;apply-inbound-acl&quot; value=&quot;loopback.auto&quot;/&gt;<br>            &lt;param name=&quot;stop-on-bind-error&quot; value=&quot;true&quot;/&gt;<br>          &lt;/settings&gt;<br>        &lt;/configuration&gt;<br><br>        &lt;!-- SIP Profile for incoming calls --&gt;<br>        &lt;configuration name=&quot;sofia.conf&quot; description=&quot;sofia Endpoint&quot;&gt;<br>          &lt;global_settings&gt;<br>            &lt;param name=&quot;log-level&quot; value=&quot;0&quot;/&gt;<br>            &lt;param name=&quot;abort-on-empty-external-ip&quot; value=&quot;true&quot;/&gt;<br>            &lt;param name=&quot;auto-restart&quot; value=&quot;false&quot;/&gt;<br>          &lt;/global_settings&gt;<br><br>          &lt;profiles&gt;<br>            &lt;profile name=&quot;external&quot;&gt;<br>              &lt;gateways&gt;<br>                &lt;!-- SIP provider gateway configuration --&gt;<br>                &lt;gateway name=&quot;restaurant-sip&quot;&gt;<br>                  &lt;param name=&quot;username&quot; value=&quot;${SIP_USERNAME}&quot;/&gt;<br>                  &lt;param name=&quot;password&quot; value=&quot;${SIP_PASSWORD}&quot;/&gt;<br>                  &lt;param name=&quot;realm&quot; value=&quot;${SIP_REALM}&quot;/&gt;<br>                  &lt;param name=&quot;proxy&quot; value=&quot;${SIP_PROXY}&quot;/&gt;<br>                  &lt;param name=&quot;register&quot; value=&quot;true&quot;/&gt;<br>                  &lt;param name=&quot;expire-seconds&quot; value=&quot;600&quot;/&gt;<br>                  &lt;param name=&quot;retry-seconds&quot; value=&quot;30&quot;/&gt;<br>                &lt;/gateway&gt;<br>              &lt;/gateways&gt;<br><br>              &lt;settings&gt;<br>                &lt;param name=&quot;context&quot; value=&quot;public&quot;/&gt;<br>                &lt;param name=&quot;rfc2833-pt&quot; value=&quot;101&quot;/&gt;<br>                &lt;param name=&quot;sip-port&quot; value=&quot;5060&quot;/&gt;<br>                &lt;param name=&quot;dialplan&quot; value=&quot;XML&quot;/&gt;<br>                &lt;param name=&quot;dtmf-duration&quot; value=&quot;2000&quot;/&gt;<br>                &lt;param name=&quot;codec-prefs&quot; value=&quot;G722,opus@48000h@20i,PCMA,PCMU,GSM&quot;/&gt;<br>                &lt;param name=&quot;use-rtp-timer&quot; value=&quot;true&quot;/&gt;<br>                &lt;param name=&quot;rtp-timer-name&quot; value=&quot;soft&quot;/&gt;<br>                &lt;param name=&quot;manage-presence&quot; value=&quot;false&quot;/&gt;<br>                &lt;param name=&quot;inbound-codec-negotiation&quot; value=&quot;generous&quot;/&gt;<br>                &lt;param name=&quot;nonce-ttl&quot; value=&quot;60&quot;/&gt;<br>                &lt;param name=&quot;auth-calls&quot; value=&quot;false&quot;/&gt;<br>                &lt;param name=&quot;inbound-late-negotiation&quot; value=&quot;true&quot;/&gt;<br>                &lt;param name=&quot;inbound-zrtp-passthru&quot; value=&quot;true&quot;/&gt;<br>                &lt;param name=&quot;rtp-ip&quot; value=&quot;auto-nat&quot;/&gt;<br>                &lt;param name=&quot;sip-ip&quot; value=&quot;auto-nat&quot;/&gt;<br>                &lt;param name=&quot;ext-rtp-ip&quot; value=&quot;auto-nat&quot;/&gt;<br>                &lt;param name=&quot;ext-sip-ip&quot; value=&quot;auto-nat&quot;/&gt;<br>                &lt;param name=&quot;rtp-timeout-sec&quot; value=&quot;300&quot;/&gt;<br>                &lt;param name=&quot;rtp-hold-timeout-sec&quot; value=&quot;1800&quot;/&gt;<br>                &lt;param name=&quot;minimum-session-expires&quot; value=&quot;120&quot;/&gt;<br>                &lt;param name=&quot;apply-nat-acl&quot; value=&quot;nat.auto&quot;/&gt;<br>                &lt;param name=&quot;aggressive-nat-detection&quot; value=&quot;true&quot;/&gt;<br>              &lt;/settings&gt;<br>            &lt;/profile&gt;<br>          &lt;/profiles&gt;<br>        &lt;/configuration&gt;<br><br>        &lt;!-- Switch Configuration --&gt;<br>        &lt;configuration name=&quot;switch.conf&quot; description=&quot;Core Configuration&quot;&gt;<br>          &lt;settings&gt;<br>            &lt;param name=&quot;colorize-console&quot; value=&quot;true&quot;/&gt;<br>            &lt;param name=&quot;max-sessions&quot; value=&quot;1000&quot;/&gt;<br>            &lt;param name=&quot;sessions-per-second&quot; value=&quot;30&quot;/&gt;<br>            &lt;param name=&quot;loglevel&quot; value=&quot;info&quot;/&gt;<br>            &lt;param name=&quot;dump-cores&quot; value=&quot;yes&quot;/&gt;<br>          &lt;/settings&gt;<br>        &lt;/configuration&gt;<br><br>      &lt;/section&gt;<br><br>      &lt;!-- Dialplan for routing calls to LiveKit --&gt;<br>      &lt;section name=&quot;dialplan&quot; description=&quot;Regex/XML Dialplan&quot;&gt;<br>        &lt;context name=&quot;public&quot;&gt;<br><br>          &lt;!-- Route incoming calls to restaurant assistant --&gt;<br>          &lt;extension name=&quot;restaurant-assistant&quot;&gt;<br>            &lt;condition field=&quot;destination_number&quot; expression=&quot;^(restaurant|${RESTAURANT_PHONE_NUMBER})$&quot;&gt;<br>              &lt;action application=&quot;answer&quot;/&gt;<br>              &lt;action application=&quot;sleep&quot; data=&quot;1000&quot;/&gt;<br>              &lt;action application=&quot;set&quot; data=&quot;call_direction=inbound&quot;/&gt;<br>              &lt;action application=&quot;set&quot; data=&quot;restaurant_call=true&quot;/&gt;<br>              &lt;!-- This will be handled by LiveKit SIP integration --&gt;<br>              &lt;action application=&quot;socket&quot; data=&quot;backend-service:8000 async full&quot;/&gt;<br>            &lt;/condition&gt;<br>          &lt;/extension&gt;<br><br>          &lt;!-- Default handler for unmatched calls --&gt;<br>          &lt;extension name=&quot;unmatched&quot;&gt;<br>            &lt;condition field=&quot;destination_number&quot; expression=&quot;^.*$&quot;&gt;<br>              &lt;action application=&quot;answer&quot;/&gt;<br>              &lt;action application=&quot;playback&quot; data=&quot;tone_stream://%(400,200,400,450);%(400,2000,400,450)&quot;/&gt;<br>              &lt;action application=&quot;hangup&quot;/&gt;<br>            &lt;/condition&gt;<br>          &lt;/extension&gt;<br><br>        &lt;/context&gt;<br>      &lt;/section&gt;<br><br>    &lt;/document&gt;<br><br>  vars.xml: |<br>    &lt;?xml version=&quot;1.0&quot;?&gt;<br>    &lt;include&gt;<br>      &lt;!-- FreeSWITCH Variables for Restaurant AI --&gt;<br><br>      &lt;!-- Network settings --&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;default_password=${FREESWITCH_DEFAULT_PASSWORD}&quot;/&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;domain=${FREESWITCH_DOMAIN}&quot;/&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;domain_name=${FREESWITCH_DOMAIN}&quot;/&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;hold_music=${FREESWITCH_HOLD_MUSIC}&quot;/&gt;<br><br>      &lt;!-- SIP settings --&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;external_rtp_ip=auto-nat&quot;/&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;external_sip_ip=auto-nat&quot;/&gt;<br><br>      &lt;!-- Codec preferences --&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;global_codec_prefs=G722,opus@48000h@20i,PCMA,PCMU,GSM&quot;/&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;outbound_codec_prefs=G722,opus@48000h@20i,PCMA,PCMU,GSM&quot;/&gt;<br><br>      &lt;!-- Restaurant specific --&gt;<br>      &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;restaurant_name=${RESTAURANT_NAME}&quot;/&gt;<br><br>    &lt;/include&gt;</pre><p>We are using a pipe instead of creating files. This will help in managing even though its sensitive it does make for an easier manage.</p><p>Okay we will also need a place to call it. <em>deployment.yaml. </em>If you look carefully you will notice the reference to secrets, global config maps and mounting of the freeswitch specific config.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: freeswitch-deployment<br>  namespace: vocare-restaurant<br>  labels:<br>    app: freeswitch-server<br>spec:<br>  replicas: 1  # FreeSWITCH typically runs as single instance<br>  selector:<br>    matchLabels:<br>      app: freeswitch-server<br>  template:<br>    metadata:<br>      labels:<br>        app: freeswitch-server<br>    spec:<br>      # Security context for FreeSWITCH capabilities<br>      securityContext:<br>        fsGroup: 1000<br>      containers:<br>      - name: freeswitch-server<br>        image: safarov/freeswitch:latest<br>        ports:<br>        - containerPort: 5060<br>          name: sip-udp<br>          protocol: UDP<br>        - containerPort: 5080<br>          name: sip-alt-udp<br>          protocol: UDP<br>        - containerPort: 8021<br>          name: event-socket<br>          protocol: TCP<br>        # RTP port range - this is a challenge in Kubernetes<br>        # Consider using a smaller range or NodePort services<br>        env:<br>        - name: SOUND_RATES<br>          value: &quot;8000,16000&quot;<br>        - name: SOUND_TYPES<br>          value: &quot;wav&quot;<br>        - name: FREESWITCH_LOG_LEVEL<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: FREESWITCH_LOG_LEVEL<br>        - name: FREESWITCH_DEFAULT_PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-freeswitch-secrets<br>              key: default-password<br>        - name: FREESWITCH_DOMAIN<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: FREESWITCH_DOMAIN<br>        - name: FREESWITCH_HOLD_MUSIC<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: FREESWITCH_HOLD_MUSIC<br>        - name: RESTAURANT_NAME<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: RESTAURANT_NAME<br>        - name: FREESWITCH_EXTERNAL_RTP_PORT_MIN<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: FREESWITCH_EXTERNAL_RTP_PORT_MIN<br>        - name: FREESWITCH_EXTERNAL_RTP_PORT_MAX<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: FREESWITCH_EXTERNAL_RTP_PORT_MAX<br>        # LiveKit integration<br>        - name: LIVEKIT_URL<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: LIVEKIT_URL<br>        - name: LIVEKIT_API_KEY<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: livekit-api-key<br>        - name: LIVEKIT_API_SECRET<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: livekit-api-secret<br>        # SIP provider configuration<br>        - name: SIP_USERNAME<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-sip-secrets<br>              key: sip-username<br>        - name: SIP_PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-sip-secrets<br>              key: sip-password<br>        - name: SIP_REALM<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-sip-secrets<br>              key: sip-realm<br>        - name: SIP_PROXY<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-sip-secrets<br>              key: sip-proxy<br>        volumeMounts:<br>        - name: freeswitch-config<br>          mountPath: /etc/freeswitch<br>          readOnly: true<br>        resources:<br>          requests:<br>            memory: &quot;256Mi&quot;<br>            cpu: &quot;200m&quot;<br>          limits:<br>            memory: &quot;512Mi&quot;<br>            cpu: &quot;500m&quot;<br>        # Security context for capabilities<br>        securityContext:<br>          capabilities:<br>            add:<br>            - SYS_NICE<br>          # Note: privileged: true might be needed for full FreeSWITCH functionality<br>          # privileged: true<br>        livenessProbe:<br>          tcpSocket:<br>            port: 8021<br>          initialDelaySeconds: 30<br>          periodSeconds: 10<br>        readinessProbe:<br>          tcpSocket:<br>            port: 8021<br>          initialDelaySeconds: 10<br>          periodSeconds: 5<br>      volumes:<br>      - name: freeswitch-config<br>        configMap:<br>          name: freeswitch-config</pre><p>Now that our deployment is ready we need a service to manage the deployment and make it accessible to the world and for this the <em>service.yaml</em> will handle this. You will realise this by seeing the ports. Also due to the nature of real time communication in this regard, FreeSwitch which makes use of RTP, a lot of ports are needed just for sending and receiving in some cases from 10000–20000, 30000–31000. We simply can’t do this by hand so we pick the one’s we can by hand. But we can handle this better for production cases, NodePort: ANodePort service exposes your service on a static port on <em>each Node&#39;s IP address</em> in the cluster. It will allow us to set a port range and therefore not have to worry about setting it manually. External traffic destined for NodeIP:NodePort is then routed to the Freeswitch pods. If you change anything in the nodeport you will have to change it everywhere.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: freeswitch-service<br>  namespace: vocare-restaurant<br>  labels:<br>    app: freeswitch-server<br>  annotations:<br>    service.beta.kubernetes.io/azure-load-balancer-external-subnet: &quot;default&quot;<br>spec:<br>  selector:<br>    app: freeswitch-server<br>  ports:<br>  - name: sip-udp<br>    port: 5060<br>    targetPort: 5060<br>    protocol: UDP<br>  - name: sip-alt-udp<br>    port: 5080<br>    targetPort: 5080<br>    protocol: UDP<br>  - name: event-socket<br>    port: 8021<br>    targetPort: 8021<br>    protocol: TCP<br>  type: LoadBalancer<br><br>---<br># RTP Media Service - This is challenging due to port range requirements<br># Consider using NodePort or multiple services for RTP ports<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: freeswitch-rtp-service<br>  namespace: vocare-restaurant<br>  labels:<br>    app: freeswitch-server<br>  annotations:<br>    service.beta.kubernetes.io/azure-load-balancer-external-subnet: &quot;default&quot;<br>spec:<br>  selector:<br>    app: freeswitch-server<br>  ports:<br>  # RTP port range - this is a simplified version<br>  # In production, you might need multiple services or NodePort<br>  - name: rtp-30000<br>    port: 30000<br>    targetPort: 30000<br>    protocol: UDP<br>  - name: rtp-30001<br>    port: 30001<br>    targetPort: 30001<br>    protocol: UDP<br>  - name: rtp-30002<br>    port: 30002<br>    targetPort: 30002<br>    protocol: UDP<br>  - name: rtp-30003<br>    port: 30003<br>    targetPort: 30003<br>    protocol: UDP<br>  - name: rtp-30004<br>    port: 30004<br>    targetPort: 30004<br>    protocol: UDP<br>  - name: rtp-30005<br>    port: 30005<br>    targetPort: 30005<br>    protocol: UDP<br>  - name: rtp-30006<br>    port: 30006<br>    targetPort: 30006<br>    protocol: UDP<br>  - name: rtp-30007<br>    port: 30007<br>    targetPort: 30007<br>    protocol: UDP<br>  - name: rtp-30008<br>    port: 30008<br>    targetPort: 30008<br>    protocol: UDP<br>  - name: rtp-30009<br>    port: 30009<br>    targetPort: 30009<br>    protocol: UDP<br>  - name: rtp-30010<br>    port: 30010<br>    targetPort: 30010<br>    protocol: UDP<br>  type: LoadBalancer<br><br>---<br># Internal service for cluster communication<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: freeswitch-internal<br>  namespace: vocare-restaurant<br>  labels:<br>    app: freeswitch-server<br>spec:<br>  selector:<br>    app: freeswitch-server<br>  ports:<br>  - name: event-socket<br>    port: 8021<br>    targetPort: 8021<br>    protocol: TCP<br>  type: ClusterIP</pre><p>Now since we have the basics understood, we can now set up Livekit which is basically the same thing only that its for Livekit.</p><p><em>deployment.yaml</em></p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: livekit-deployment<br>  namespace: vocare-restaurant<br>  labels:<br>    app: livekit-server<br>spec:<br>  replicas: 1  # LiveKit typically runs as single instance<br>  selector:<br>    matchLabels:<br>      app: livekit-server<br>  template:<br>    metadata:<br>      labels:<br>        app: livekit-server<br>    spec:<br>      containers:<br>      - name: livekit-server<br>        image: livekit/livekit-server:latest<br>        ports:<br>        - containerPort: 7880<br>          name: websocket<br>        - containerPort: 7881<br>          name: websocket-tls<br>        - containerPort: 7882<br>          name: turn-udp<br>          protocol: UDP<br>        env:<br>        - name: LIVEKIT_CONFIG<br>          value: &quot;/etc/livekit.yaml&quot;<br>        - name: LIVEKIT_KEYS<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: livekit-api-key<br>        - name: LIVEKIT_SECRET<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: livekit-api-secret<br>        volumeMounts:<br>        - name: livekit-config<br>          mountPath: /etc/livekit.yaml<br>          subPath: livekit.yaml<br>          readOnly: true<br>        resources:<br>          requests:<br>            memory: &quot;256Mi&quot;<br>            cpu: &quot;200m&quot;<br>          limits:<br>            memory: &quot;512Mi&quot;<br>            cpu: &quot;500m&quot;<br>        livenessProbe:<br>          httpGet:<br>            path: /<br>            port: 7880<br>          initialDelaySeconds: 30<br>          periodSeconds: 10<br>        readinessProbe:<br>          httpGet:<br>            path: /<br>            port: 7880<br>          initialDelaySeconds: 5<br>          periodSeconds: 5<br>      volumes:<br>      - name: livekit-config<br>        configMap:<br>          name: livekit-config</pre><p><em>service.yaml</em></p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: livekit-service<br>  namespace: vocare-restaurant<br>  labels:<br>    app: livekit-server<br>  annotations:<br>    service.beta.kubernetes.io/azure-load-balancer-external-subnet: &quot;default&quot;<br>spec:<br>  selector:<br>    app: livekit-server<br>  ports:<br>  - name: websocket<br>    port: 7880<br>    targetPort: 7880<br>    protocol: TCP<br>  - name: websocket-tls<br>    port: 7881<br>    targetPort: 7881<br>    protocol: TCP<br>  - name: turn-udp<br>    port: 7882<br>    targetPort: 7882<br>    protocol: UDP<br>  type: LoadBalancer<br><br>---<br># Internal service for cluster communication<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: livekit-internal<br>  namespace: vocare-restaurant<br>  labels:<br>    app: livekit-server<br>spec:<br>  selector:<br>    app: livekit-server<br>  ports:<br>  - name: websocket<br>    port: 7880<br>    targetPort: 7880<br>    protocol: TCP<br>  type: ClusterIP</pre><p>Now for our backend, we will need to be slightly more careful since we are calling the image and more stuff is going on. Make sure to reference the right image and don’t just copy paste. You can always update it using kubectl but the errors you get aren’t always clear and it will be hard to know where the error is coming from. Alot of reference from key vault.</p><pre># Backend Deployment with Azure Key Vault Integration<br># This version uses Azure Key Vault Secrets Provider for enhanced security<br><br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: backend-deployment<br>  namespace: vocare-restaurant<br>  labels:<br>    app: vocare-backend<br>    version: keyvault<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: vocare-backend<br><br>  template:<br>    metadata:<br>      labels:<br>        app: vocare-backend<br><br>    spec:<br>      serviceAccountName: vocare-workload-identity  # For Azure Workload Identity<br>      containers:<br>      - name: vocare-backend<br>        image: &quot;vocareacr.azurecr.io/vocare-backend:latest&quot;<br>        ports:<br>        - containerPort: 8000<br>          name: freeswitch-api<br>        - containerPort: 8081<br>          name: livekit-agent<br>        env:<br>        # API Keys from Azure Key Vault (via auto-created Kubernetes secrets)<br>        - name: OPENAI_API_KEY<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: openai-api-key<br>        - name: DEEPGRAM_API_KEY<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: deepgram-api-key<br>        - name: CARTESIA_API_KEY<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: cartesia-api-key<br>        - name: LIVEKIT_API_KEY<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: livekit-api-key<br>        - name: LIVEKIT_API_SECRET<br>          valueFrom:<br>            secretKeyRef:<br>              name: vocare-api-secrets<br>              key: livekit-api-secret<br>        # Configuration from ConfigMap<br>        - name: OPENAI_MODEL<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: OPENAI_MODEL<br>        - name: FIREBASE_SERVICE_ACCOUNT_PATH<br>          value: &quot;/mnt/secrets-store/firebase-service-account-json&quot;<br>        - name: LIVEKIT_URL<br>          valueFrom:<br>            configMapKeyRef:<br>              name: vocare-config<br>              key: LIVEKIT_URL<br>        volumeMounts:<br>        - name: keyvault-secrets<br>          mountPath: /mnt/secrets-store<br>          readOnly: true<br>        resources:<br>          requests:<br>            memory: &quot;512Mi&quot;<br>            cpu: &quot;250m&quot;<br>          limits:<br>            memory: &quot;1Gi&quot;<br>            cpu: &quot;500m&quot;<br>        livenessProbe:<br>          httpGet:<br>            path: /health<br>            port: 8000<br>          initialDelaySeconds: 30<br>          periodSeconds: 10<br>        readinessProbe:<br>          httpGet:<br>            path: /ready<br>            port: 8000<br>          initialDelaySeconds: 5<br>          periodSeconds: 5<br>        securityContext:<br>          allowPrivilegeEscalation: false<br>          runAsNonRoot: true<br>          runAsUser: 1000<br>          capabilities:<br>            drop:<br>            - ALL<br>      volumes:<br>      - name: keyvault-secrets<br>        csi:<br>          driver: secrets-store.csi.k8s.io<br>          readOnly: true<br>          volumeAttributes:<br>            secretProviderClass: vocare-keyvault-secrets</pre><p>The backend service yaml.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: backend-service<br>  namespace: vocare-restaurant<br>  labels:<br>    app: vocare-backend<br>spec:<br>  selector:<br>    app: vocare-backend<br>  ports:<br>  - name: freeswitch-api<br>    port: 8000<br>    targetPort: 8000<br>    protocol: TCP<br>  - name: livekit-agent<br>    port: 8081<br>    targetPort: 8081<br>    protocol: TCP<br>  type: ClusterIP</pre><p>You can then apply all of these deployment and you will be good to go.</p><pre>kubectl apply -f freeswitch/configmap.yaml<br>kubectl apply -f freeswitch/deployment.yaml<br>kubectl apply -f freeswitch/service.yaml<br><br>kubectl apply -f livekit/deployment.yaml<br>kubectl apply -f livekit/service.yaml<br><br>kubectl apply -f backend/deployment.yaml<br>kubectl apply -f backend/service.yaml</pre><p>Once complete, check whether for the status of the deployed resources. Make sure all deployments are ready. You can always wait</p><pre>kubectl get all -n vocare-restaurant</pre><h3>Monitoring</h3><p>So after successfully deploying we need to set up basic monitoring. Go to the App insights. You will get the instrumentation key and connection string to get data on our services.</p><p>You can then use them to create this config to apply to the app.</p><pre># Azure Monitor and Application Insights configuration<br># This enables monitoring and observability for the Vocare Restaurant Assistant<br><br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: azure-monitor-config<br>  namespace: vocare-restaurant<br>data:<br>  # Application Insights configuration<br>  APPLICATIONINSIGHTS_CONNECTION_STRING: &quot;Your connection string here&quot;<br>  APPINSIGHTS_INSTRUMENTATIONKEY: &quot;Your key here&quot;<br><br>  # Azure Monitor configuration<br>  AZURE_LOG_ANALYTICS_WORKSPACE_ID: &quot;WKSP ID here&quot;<br>  AZURE_LOG_ANALYTICS_WORKSPACE_KEY: &quot;Your key here&quot;<br><br>---<br># ServiceMonitor for Prometheus scraping (if using Azure Monitor for Prometheus)<br>apiVersion: monitoring.coreos.com/v1<br>kind: ServiceMonitor<br>metadata:<br>  name: vocare-backend-monitor<br>  namespace: vocare-restaurant<br>  labels:<br>    app: vocare-backend<br>spec:<br>  selector:<br>    matchLabels:<br>      app: vocare-backend<br>  endpoints:<br>  - port: metrics<br>    interval: 30s<br>    path: /metrics<br><br>---<br># ServiceMonitor for LiveKit<br>apiVersion: monitoring.coreos.com/v1<br>kind: ServiceMonitor<br>metadata:<br>  name: livekit-monitor<br>  namespace: vocare-restaurant<br>  labels:<br>    app: livekit-server<br>spec:<br>  selector:<br>    matchLabels:<br>      app: livekit-server<br>  endpoints:<br>  - port: metrics<br>    interval: 30s<br>    path: /metrics<br><br>---<br># ServiceMonitor for FreeSWITCH<br>apiVersion: monitoring.coreos.com/v1<br>kind: ServiceMonitor<br>metadata:<br>  name: freeswitch-monitor<br>  namespace: vocare-restaurant<br>  labels:<br>    app: freeswitch-server<br>spec:<br>  selector:<br>    matchLabels:<br>      app: freeswitch-server<br>  endpoints:<br>  - port: metrics<br>    interval: 30s<br>    path: /metrics<br><br>---<br># PrometheusRule for alerting<br>apiVersion: monitoring.coreos.com/v1<br>kind: PrometheusRule<br>metadata:<br>  name: vocare-alerts<br>  namespace: vocare-restaurant<br>  labels:<br>    app: vocare-restaurant<br>spec:<br>  groups:<br>  - name: vocare.rules<br>    rules:<br>    - alert: VocareBackendDown<br>      expr: up{job=&quot;vocare-backend&quot;} == 0<br>      for: 1m<br>      labels:<br>        severity: critical<br>      annotations:<br>        summary: &quot;Vocare Backend is down&quot;<br>        description: &quot;Vocare Backend has been down for more than 1 minute.&quot;<br><br>    - alert: LiveKitDown<br>      expr: up{job=&quot;livekit-server&quot;} == 0<br>      for: 1m<br>      labels:<br>        severity: critical<br>      annotations:<br>        summary: &quot;LiveKit server is down&quot;<br>        description: &quot;LiveKit server has been down for more than 1 minute.&quot;<br><br>    - alert: FreeSWITCHDown<br>      expr: up{job=&quot;freeswitch-server&quot;} == 0<br>      for: 1m<br>      labels:<br>        severity: critical<br>      annotations:<br>        summary: &quot;FreeSWITCH server is down&quot;<br>        description: &quot;FreeSWITCH server has been down for more than 1 minute.&quot;<br><br>    - alert: HighCPUUsage<br>      expr: rate(container_cpu_usage_seconds_total{namespace=&quot;vocare-restaurant&quot;}[5m]) &gt; 0.8<br>      for: 5m<br>      labels:<br>        severity: warning<br>      annotations:<br>        summary: &quot;High CPU usage detected&quot;<br>        description: &quot;CPU usage is above 80% for more than 5 minutes.&quot;<br><br>    - alert: HighMemoryUsage<br>      expr: container_memory_usage_bytes{namespace=&quot;vocare-restaurant&quot;} / container_spec_memory_limit_bytes &gt; 0.9<br>      for: 5m<br>      labels:<br>        severity: warning<br>      annotations:<br>        summary: &quot;High memory usage detected&quot;<br>        description: &quot;Memory usage is above 90% for more than 5 minutes.&quot;</pre><p>To manage the cluster resources. Please set up the following. But ensure you match it to your needs. It ensures that the application doesn&#39;t exceed a particular quota even when auto scaling and keep you within budget.</p><pre># Production Resource Quotas and Limits<br># These ensure proper resource allocation and prevent resource exhaustion<br><br>apiVersion: v1<br>kind: ResourceQuota<br>metadata:<br>  name: vocare-resource-quota<br>  namespace: vocare-restaurant<br>spec:<br>  hard:<br>    # Compute resources<br>    requests.cpu: &quot;4&quot;<br>    requests.memory: 8Gi<br>    limits.cpu: &quot;8&quot;<br>    limits.memory: 16Gi<br><br>    # Storage resources<br>    requests.storage: 100Gi<br>    persistentvolumeclaims: &quot;10&quot;<br><br>    # Object counts<br>    pods: &quot;20&quot;<br>    services: &quot;10&quot;<br>    secrets: &quot;20&quot;<br>    configmaps: &quot;20&quot;<br><br>    # Load balancers (expensive in Azure)<br>    services.loadbalancers: &quot;3&quot;<br><br>---<br># Limit Range for individual pods<br>apiVersion: v1<br>kind: LimitRange<br>metadata:<br>  name: vocare-limit-range<br>  namespace: vocare-restaurant<br>spec:<br>  limits:<br>  - type: Container<br>    default:<br>      cpu: 500m<br>      memory: 512Mi<br>    defaultRequest:<br>      cpu: 100m<br>      memory: 128Mi<br>    max:<br>      cpu: &quot;2&quot;<br>      memory: 2Gi<br>    min:<br>      cpu: 50m<br>      memory: 64Mi<br>  - type: Pod<br>    max:<br>      cpu: &quot;4&quot;<br>      memory: 4Gi<br>  - type: PersistentVolumeClaim<br>    max:<br>      storage: 50Gi<br>    min:<br>      storage: 1Gi<br><br>---<br># Pod Disruption Budget for Backend<br>apiVersion: policy/v1<br>kind: PodDisruptionBudget<br>metadata:<br>  name: backend-pdb<br>  namespace: vocare-restaurant<br>spec:<br>  minAvailable: 1<br>  selector:<br>    matchLabels:<br>      app: vocare-backend<br><br>---<br># Pod Disruption Budget for LiveKit<br>apiVersion: policy/v1<br>kind: PodDisruptionBudget<br>metadata:<br>  name: livekit-pdb<br>  namespace: vocare-restaurant<br>spec:<br>  minAvailable: 1<br>  selector:<br>    matchLabels:<br>      app: livekit-server<br><br>---<br># Pod Disruption Budget for FreeSWITCH<br>apiVersion: policy/v1<br>kind: PodDisruptionBudget<br>metadata:<br>  name: freeswitch-pdb<br>  namespace: vocare-restaurant<br>spec:<br>  minAvailable: 1<br>  selector:<br>    matchLabels:<br>      app: freeswitch-server<br><br>---<br># Priority Classes for workload prioritization<br>apiVersion: scheduling.k8s.io/v1<br>kind: PriorityClass<br>metadata:<br>  name: vocare-critical<br>value: 1000<br>globalDefault: false<br>description: &quot;Critical priority class for essential Vocare services&quot;<br><br>---<br>apiVersion: scheduling.k8s.io/v1<br>kind: PriorityClass<br>metadata:<br>  name: vocare-high<br>value: 500<br>globalDefault: false<br>description: &quot;High priority class for important Vocare services&quot;<br><br>---<br>apiVersion: scheduling.k8s.io/v1<br>kind: PriorityClass<br>metadata:<br>  name: vocare-normal<br>value: 100<br>globalDefault: true<br>description: &quot;Normal priority class for standard Vocare services&quot;</pre><h3>Autoscaler</h3><p>To be specific the VPA (Vertical Pod Autoscaler) is designed to <strong>automatically adjust the CPU and memory requests and limits for the pods</strong> based on their actual resource usage over time. <br>It will observe the actual CPU and memory usage of the running pods. Based on this historical data and current trends, it will intelligently <strong>recommend</strong> optimal requests and limits for the containers.<br>So we run the following.</p><pre>kubectl apply -f https://raw.githubusercontent.com/kubernetes/autoscaler/vpa-release-1.0/vertical-pod-autoscaler/deploy/vpa-v1-crd-gen.yaml<br>kubectl apply -f https://raw.githubusercontent.com/kubernetes/autoscaler/vpa-release-1.0/vertical-pod-autoscaler/deploy/vpa-rbac.yaml</pre><h3>Security</h3><p>We need security policies to keep the line secure from hackers and bots.</p><pre># Production Security Policies<br># Enhanced security configurations for production deployment<br><br># Pod Security Standards - Restricted profile for most workloads<br>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: vocare-restaurant<br>  labels:<br>    pod-security.kubernetes.io/enforce: restricted<br>    pod-security.kubernetes.io/audit: restricted<br>    pod-security.kubernetes.io/warn: restricted<br>    app: vocare-restaurant<br>    environment: production<br><br>---<br># Security Context Constraints for FreeSWITCH (requires elevated privileges)<br>apiVersion: v1<br>kind: Namespace<br>metadata:<br>  name: vocare-telephony<br>  labels:<br>    pod-security.kubernetes.io/enforce: baseline<br>    pod-security.kubernetes.io/audit: baseline<br>    pod-security.kubernetes.io/warn: baseline<br>    app: vocare-restaurant<br>    environment: production<br>    workload-type: telephony<br><br>---<br># Network Policy - Default Deny All<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: default-deny-all<br>  namespace: vocare-restaurant<br>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Ingress<br>  - Egress<br><br>---<br># Network Policy - Allow DNS<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-dns<br>  namespace: vocare-restaurant<br>spec:<br>  podSelector: {}<br>  policyTypes:<br>  - Egress<br>  egress:<br>  - to: []<br>    ports:<br>    - protocol: UDP<br>      port: 53<br>    - protocol: TCP<br>      port: 53<br><br>---<br># Network Policy - Allow external HTTPS for API calls<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: allow-external-https<br>  namespace: vocare-restaurant<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: vocare-backend<br>  policyTypes:<br>  - Egress<br>  egress:<br>  - to: []<br>    ports:<br>    - protocol: TCP<br>      port: 443<br>    - protocol: TCP<br>      port: 80<br><br>---<br># RBAC - Service Account for backend<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: vocare-backend-sa<br>  namespace: vocare-restaurant<br>  annotations:<br>    azure.workload.identity/client-id: &quot;REPLACE_WITH_MANAGED_IDENTITY_CLIENT_ID&quot;<br>  labels:<br>    azure.workload.identity/use: &quot;true&quot;<br>automountServiceAccountToken: false<br><br>---<br># RBAC - Role for backend service<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  name: vocare-backend-role<br>  namespace: vocare-restaurant<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;configmaps&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;secrets&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;pods&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]<br><br>---<br># RBAC - RoleBinding<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: vocare-backend-binding<br>  namespace: vocare-restaurant<br>subjects:<br>- kind: ServiceAccount<br>  name: vocare-backend-sa<br>  namespace: vocare-restaurant<br>roleRef:<br>  kind: Role<br>  name: vocare-backend-role<br>  apiGroup: rbac.authorization.k8s.io<br><br>---<br># Security Context for Backend Pods<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: security-contexts<br>  namespace: vocare-restaurant<br>data:<br>  backend-security-context.yaml: |<br>    securityContext:<br>      runAsNonRoot: true<br>      runAsUser: 1000<br>      runAsGroup: 1000<br>      fsGroup: 1000<br>      seccompProfile:<br>        type: RuntimeDefault<br>      capabilities:<br>        drop:<br>        - ALL<br>      allowPrivilegeEscalation: false<br>      readOnlyRootFilesystem: true<br><br>  livekit-security-context.yaml: |<br>    securityContext:<br>      runAsNonRoot: true<br>      runAsUser: 1001<br>      runAsGroup: 1001<br>      fsGroup: 1001<br>      seccompProfile:<br>        type: RuntimeDefault<br>      capabilities:<br>        drop:<br>        - ALL<br>      allowPrivilegeEscalation: false<br>      readOnlyRootFilesystem: false  # LiveKit needs write access<br><br>  freeswitch-security-context.yaml: |<br>    securityContext:<br>      runAsNonRoot: false  # FreeSWITCH may need root for some operations<br>      runAsUser: 0<br>      runAsGroup: 0<br>      fsGroup: 1000<br>      seccompProfile:<br>        type: RuntimeDefault<br>      capabilities:<br>        add:<br>        - SYS_NICE  # Required for FreeSWITCH<br>        drop:<br>        - ALL<br>      allowPrivilegeEscalation: true  # Required for FreeSWITCH</pre><p>and finally we need to ensure we set up network policies for our services.</p><pre># Network Policies for Vocare Restaurant Assistant<br># These policies control traffic flow between services for security<br><br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: backend-network-policy<br>  namespace: vocare-restaurant<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: vocare-backend<br>  policyTypes:<br>  - Ingress<br>  - Egress<br>  ingress:<br>  # Allow traffic from LiveKit<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          app: livekit-server<br>    ports:<br>    - protocol: TCP<br>      port: 8000<br>  # Allow traffic from FreeSWITCH<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          app: freeswitch-server<br>    ports:<br>    - protocol: TCP<br>      port: 8000<br>  egress:<br>  # Allow outbound to LiveKit<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: livekit-server<br>    ports:<br>    - protocol: TCP<br>      port: 7880<br>  # Allow outbound to FreeSWITCH<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: freeswitch-server<br>    ports:<br>    - protocol: TCP<br>      port: 8021<br>  # Allow outbound to external APIs (OpenAI, Deepgram, etc.)<br>  - to: []<br>    ports:<br>    - protocol: TCP<br>      port: 443<br>    - protocol: TCP<br>      port: 80<br>  # Allow DNS<br>  - to: []<br>    ports:<br>    - protocol: UDP<br>      port: 53<br><br>---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: livekit-network-policy<br>  namespace: vocare-restaurant<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: livekit-server<br>  policyTypes:<br>  - Ingress<br>  - Egress<br>  ingress:<br>  # Allow external WebSocket connections<br>  - from: []<br>    ports:<br>    - protocol: TCP<br>      port: 7880<br>    - protocol: TCP<br>      port: 7881<br>    - protocol: UDP<br>      port: 7882<br>  # Allow traffic from backend<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          app: vocare-backend<br>    ports:<br>    - protocol: TCP<br>      port: 7880<br>  egress:<br>  # Allow outbound to backend for webhooks<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: vocare-backend<br>    ports:<br>    - protocol: TCP<br>      port: 8000<br>  # Allow DNS<br>  - to: []<br>    ports:<br>    - protocol: UDP<br>      port: 53<br><br>---<br>apiVersion: networking.k8s.io/v1<br>kind: NetworkPolicy<br>metadata:<br>  name: freeswitch-network-policy<br>  namespace: vocare-restaurant<br>spec:<br>  podSelector:<br>    matchLabels:<br>      app: freeswitch-server<br>  policyTypes:<br>  - Ingress<br>  - Egress<br>  ingress:<br>  # Allow external SIP traffic<br>  - from: []<br>    ports:<br>    - protocol: UDP<br>      port: 5060<br>    - protocol: UDP<br>      port: 5080<br>  # Allow RTP traffic (simplified range)<br>  - from: []<br>    ports:<br>    - protocol: UDP<br>      port: 30000<br>    - protocol: UDP<br>      port: 30001<br>    - protocol: UDP<br>      port: 30002<br>    - protocol: UDP<br>      port: 30003<br>    - protocol: UDP<br>      port: 30004<br>    - protocol: UDP<br>      port: 30005<br>    - protocol: UDP<br>      port: 30006<br>    - protocol: UDP<br>      port: 30007<br>    - protocol: UDP<br>      port: 30008<br>    - protocol: UDP<br>      port: 30009<br>    - protocol: UDP<br>      port: 30010<br>  # Allow traffic from backend<br>  - from:<br>    - podSelector:<br>        matchLabels:<br>          app: vocare-backend<br>    ports:<br>    - protocol: TCP<br>      port: 8021<br>  egress:<br>  # Allow outbound to backend<br>  - to:<br>    - podSelector:<br>        matchLabels:<br>          app: vocare-backend<br>    ports:<br>    - protocol: TCP<br>      port: 8000<br>  # Allow outbound SIP registration<br>  - to: []<br>    ports:<br>    - protocol: UDP<br>      port: 5060<br>    - protocol: TCP<br>      port: 5060<br>  # Allow DNS<br>  - to: []<br>    ports:<br>    - protocol: UDP<br>      port: 53</pre><h3>Conclusion</h3><p>This deployment has been a lot I hop you have at least had fun configuring and getting to know a little on devops. There’s so much I haven’t added in for example connecting our domain to the servers, creating helm package for this to ensure everything falls is run with one command and it does not have to be a marathon on one leg. Its definitely way better than not knowing what is happening under the hood.</p><p>Congratulations, you deployed the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Jipjyj0hK6g8wzp6.gif" /></figure><p>A lot of tests have to be run also the CPU we added only serves a few. The article has become a bit too long, I will need to reserve what’s left for later.</p><p>Please reach out over on <a href="https://www.linkedin.com/in/mwangi-brian/">LinkedIn</a> and let me know of your journey. You can check out the repo <a href="https://github.com/BrianMwas/vocare/tree/ft/aks-deployment-init">here</a>..</p><p>As always keep building 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c75e83c18b77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI agents in Kotlin: A deep dive into Koog]]></title>
            <link>https://medium.com/@brianmwangi_dev/building-ai-agents-in-kotlin-a-deep-dive-into-koog-d279915be5c1?source=rss-28225805d05b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d279915be5c1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[intellij]]></category>
            <dc:creator><![CDATA[Brian Mwangi]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 15:27:52 GMT</pubDate>
            <atom:updated>2025-07-12T15:27:52.255Z</atom:updated>
            <content:encoded><![CDATA[<p>Just recently Jetbrains released an AI agent building framework, Koog. It allows for great customization with ability to create single run and complex workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z22gjN2quyiQpotd" /><figcaption>Photo by <a href="https://unsplash.com/@louis993546?utm_source=medium&amp;utm_medium=referral">Louis Tsai</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here are the main features</p><ol><li><strong>Entirely</strong> <strong>Kotlin</strong>: The entire library uses Kotlin and this takes advantage of the idiomatic flows and the language itself.</li><li><strong>MCP</strong> (Model Context Protocol): Connects to Model context protocol for model management.</li><li><strong>Embeddings</strong>: Handle search and retrieval easily</li><li><strong>Prebuilt Components</strong>: Packaged components for handling common AI functionality.</li><li><strong>Powerful Streaming</strong>: Streaming and Parallel tool calls are a breeze.</li><li><strong>Persistent Agent Memory</strong>: Knowledge retention across sessions and different agents.</li><li><strong>Multiplatform</strong>: Runs on both JVM and JS targets with KMM.</li><li><strong>Flexible Graph Workflows: </strong>Allows for graph based workflows that are easy to follow through.</li><li><strong>Scalable</strong>: You can build all manner of AI apps from chatbots to sophisticated applications that serve millions.</li><li><strong>Evaluation</strong>: Its possible to monitor agents all without adding more libraries</li></ol><p>There are a lot of benefits to using it and we can see how well it runs by building a simple chatbot and a complex agentic workflow.</p><h3><strong>Installation</strong></h3><p>Let’s start by adding the dependencies. This article assumes you have IntelliJ IDE and a valid API key from the LLM provider you will be using. I believe this is one of the drawbacks of using the framework a lot of people are more comfortable with VS Code.</p><p>Go to build.gradle.kts and add the following dependency.</p><pre>dependencies {<br>    implementation(&quot;ai.koog:koog-agents:LATEST_VERSION&quot;)<br>}</pre><h3>Simple ChatBot</h3><p>Creating a basic chatbot with kotlin is quite simple and Koog handles a lot of things on your behalf by using a single run agent. You only need to specify your LLM and entry point and that’s it.</p><p>Let’s create the agent. The system prompt tells the agent how to behave to user input. The temperature is mainly to tell the agent how creative it should be from a scale of 0 to 1. In this case we give it a 0.8 since we don’t have any vector database attached yet</p><pre>val agent = AIAgent(<br>    executor = simpleOpenAIExecutor(System.getenv(&quot;YOUR_API_KEY&quot;)),<br>    systemPrompt = &quot;You are a helpful assistant named Jack. Be precise and startight to the point.&quot;,<br>    llmModel = OpenAIModels.Chat.GPT4o,<br>    temperature = 0.8<br>)</pre><p>We can now run the agent. But before we read the data, we need to know how to handle the output. To do this we make use of event handlers.</p><pre>agent.run(readln()) // How we read user input from the terminal<br><br>// Output<br>var result: String? = null<br>val eventHandlerConfig: EventHandlerConfig.() -&gt; Unit = {<br>    // We assign the agent response to the result<br>    onAgentFinished { strategyName, agentResult -&gt; result = agentResult }<br>}<br><br>// print the result of the agent<br>println(&quot;Agent completed. Result: $result&quot;)</pre><p>Please note that we need to pass the event handler config to the agent.</p><pre>val agent = AIAgent(<br>        executor = simpleOpenAIExecutor(System.getenv(&quot;YOUR_API_KEY&quot;)),<br>        llmModel = OpenAIModels.Reasoning.GPT4oMini,<br>        systemPrompt = &quot;You are a code assistant. Provide concise code examples.&quot;,<br>        // Pass the config to the install features.<br>        installFeatures = { install(EventHandler, eventHandlerConfig) }<br>    )</pre><p>The code has to be run in a coroutine, <strong>runBlocking</strong></p><pre>fun main() = runBlocking {<br>    val result = agent.run(readln()) // Ask Hello!<br>}<br><br>// Output<br>Agent says: Hello! I&#39;m here to assist you with a variety of tasks. Whether you have questions, need information, or require help with specific tasks, feel free to ask. How can I assist you today?</pre><p>So far so good but its a little boring, the point of this being an agent is it being able to do stuff for me not just answer questions. So let’s make it calculate my BMI. This is made possible by use of tools which we add to the agent using the tool registry, so let’s create our calculator.</p><p>To create a simple tool we need to implement the abstract class SimpleTool and its members and override for our use case.</p><p>To get the best results ensure tour descriptions are as simple and clear as possible.</p><p>You will also notice I added the SayToUser tool its inbuilt you don’t have to create it. It allows for sending a message to the user so we don’t have to use the event call like before.</p><pre><br>object BMICalculatorTool: SimpleTool&lt;BMICalculatorTool.Args&gt;() {<br>    override suspend fun doExecute(args: Args): String {<br>        if (args.height &lt;= 0.0) {<br>            return &quot;Height must be greater than 0.&quot;<br>        }<br><br>        val bmi = args.weight / (args.height * args.height)<br>        val category = when {<br>            bmi &lt; 18.5 -&gt; &quot;underweight&quot;<br>            bmi &lt; 25.0 -&gt; &quot;normal weight&quot;<br>            bmi &lt; 30.0 -&gt; &quot;overweight&quot;<br>            else -&gt; &quot;obese&quot;<br>        }<br><br>        return &quot;BMI: %.2f (%s)&quot;.format(bmi, category)<br>    }<br><br>    override val argsSerializer: KSerializer&lt;Args&gt;<br>        get() = Args.serializer()<br><br><br>    override val descriptor: ToolDescriptor = ToolDescriptor(<br>        name = &quot;calculate_bmi&quot;,<br>        description = &quot;Calculate Body Mass Index from weight and height&quot;,<br>        requiredParameters = listOf(<br>            ToolParameterDescriptor(<br>                name = &quot;weight&quot;,<br>                description = &quot;Weight in kilograms (e.g., 70.0)&quot;,<br>                type = ToolParameterType.Float<br>            ),<br>            ToolParameterDescriptor(<br>                name = &quot;height&quot;,<br>                description = &quot;Height in meters (e.g., 1.75)&quot;,<br>                type = ToolParameterType.Float<br>            )<br>        )<br>    )<br><br>    @Serializable<br>    data class Args(<br>        val weight: Double,<br>        val height: Double<br>    ) : Tool.Args<br>}<br><br><br>// Add the tool to the tool registry<br>val toolRegistry = ToolRegistry {<br>    tool(AskUser) // built in<br>    tool(SayToUser) // built in<br>    tool(BMICalculatorTool) // custom tool<br>}</pre><p>Now we can add our tool registry to our agent and clean it up a little bit.</p><pre>val agent = AIAgent(<br>        executor = simpleOpenAIExecutor(System.getenv(&quot;YOUR_API_KEY&quot;)),<br>        llmModel = OpenAIModels.Reasoning.GPT4oMini,<br>        systemPrompt = &quot;You are a BMI Calculator, you help to tell whether someone is in good shape or not.&quot;,<br>        toolRegistry = toolRegistry<br>    )<br><br>// Run the agent<br>fun main() = runBlocking {<br>    val result = agent.run(readln()) // Ask Hello! my weight is 60kg and my height is 1.45 meters, am I obese?<br>}<br><br>// Response <br>Hello, my height is 1.56m and my weight is 70kg<br>Agent says: Your Body Mass Index (BMI) is 28.76, which is considered overweight.</pre><p>Now our agent is getting better. But it can get more complex (<em>Do more helpful tasks</em>)</p><p>Adding tools is very simple but in a real world scenario, we might need to handle more than a simple division. The code we just ran is a single run agent meaning it will only process one input and respond once.</p><p>Let’s improve the prompt. We can do so using the agent config. To make this possible Koog provides the use of <strong>strategies. </strong>Which is mainly a flow (<strong><em>subgraph</em></strong>) the agent needs to follow from the input to the result. Strategy allows for performance checks. Think of it as a pipeline the input has to go through powered by nodes and edges in this case links between nodes, the nodes being stages the input has to pass through and an action happens like compression or improvisation.</p><p>You get more flexibility compared to the simple strategies.</p><pre>val agentStrategy = strategy(&quot;bmi calculator strategy&quot;) {<br>    val nodeCallLLM by nodeLLMRequest()<br>    val nodeExecuteTool by nodeExecuteTool()<br>    val nodeSendToolResult by nodeLLMSendToolResult()<br><br>    edge(nodeStart forwardTo nodeCallLLM)<br><br>    // Direct finish if LLM responds without tools<br>    edge(<br>        (nodeCallLLM forwardTo nodeFinish)<br>                onAssistantMessage { true }<br>    )<br><br>    // Execute tool if LLM requests it<br>    edge(<br>        (nodeCallLLM forwardTo nodeExecuteTool)<br>                onToolCall { true }<br>    )<br><br>    // Send tool result back to LLM<br>    edge(nodeExecuteTool forwardTo nodeSendToolResult)<br><br>    // Handle tool calls AFTER receiving tool results<br>    edge(<br>        (nodeSendToolResult forwardTo nodeExecuteTool)  <br>                onToolCall { true }<br>    )<br><br>    // Finish after LLM processes tool result<br>    edge(<br>        (nodeSendToolResult forwardTo nodeFinish)<br>                onAssistantMessage { true }<br>    )<br>}</pre><p>We can configure the agent here with a prompt.</p><pre>val agentConfig = AIAgentConfig(<br>    prompt = Prompt.build(&quot;bmi-calculator&quot;) {<br>        system(<br>            &quot;&quot;&quot;<br>                You are a Body Mass Index (BMI) calculator assistant.<br><br>                Your job is to help users calculate their BMI using the provided tool. The tool takes a person&#39;s weight in kilograms and height in meters, and returns their BMI along with the weight category (underweight, normal weight, overweight, or obese).<br>                <br>                When the user provides input, extract the weight and height values. The input might be phrased in various ways, such as:<br>                - &quot;My weight is 70 kg and height is 1.75 m&quot;<br>                - &quot;Calculate BMI for 80kg and 1.8m&quot;<br>                - &quot;BMI for 65 1.65&quot;<br>                - &quot;I weigh 95 and my height is 1.68&quot;<br>                <br>                Once you&#39;ve extracted the weight and height, use the `calculateBMITool` to compute the BMI. <br>                <br>                Always respond with a clear and friendly explanation of the result, including the BMI value and its health category.<br>            &quot;&quot;&quot;.trimIndent()<br>        )<br>    },<br>    model = OpenAIModels.Chat.GPT4o,<br>    maxAgentIterations = 3<br>)</pre><p>Now to get details on what is going on when the agent runs, we adding logging on the events. We can track the input passed to the next node, which input it was given and other configurations. <br>So in this example we have the EventHandler which allows us to use callbacks to get meaningful data from the agent flow.<br>We can also use <strong>AgentMemory</strong>, which is a component provided to help store and retrieve user information in the conversation.<br>It uses a memory provider to help save the conversation such as the user’s name. We will handle it later on for now let&#39;s have it simple.</p><pre>installFeatures = {<br>        install(EventHandler) {<br>            onBeforeAgentStarted { strategy: AIAgentStrategy, agent: AIAgent -&gt;<br>                println(&quot;Starting strategy: ${strategy.name}&quot;)<br>            }<br>            onAfterNode { node, context, _, _ -&gt;<br>                println(&quot;We have passed the node ${node.name} and input: ${context.agentInput}&quot;)<br>            }<br>            onAgentFinished { strategyName: String, result: String? -&gt;<br>                println(&quot;Result: $result&quot;)<br>            }<br>        }<br>        install(AgentMemory) {<br>            agentName = &quot;Koogy&quot;<br>            featureName = &quot;Conversations Agent&quot;<br>            organizationName = &quot;Quicksnap&quot;<br>        }<br>    }</pre><p>Now to bring everything together.</p><pre>val agent = AIAgent(<br>    promptExecutor = promptExecutor,<br>    strategy = agentStrategy,<br>    agentConfig = agentConfig,<br>    toolRegistry = toolRegistry,<br>    installFeatures = {<br>        install(EventHandler) {<br>            onBeforeAgentStarted { strategy: AIAgentStrategy, agent: AIAgent -&gt;<br>                println(&quot;Starting strategy: ${strategy.name}&quot;)<br>            }<br>            onAfterNode { node, context, _, _ -&gt;<br>                println(&quot;We have passed the node ${node.name} and we ${context.agentInput}&quot;)<br>            }<br>            onAgentFinished { strategyName: String, result: String? -&gt;<br>                println(&quot;Result: $result&quot;)<br>            }<br>        }<br>        install(AgentMemory) {<br>            agentName = &quot;Koogy&quot;<br>            featureName = &quot;Conversations&quot;<br>            organizationName = &quot;Quicksnap&quot;<br>        }<br>    }<br>)<br><br>// run the app<br>fun main() = runBlocking {<br>  val userInput = readlnOrNull() ?: &quot;&quot;<br>  agent.run(userInput)<br>}<br><br>// Results<br>User: Hello<br>Agent: Starting strategy: bmi-calculator-strategy<br>       We have passed the node __start__ and input Hello<br>       We have passed the node nodeSendInput and input Hello<br>       Agent says: Hi there! How can I assist you with calculating your BMI today?<br>       We have passed the node nodeExecuteTool and input Hello<br>       We have passed the node nodeSendToolResult and input Hello<br>       Result: Hi there! How can I assist you with calculating your BMI today?<br><br><br>User: Hello my name is Brian, my weight is 60kg and my height is 1.45meters<br>Agent: Hi Brian! Based on the weight of 60 kg and height of 1.45 meters, your BMI is 28.54, which falls into the &#39;overweight&#39; category. If you have any more questions or need further assistance, feel free to ask!</pre><p>This is great, we have been able to use create our own tool. But what if we could add just a little more action to this. With use of subgraphs and toolset we can make this an even more complex workflow</p><h3>Complex Workflow</h3><p>Koog allows us to make use of subgraphs to handle complex workflows that are both easy to understand and follow through. So let’s implement a medical triage toolset.</p><pre>@LLMDescription(&quot;Medical triage tools&quot;)<br>class MedicalTriageTools: ToolSet {<br>    @Tool<br>    @LLMDescription(&quot;Assess the urgency of a symptom based on severity and duration&quot;)<br>    fun assessUrgency(<br>        @LLMDescription(&quot;Symptom description&quot;) symptom: String,<br>        @LLMDescription(&quot;Duration in hours&quot;) duration: Int,<br>        @LLMDescription(&quot;Is the patient conscious?&quot;) conscious: Boolean<br>    ): String {<br>        if (!conscious) return &quot;Critical&quot;<br>        return if (symptom.contains(&quot;chest&quot;, true) &amp;&amp; duration &gt; 1) &quot;High&quot;<br>        else if (symptom.contains(&quot;fever&quot;, true) &amp;&amp; duration &gt; 72) &quot;Medium&quot;<br>        else &quot;Low&quot;<br>    }<br><br>    @Tool<br>    @LLMDescription(&quot;Provide urgent medical escalation steps&quot;)<br>    fun escalateCase(@LLMDescription(&quot;Urgency level&quot;) urgency: String): String {<br>        return &quot;Urgency: $urgency. Call an ambulance and begin emergency procedures.&quot;<br>    }<br><br>    @Tool<br>    @LLMDescription(&quot;Provide at-home care advice for low and medium urgency&quot;)<br>    fun provideAdvice(@LLMDescription(&quot;Urgency level&quot;) urgency: String): String {<br>        return when (urgency) {<br>            &quot;Low&quot; -&gt; &quot;Monitor symptoms, hydrate, and rest.&quot;<br>            &quot;Medium&quot; -&gt; &quot;Visit a local clinic in the next 24 hours.&quot;<br>            else -&gt; &quot;Unknown urgency level.&quot;<br>        }<br>    }<br><br>    @Tool<br>    @LLMDescription(&quot;Log the triage case for medical records&quot;)<br>    fun logCase(@LLMDescription(&quot;Case details&quot;) case: String): String {<br>        println(&quot;📄 Case logged: $case&quot;)<br>        return &quot;Case logged successfully&quot;<br>    }<br>}</pre><p>Register the tool set to the registry.</p><pre>val toolRegistry = ToolRegistry {<br>    tool(AskUser)<br>    tool(SayToUser)<br>    tools(MedicalTriageTools().asTools()) // Add the toolset<br>}</pre><p>So this present multiple steps and branching, but its going to require a more meaningful workflow which we can do with multiple graphs</p><p>First how we take in information</p><pre>val inputSubgraph by subgraph&lt;String, String&gt; {<br>    val askSymptoms by nodeLLMRequest()<br>    edge(nodeStart forwardTo askSymptoms)<br>    edge(askSymptoms forwardTo nodeFinish onAssistantMessage { true })<br>}</pre><p>then we need to reason on how critical the case is and branch to the right stage. It calls the <em>assessUrgency</em> tool</p><pre>val analyzeSubgraph by subgraph&lt;String, String&gt;(<br>        tools = toolRegistry.getTools(&quot;MedicalTriageTools&quot;)<br>    ) {<br>        val sendInput by nodeLLMRequest()<br>        val executeTool by nodeExecuteTool()<br>        val sendResult by nodeLLMSendToolResult()<br><br>        edge(nodeStart forwardTo sendInput)<br>        edge(sendInput forwardTo executeTool onToolCall { true })<br>        edge(executeTool forwardTo sendResult)<br>        edge(sendResult forwardTo nodeFinish onAssistantMessage { true })<br>    }<br><br>val adviceSubgraph by subgraph&lt;String, String&gt;(<br>        tools = listOf(toolRegistry.getTool(&quot;MedicalTriageTools#provideAdvice&quot;))<br>    ) {<br>        val askAdvice by nodeLLMRequest()<br>        val executeAdvice by nodeExecuteTool()<br>        val sendAdvice by nodeLLMSendToolResult()<br><br>        edge(nodeStart forwardTo askAdvice)<br>        edge(askAdvice forwardTo executeAdvice onToolCall { true })<br>        edge(executeAdvice forwardTo sendAdvice)<br>        edge(sendAdvice forwardTo nodeFinish onAssistantMessage { true })<br>    }</pre><p>We have another branch which can escalate the case, with the <em>escalateCase</em> and <em>logCase</em> tools</p><pre>val escalationSubgraph by subgraph&lt;String, String&gt;(<br>    tools = listOf(MedicalTriageTools::escalateCase, MedicalTriageTools::logCase)<br>) {<br>    val sendEscalationPrompt by nodeLLMRequest()<br>    val runEscalation by nodeExecuteTool()<br>    val sendEscalationResult by nodeLLMSendToolResult()<br><br>    edge(nodeStart forwardTo sendEscalationPrompt)<br>    edge(sendEscalationPrompt forwardTo runEscalation onToolCall { true })<br>    edge(runEscalation forwardTo sendEscalationResult)<br>    edge(sendEscalationResult forwardTo runEscalation onToolCall { true })<br>    edge(sendEscalationResult forwardTo nodeFinish onAssistantMessage { true })<br>}</pre><p>And then the last stage, the advice</p><pre>val adviceSubgraph by subgraph&lt;String, String&gt;(<br>    tools = listOf(MedicalTriageTools::provideAdvice, MedicalTriageTools::logCase)<br>) {<br>    val sendAdvicePrompt by nodeLLMRequest()<br>    val runAdvice by nodeExecuteTool()<br>    val sendAdviceResult by nodeLLMSendToolResult()<br><br>    edge(nodeStart forwardTo sendAdvicePrompt)<br>    edge(sendAdvicePrompt forwardTo runAdvice onToolCall { true })<br>    edge(runAdvice forwardTo sendAdviceResult)<br>    edge(sendAdviceResult forwardTo runAdvice onToolCall { true })<br>    edge(sendAdviceResult forwardTo nodeFinish onAssistantMessage { true })<br>}</pre><p>So with all of this in mind. We can combine them for a definitive flow.</p><pre>val triageStrategy = strategy(&quot;advanced medical triage&quot;) {<br>    val inputSubgraph by subgraph&lt;String, String&gt; {<br>        val askSymptoms by nodeLLMRequest()<br><br>        edge(nodeStart forwardTo askSymptoms)<br>        edge(askSymptoms forwardTo nodeFinish onAssistantMessage { true })<br>    }<br><br>    val analyzeSubgraph by subgraph&lt;String, String&gt;(<br>        tools = medicalTools<br>    ) {<br>        val sendInput by nodeLLMRequest()<br>        val executeTool by nodeExecuteTool()<br>        val sendResult by nodeLLMSendToolResult()<br><br>        edge(nodeStart forwardTo sendInput)<br>        edge(sendInput forwardTo executeTool onToolCall { true })<br>        edge(executeTool forwardTo sendResult)<br>        edge(sendResult forwardTo nodeFinish onAssistantMessage { true })<br>    }<br><br>    val adviceSubgraph by subgraph&lt;String, String&gt;(<br>        tools = medicalTools<br>    ) {<br>        val sendAdvicePrompt by nodeLLMRequest()<br>        val runAdvice by nodeExecuteTool()<br>        val sendAdviceResult by nodeLLMSendToolResult()<br><br>        edge(nodeStart forwardTo sendAdvicePrompt)<br>        edge(sendAdvicePrompt forwardTo runAdvice onToolCall { true })<br>        edge(runAdvice forwardTo sendAdviceResult)<br>        edge(sendAdviceResult forwardTo nodeFinish onAssistantMessage { true })<br>    }<br><br>    val escalationSubgraph by subgraph&lt;String, String&gt;(<br>        tools = medicalTools<br>    ) {<br>        val sendEscalationPrompt by nodeLLMRequest()<br>        val runEscalation by nodeExecuteTool()<br>        val sendEscalationResult by nodeLLMSendToolResult()<br><br>        edge(nodeStart forwardTo sendEscalationPrompt)<br>        edge(sendEscalationPrompt forwardTo runEscalation onToolCall { true })<br>        edge(runEscalation forwardTo sendEscalationResult)<br>        edge(sendEscalationResult forwardTo nodeFinish onAssistantMessage { true })<br>    }<br><br>    // Chain input → reasoning<br>    nodeStart then inputSubgraph then analyzeSubgraph then adviceSubgraph then escalationSubgraph then nodeFinish<br>}<br><br>// Don&#39;t forget to add it in<br>val agent = AIAgent(<br>    promptExecutor = promptExecutor,<br>    strategy = triageStrategy, // here</pre><h3>Improvements</h3><p>So the app now runs well but we can improve it by adding the following</p><p>1. <strong>Streaming</strong>. This entire time all responses have been on a wait basis. The agent has to generate the whole answer first and then provide the response. But this increases latency, we can improve the wait time by adding streaming, connected with markdown to structure out the response.</p><pre>fun triageMarkdownDefinition(): MarkdownStructuredDataDefinition {<br>    return MarkdownStructuredDataDefinition(&quot;triage_report&quot;, schema = {})<br>}<br><br>val streamFinalMarkdown by node&lt;String, String&gt; { input -&gt;<br>        val mdDef = triageMarkdownDefinition()<br><br>        llm.writeSession {<br>            updatePrompt { user(input) }<br><br>            val stream = requestLLMStreaming(mdDef)<br><br>            // Optional: Combine chunks into final markdown<br>            val builder = StringBuilder()<br>            stream.collect { chunk -&gt;<br>                println(&quot;📄 Chunk: $chunk&quot;)<br>                builder.append(chunk)<br>            }<br><br>            builder.toString()<br>        }<br>    }<br><br>// Add a node for the streaming<br>val finalStreamingSubgraph by subgraph&lt;String, String&gt; {<br>        edge(nodeStart forwardTo streamFinalMarkdown)<br>        edge(streamFinalMarkdown forwardTo nodeFinish)<br>    }<br><br>// connect it to the others<br>nodeStart then inputSubgraph then analyzeSubgraph then adviceSubgraph then escalationSubgraph then finalStreamingSubgraph then nodeFinish</pre><p>2. <strong>History Compression</strong>. To prevent build up of the chat history, compression can be added to help in summarizing the context needed to keep the conversation from using too much tokens.</p><pre>// We define the check to ensure we have a mark <br>private suspend fun AIAgentContextBase.historyIsTooLong(): Boolean {<br>    return llm.readSession { prompt.messages.size &gt; 100 }<br>}<br><br>// We update the final subgraph<br>val finalStreamingSubgraph by subgraph&lt;String, String&gt; {<br>    val generateResponse by nodeLLMRequest()<br>    val compressHistory by nodeLLMCompressHistory&lt;Message.Assistant&gt;()<br>    val streamMarkdown by node&lt;String, String&gt; { input -&gt;<br>        val def = triageMarkdownDefinition()<br>        llm.writeSession {<br>            updatePrompt { user(input) }<br>            val stream = requestLLMStreaming(def)<br>            val builder = StringBuilder()<br>            stream.collect { chunk -&gt;<br>                println(&quot;📄 Chunk: $chunk&quot;)<br>                builder.append(chunk)<br>            }<br>            builder.toString()<br>        }<br>    }<br>    edge(nodeStart forwardTo generateResponse)<br>    edge(generateResponse forwardTo compressHistory onCondition { historyIsTooLong() })<br>    edge(compressHistory forwardTo streamMarkdown)<br>    edge(generateResponse forwardTo streamMarkdown onCondition { !historyIsTooLong() })<br>    edge(streamMarkdown forwardTo nodeFinish)<br>}</pre><p>3. <strong>Parallels</strong></p><p>This is a tool that let’s you call multiple calls in the subgraph concurrently, thereby improving performance</p><p>Here’s how we add it in</p><pre>// Replace what&#39;s inside the analyze graph to make use of parallelization<br><br>val callLLM by nodeLLMRequestMultiple()<br>val runParallelTools by nodeExecuteMultipleTools(parallelTools = true)<br>val sendParallelResults by nodeLLMSendMultipleToolResults()<br>val compressHistory by nodeLLMCompressHistory&lt;List&lt;ReceivedToolResult&gt;&gt;()<br><br>// How we apply it<br>val analyzeSubgraph by subgraph&lt;String, String&gt;(<br>    tools = medicalTools<br>) {<br>    val callLLM by nodeLLMRequestMultiple()<br>    val runParallelTools by nodeExecuteMultipleTools(parallelTools = true)<br>    val sendParallelResults by nodeLLMSendMultipleToolResults()<br>    val compressHistory by nodeLLMCompressHistory&lt;List&lt;ReceivedToolResult&gt;&gt;()<br><br>    edge(nodeStart forwardTo callLLM)<br><br>    edge(callLLM forwardTo nodeFinish<br>        transformed { it.first() }<br>        onAssistantMessage { true }<br>    )<br><br>    edge(callLLM forwardTo runParallelTools<br>        onMultipleToolCalls { true }<br>    )<br><br>    edge(runParallelTools forwardTo compressHistory<br>        onCondition { llm.readSession { prompt.latestTokenUsage &gt; 4000 } } // adjust token threshold<br>    )<br>    edge(compressHistory forwardTo sendParallelResults)<br><br>    edge(runParallelTools forwardTo sendParallelResults<br>        onCondition { llm.readSession { prompt.latestTokenUsage &lt;= 4000 } }<br>    )<br><br>    edge(sendParallelResults forwardTo runParallelTools<br>        onMultipleToolCalls { true }<br>    )<br><br>    edge(sendParallelResults forwardTo nodeFinish<br>        transformed { it.first() }<br>        onAssistantMessage { true }<br>    )<br>}</pre><p>4. <strong>Logging</strong></p><p>So the app is great but there has to be a way to check for errors and Tracing handles this to give information. It&#39;s added in the install feature parameter.<br>Its inbuilt so you don’t have to add another feature in. With this it can intercept events in the agent pipeline.</p><pre>val logger = KotlinLogging.logger(&quot;your.trace.logger&quot;)<br><br>install(Tracing) {<br>    addMessageProcessor(TraceFeatureMessageLogWriter(logger))<br>    messageFilter = { message -&gt;<br>        // Only trace LLM calls and tool calls<br>        message is LLMCallStartEvent || message is ToolCallEvent<br>    }<br>}<br><br>// and now we have<br>installFeatures = {<br>        install(EventHandler) {<br>            onToolCall { tool: Tool&lt;*, *&gt;, toolArgs: Tool.Args -&gt;<br>                println(&quot;Tool called: tool ${tool.name}&quot;)<br>            }<br>            onAgentFinished { strategyName: String, result: String? -&gt;<br>                println(&quot;Result: $result&quot;)<br>            }<br>        }<br>        install(AgentMemory) {<br>            agentName = &quot;Koogy&quot;<br>            featureName = &quot;Conversations&quot;<br>            organizationName = &quot;Quicksnap&quot;<br>        }<br>        install(Tracing) {<br>            addMessageProcessor(TraceFeatureMessageLogWriter(logger))<br>            messageFilter = { message -&gt;<br>                // Only trace LLM calls and tool calls<br>                message is LLMCallStartEvent || message is ToolCallEvent<br>            }<br>        }<br>    }</pre><p><strong>Conclusion</strong></p><p>Koog is one of the best agent building framework, for all kotlin lovers it allows for such a fun experience translating complex workflows. You also don’t have to sweat handling most of these implementations like adding dependencies. Don’t get me wrong though there’s still a long way to go and a lot will change with the coming releases but it&#39;s definitely going to be up there with the big boys. <br>As always keep building 😎</p><p>You can reach me via <a href="https://www.linkedin.com/in/mwangi-brian/">LinkedIn</a> and tell me on the awesome ways you intend to use Koog</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d279915be5c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Voice Assistant Agent: LiveKit, Firebase and FreeSwitch]]></title>
            <link>https://medium.com/@brianmwangi_dev/voice-assistant-agent-livekit-firebase-and-freeswitch-efaedf34757e?source=rss-28225805d05b------2</link>
            <guid isPermaLink="false">https://medium.com/p/efaedf34757e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[cartesian]]></category>
            <category><![CDATA[livekit]]></category>
            <category><![CDATA[freeswitch]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Brian Mwangi]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 08:41:33 GMT</pubDate>
            <atom:updated>2025-07-10T07:45:13.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LgA1fRjJ-5IuSPKaw-uO8A.jpeg" /></figure><p>Over the past couple of months there has been an increase in the number of startups building Voice Assistants, but the one problem they all share is how to get the conversation better and as close as possible to a call center human responder. While coding agents can now handling building these systems there’s still a gap in information on the flow of these systems: <strong>SIP (Session Initiation Protocol). </strong>SIP is essential for allowing agents to initiate, manage and terminate the voice and video calls over the internet which have been managed by VoIP like Twilio and Telynx.</p><p>For example imagine a restaurant business, it has overwhelming reservation calls, while still having to manage orders. An AI agent can really be of help here. The restaurant would use a VoIP but how do they ensure they have the right data for the right customer, how do they initiate the conversation, ensure the communication is right? and be able to end the call once the data has been captured. So we need SIP for that and to be able to connect to traditional network that’s where <strong>SIP trunking</strong> comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WE8IbsnUseoWZ9vJ0laUg.png" /></figure><p>Let’s dive in on how to build the restaurant agent, We will use FreeSwitch to handle the calls, Firebase to store the data and LiveKit Agents to manage the conversation.</p><h3>Setting Up</h3><p>To ensure we keep this simple and straight forward, the assumption is you have <strong>Firebase</strong> account set up, create a new project. We will only use Firestore for now. But you need to head on over to the project settings and service account tab and generate a new private key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMhl83uQYkLD_i0lDUpCug.png" /></figure><p>You also need to set up a python project with virtual environment. Now install the following dependencies.</p><pre>pip install firebase-admin &quot;livekit-agents[deepgram,openai,cartesia,silero,turn-detector]~=1.0&quot; \<br>  &quot;livekit-plugins-noise-cancellation~=0.2&quot; \<br>  &quot;python-dotenv&quot;</pre><p>Once complete, we need to set up the required keys, needed to communicate with OpenAI apis and Livekit. You can get some tokens to use to test with before you add your pay for any of the services, Deepgram is a good option. Create a .env and add the following, you can omit Cartesia or retain it.</p><pre>DEEPGRAM_API_KEY=&lt;Your Deepgram API Key&gt;<br>OPENAI_API_KEY=&lt;Your OpenAI API Key&gt;<br>CARTESIA_API_KEY=&lt;Your Cartesia API Key&gt;<br>LIVEKIT_API_KEY=&lt;your API Key&gt;<br>LIVEKIT_API_SECRET=&lt;your API Secret&gt;<br>LIVEKIT_URL=&lt;your LiveKit URL&gt;<br>GROQ_API_KEY=&lt;your groq api Secret&gt;</pre><p>We will be using Docker to run FreeSwitch and Livekit server all together locally, so create a Dockerfile and docker-compose.yml file to create the config and run the app. Here’s how it should look like</p><p>We define the Dockerfile</p><pre># Dockerfile<br>FROM python:3.11-slim<br><br>WORKDIR /app<br><br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br><br>COPY . .<br><br># Expose port for FreeSWITCH socket connection<br>EXPOSE 8000<br><br>CMD [&quot;python&quot;, &quot;main.py&quot;]</pre><p>and compose, reference the Dockerfile in the backend config using . since its located in the same directory. We will talk about Freeswitch later on, and how to set it up for testing using its referenced config.</p><pre>version: &#39;3&#39;<br>services:<br>  freeswitch:<br>    image: drachtio/freeswitch:latest<br>    ports:<br>      - &quot;5060:5060/udp&quot;    # SIP signaling<br>      - &quot;5080:5080/udp&quot;    # SIP signaling (alternative)<br>      - &quot;8021:8021&quot;        # Event Socket for LiveKit<br>      - &quot;16384-16394:16384-16394/udp&quot;  # RTP media ports<br>    volumes:<br>      - ./freeswitch-config:/etc/freeswitch<br>    environment:<br>      - FREESWITCH_LOG_LEVEL=INFO<br>    networks:<br>      - restaurant-net<br>    depends_on:<br>      - livekit<br>  <br>  # LiveKit server for media processing<br>  livekit:<br>    image: livekit/livekit-server:latest<br>    ports:<br>      - &quot;7880:7880&quot;   # WebSocket<br>      - &quot;7881:7881&quot;   # WebSocket with TLS  <br>      - &quot;7882:7882/udp&quot;  # TURN/UDP<br>      - &quot;50000-60000:50000-60000/udp&quot;  # LiveKit media ports<br>    environment:<br>      - LIVEKIT_KEYS=devkey:secret<br>      - LIVEKIT_CONFIG=/etc/livekit.yaml<br>    volumes:<br>      - ./livekit-config.yaml:/etc/livekit.yaml<br>    networks:<br>      - restaurant-net<br><br>  # Restaurant AI Assistant<br>  backend:<br>    build: .<br>    ports:<br>      - &quot;8000:8000&quot;<br>    volumes:<br>      - .:/app<br>      - ./service.json:/app/service.json<br>    environment:<br>      - OPENAI_API_KEY=${OPENAI_API_KEY}<br>      - DEEPGRAM_API_KEY=${DEEPGRAM_API_KEY}<br>      - CARTESIA_API_KEY=${CARTESIA_API_KEY}<br>      - CARTESIA_VOICE_ID=${CARTESIA_VOICE_ID}<br>      - FIREBASE_SERVICE_ACCOUNT_PATH=/app/service.json<br>      # LiveKit connection<br>      - LIVEKIT_URL=${LIVEKIT_URL}<br>      - LIVEKIT_API_KEY=${LIVEKIT_API_KEY}<br>      - LIVEKIT_API_SECRET=${LIVEKIT_API_SECRET}<br>    networks:<br>      - restaurant-net<br>    depends_on:<br>      - livekit<br>      - freeswitch<br>    command: python main.py<br><br>  # Menu management service<br>  menu-seeder:<br>    build: .<br>    volumes:<br>      - .:/app<br>      - ./service.json:/app/service.json<br>    environment:<br>      - FIREBASE_SERVICE_ACCOUNT_PATH=/app/service.json<br>    networks:<br>      - restaurant-net<br>    profiles:<br>      - tools<br>    command: python scripts/quick_seed.py<br><br>networks:<br>  restaurant-net:<br>    driver: bridge</pre><p>Great! now for the best part, building our data persistence. We need a menu in place, and where we will store all customer information, Firestore fast read and write capability will enhance the way we store the call details.</p><h3>Long Term Memory: Firebase</h3><p>Create a Firestore manager, remember the key you generated and downloaded, you will need to paste it into the directory and will be used to initialize firebase,</p><pre># manager.py<br><br>class FirebaseManager:<br>    &quot;&quot;&quot;Handles all Firebase operations for the restaurant&quot;&quot;&quot;<br>    <br>    def __init__(self, credentials_path: str):<br>        &quot;&quot;&quot;Initialize Firebase Admin SDK&quot;&quot;&quot;<br>        try:<br>            # Initialize Firebase Admin<br>            cred = credentials.Certificate(credentials_path)<br>            firebase_admin.initialize_app(cred)<br>            <br>            # Get Firestore client<br>            self.db = firestore.client()<br>            <br>            # Collection references<br>            self.menu_collection = self.db.collection(&#39;menu_items&#39;)<br>            self.orders_collection = self.db.collection(&#39;orders&#39;)<br>            self.customers_collection = self.db.collection(&#39;customers&#39;)<br>            self.call_logs_collection = self.db.collection(&#39;call_logs&#39;)<br>            self.analytics_collection = self.db.collection(&#39;analytics&#39;)<br>            <br>            # In-memory menu cache for faster access<br>            self.menu_items = {}<br>            <br>              # Load menu items into memory asynchronously<br>            asyncio.create_task(self._load_menu())<br>            <br>            logger.info(&quot;Firebase initialized successfully&quot;)<br>        except Exception as e:<br>            logger.error(f&quot;Firebase initialization failed: {e}&quot;)<br>            raise<br><br>    <br>    async def _load_menu(self):<br>        &quot;&quot;&quot;Load menu items into memory for faster access&quot;&quot;&quot;<br>        try:<br>            docs = self.menu_collection.where(&#39;available&#39;, &#39;==&#39;, True).stream()<br>            self.menu_items = {doc.id: doc.to_dict() for doc in docs}<br>            logger.info(f&quot;Loaded {len(self.menu_items)} menu items into memory&quot;)<br>        except Exception as e:<br>            logger.error(f&quot;Error loading menu: {e}&quot;)</pre><p>You can use a script to initialize the menu which is how I did it, we are using the menu_items cache to ensure that everything is fast access.</p><p>Since its a restaurant we need a way to handle the reservations and order, so add the following functions in. We have also to add and/or retrieve customer information so we can relate the order/reservation to the right person.</p><pre>def save_reservation(self, userdata: UserData) -&gt; bool:<br>    &quot;&quot;&quot;Save reservation to Firebase&quot;&quot;&quot;<br>    try:<br>        reservation_data = {<br>            &#39;id&#39;: str(uuid.uuid4()),<br>            &#39;customer_name&#39;: userdata.customer_name,<br>            &#39;customer_phone&#39;: userdata.customer_phone,<br>            &#39;reservation_date&#39;: userdata.reservation_date,<br>            &#39;reservation_time&#39;: userdata.reservation_time,<br>            &#39;party_size&#39;: userdata.party_size,<br>            &#39;created_at&#39;: datetime.now(),<br>            &#39;status&#39;: &#39;confirmed&#39;,<br>            &#39;call_id&#39;: userdata.call_id<br>        }<br>        <br>        self.db.collection(&#39;reservations&#39;).add(reservation_data)<br>        logger.info(f&quot;Saved reservation for {userdata.customer_name}&quot;)<br>        return True<br>        <br>    except Exception as e:<br>        logger.error(f&quot;Error saving reservation: {e}&quot;)<br>        return False<br><br><br>def create_order(self, order: CustomerOrder) -&gt; bool:<br>      &quot;&quot;&quot;Create new order in Firebase&quot;&quot;&quot;<br>      try:<br>          order_ref = self.orders_collection.document(order.id)<br>          order_ref.set(order.to_dict())<br>          <br>          # Update customer info<br>          self._update_customer_info(order.customer_phone, order.customer_name)<br>          <br>          # Update analytics<br>          self._update_order_analytics(order)<br>          <br>          logger.info(f&quot;Created order {order.id} for ${order.total_amount}&quot;)<br>          return True<br>          <br>      except Exception as e:<br>          logger.error(f&quot;Error creating order: {e}&quot;)<br>          return False<br><br>def _update_order_analytics(self, order: CustomerOrder):<br>        &quot;&quot;&quot;Update daily analytics with new order&quot;&quot;&quot;<br>        try:<br>            today = datetime.now().date()<br>            analytics_ref = self.analytics_collection.document(today.isoformat())<br>            <br>            analytics_ref.set({<br>                &#39;date&#39;: today,<br>                &#39;total_orders&#39;: firestore.Increment(1),<br>                &#39;total_revenue&#39;: firestore.Increment(order.total_amount),<br>                &#39;average_order_value&#39;: firestore.Increment(order.total_amount),<br>                &#39;updated_at&#39;: datetime.now()<br>            }, merge=True)<br>            <br>        except Exception as e:<br>            logger.error(f&quot;Error updating analytics: {e}&quot;)<br><br># === CUSTOMER OPERATIONS ===<br>    def _update_customer_info(self, phone: str, name: str):<br>        &quot;&quot;&quot;Update or create customer record&quot;&quot;&quot;<br>        try:<br>            customer_ref = self.customers_collection.document(phone)<br>            <br>            # Check if customer exists<br>            customer_doc = customer_ref.get()<br>            <br>            if customer_doc.exists:<br>                # Update existing customer<br>                customer_ref.update({<br>                    &#39;name&#39;: name,<br>                    &#39;last_order_time&#39;: datetime.now(),<br>                    &#39;total_orders&#39;: firestore.Increment(1)<br>                })<br>            else:<br>                # Create new customer<br>                customer_ref.set({<br>                    &#39;phone&#39;: phone,<br>                    &#39;name&#39;: name,<br>                    &#39;first_order_time&#39;: datetime.now(),<br>                    &#39;last_order_time&#39;: datetime.now(),<br>                    &#39;total_orders&#39;: 1,<br>                    &#39;preferred_items&#39;: [],<br>                    &#39;dietary_restrictions&#39;: []<br>                })<br>            <br>        except Exception as e:<br>            logger.error(f&quot;Error updating customer info: {e}&quot;)</pre><p>Okay great, now we need to set up agents that will be able to save the customers data when they make an order or set up a reservation over the call.</p><p>So we need to set up our agents, to handle this. Usually when setting up the agents you need to have a flow of events that would happen in a typical phone call. So the idea is after a call you need to know the intent, are they asking for information, are they making an order are they making a complaint? We need an agent that can help decide this, an <strong>IntentClassifierAgent</strong>. This agent will be the first one to take the call and decide what the caller wants it will also make greetings.</p><h3>Short Term Memory: Agent State</h3><p>But our classifier agent, needs to be able to keep state. That is to be able to allow the data to persist about the user, and the intent so that the many turns won’t be lost and end up in a cycle in the call trying to decipher which action to take. Livekit allows for memory cache using <strong>RunContext</strong>. And we can use it to define the base state</p><pre># models.py<br><br>@dataclass<br>class UserData:<br>    &quot;&quot;&quot;Comprehensive user session data&quot;&quot;&quot;<br>    # Customer information<br>    customer_name: str = &quot;&quot;<br>    customer_phone: str = &quot;&quot;<br>    customer_email: str = &quot;&quot;<br><br>    # Order management<br>    current_order: List[Dict] = field(default_factory=list)<br>    order_total: float = 0.0<br>    special_instructions: str = &quot;&quot;<br><br>    # Reservation management<br>    reservation_date: str = &quot;&quot;<br>    reservation_time: str = &quot;&quot;<br>    party_size: int = 0<br><br>    # Call context<br>    call_id: str = &quot;&quot;<br>    caller_number: str = &quot;&quot;<br>    call_start_time: datetime = field(default_factory=datetime.now)<br>    intent: str = &quot;&quot;</pre><p>Okay now we use it, pass it to our constructor. To create a DRY flow, we set up a base agent that handles the base calls. It will handle the greetings and handle dependencies, validation, LLM, Set up configuration keys.</p><pre>class BaseRestaurantAgent(Agent):<br>    &quot;&quot;&quot;Base agent that knows how to update and check user data&quot;&quot;&quot;<br><br>    def __init__(self, chat_ctx: ChatContext, firebase: FirebaseManager, userdata: UserData, config: AgentConfig):<br>        self.firebase = firebase<br>        self.userdata = userdata<br>        self.config = config<br>        <br>        # Configure agent with STT, LLM, TTS, VAD and shared tools<br>        super().__init__(<br>            chat_ctx=chat_ctx,<br>            stt=deepgram.STT(api_key=config.deepgram_api_key),<br>            llm=openai.LLM(<br>                model=config.openai_model,<br>                api_key=config.openai_api_key<br>            ),<br>            tts=cartesia.TTS(<br>                api_key=config.cartesia_api_key,<br>                voice=config.cartesia_voice_id<br>            ),<br>            vad=silero.VAD.load(),<br>            tools=[<br>                update_customer_name,<br>                update_customer_phone, <br>                update_customer_email,<br>                add_special_instructions,<br>                get_customer_summary,<br>                check_loyalty_status<br>            ]<br>        )<br><br>    async def on_enter(self):<br>        &quot;&quot;&quot;Called when agent becomes active - manage context and greet user&quot;&quot;&quot;<br>        agent_name = self.__class__.__name__<br>        logger.info(f&quot;Entering {agent_name}&quot;)<br><br>        userdata: UserData = self.session.userdata<br>        if userdata.ctx and userdata.ctx.room:<br>            await userdata.ctx.room.local_participant.set_attributes({&quot;agent&quot;: agent_name})<br><br>        chat_ctx = self.chat_ctx.copy()<br><br>        # Merge context from previous agent if exists<br>        if hasattr(userdata, &#39;prev_agent&#39;) and userdata.prev_agent:<br>            items_copy = self._truncate_chat_ctx(<br>                userdata.prev_agent.chat_ctx.items, keep_function_call=True<br>            )<br>            existing_ids = {item.id for item in chat_ctx.items}<br>            items_copy = [item for item in items_copy if item.id not in existing_ids]<br>            chat_ctx.items.extend(items_copy)<br><br>        # Add system message with current context<br>        chat_ctx.add_message(<br>            role=&quot;system&quot;,<br>            content=f&quot;You are the {agent_name}. {self.instructions} Current session: {userdata.summarize()}&quot;<br>        )<br>        await self.update_chat_ctx(chat_ctx)<br>        <br>        # Generate appropriate greeting<br>        await self.session.generate_reply(<br>            instructions=&quot;Greet the user warmly based on your role and current context.&quot;,<br>        )<br><br><br>    async def _transfer_to_agent(self, name: str, context: RunContext) -&gt; Agent:<br>        &quot;&quot;&quot;Transfer to another agent while preserving context&quot;&quot;&quot;<br>        userdata = context.userdata<br>        current_agent = context.session.current_agent<br>        if hasattr(userdata, &#39;personas&#39;) and name in userdata.personas:<br>            next_agent = userdata.personas[name]<br>            userdata.prev_agent = current_agent<br>            return next_agent<br>        else:<br>            logger.error(f&quot;Agent {name} not found in personas&quot;)<br>            return current_agent<br><br>    async def on_exit(self):<br>        &quot;&quot;&quot;Called before agent handoff - say goodbye&quot;&quot;&quot;<br>        # Generate appropriate transition message<br>        await self.session.generate_reply(<br>            instructions=&quot;Let the user know you&#39;re transferring them to a specialist who can better help them.&quot;,<br>        )<br><br>    async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -&gt; None:<br>        &quot;&quot;&quot;Called after user&#39;s turn - fetch relevant information from Firebase and enrich context&quot;&quot;&quot;<br>        message_text = new_message.text_content()<br>        <br>        # Look up customer information from Firebase based on user&#39;s message<br>        customer_info = await self._lookup_customer_info(message_text)<br>        <br>        if customer_info:<br>            turn_ctx.add_message(<br>                role=&quot;assistant&quot;, <br>                content=f&quot;Customer information found: {customer_info}&quot;<br>            )<br>            # Persist the enriched context<br>            await self.update_chat_ctx(turn_ctx)<br><br>    async def _lookup_customer_info(self, message_text: str) -&gt; str:<br>        &quot;&quot;&quot;Look up customer information from Firebase based on message content&quot;&quot;&quot;<br>        import re<br>        <br>        # Extract phone numbers from message<br>        phone_matches = re.findall(r&#39;(\+?1?[-.\s]?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4})&#39;, message_text)<br>        <br>        # Extract email addresses from message<br>        email_matches = re.findall(r&#39;([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})&#39;, message_text)<br>        <br>        info_parts = []<br>        <br>        # Look up by phone number<br>        if phone_matches:<br>            try:<br>                phone = phone_matches[0]<br>                customer_history = await self.firebase.get_customer_order_history(phone)<br>                if customer_history:<br>                    info_parts.append(f&quot;Found {len(customer_history)} previous orders for {phone}&quot;)<br>                    # Get customer preferences<br>                    preferences = await self.firebase.get_customer_preferences(phone)<br>                    if preferences:<br>                        info_parts.append(f&quot;Customer preferences: {preferences}&quot;)<br>            except Exception as e:<br>                logger.warning(f&quot;Failed to lookup customer by phone: {e}&quot;)<br>        <br>        # Look up by email<br>        if email_matches:<br>            try:<br>                email = email_matches[0]<br>                # You could add email-based lookup here if your Firebase supports it<br>                info_parts.append(f&quot;Email provided: {email}&quot;)<br>            except Exception as e:<br>                logger.warning(f&quot;Failed to lookup customer by email: {e}&quot;)<br>        <br>        return &quot; | &quot;.join(info_parts) if info_parts else &quot;&quot;<br><br>    async def _validate_phone(self, phone: str) -&gt; bool:<br>        &quot;&quot;&quot;Validate phone number format&quot;&quot;&quot;<br>        import re<br>        # Simple phone validation - adjust pattern as needed<br>        phone_pattern = r&#39;^\+?1?[-.\s]?\(?[0-9]{3}\)?[-.\s]?[0-9]{3}[-.\s]?[0-9]{4}$&#39;<br>        return bool(re.match(phone_pattern, phone.strip()))<br><br>    async def _validate_email(self, email: str) -&gt; bool:<br>        &quot;&quot;&quot;Validate email format&quot;&quot;&quot;<br>        import re<br>        email_pattern = r&#39;^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$&#39;<br>        return bool(re.match(email_pattern, email.strip()))<br><br>    def _handoff_if_done(self):<br>        # Default: no handoff, override in child if needed<br>        return None</pre><p>we apply the base agent so that each specific agent only handles its specific task.</p><pre>class IntentClassifierAgent(BaseRestaurantAgent):<br>    def __init__(self, chat_ctx, firebase, userdata: UserData, config: AgentConfig):<br>        super().__init__(chat_ctx, firebase, userdata, config)<br>        <br>        # Get menu information from Firebase<br>        menu_text = firebase.get_menu_text()<br>        <br>        self.instructions = (<br>            f&quot;You&#39;re a friendly cafe staff member. Listen to what the customer wants and help them &quot;<br>            f&quot;in a warm, natural way. If they want to order food, make a reservation, or just ask questions, &quot;<br>            f&quot;respond conversationally like you&#39;re having a real conversation with a regular customer.\n\n&quot;<br>            f&quot;Our Menu Today:\n{menu_text}\n\n&quot;<br>            f&quot;GUIDELINES:\n&quot;<br>            f&quot;- If they want to order food → use intent_is_order\n&quot;<br>            f&quot;- If they want to make a reservation → use intent_is_reservation\n&quot;<br>            f&quot;- Answer simple questions about menu/hours yourself\n&quot;<br>            f&quot;- Use the shared tools to capture customer information\n&quot;<br>            f&quot;- Be warm and welcoming, especially to returning customers&quot;<br>        )<br>        <br>    @function_tool()<br>    async def intent_is_order(self, context: RunContext[UserData]):<br>        context.userdata.intent = &quot;order&quot;<br>        return OrderAgent(chat_ctx=self.session._chat_ctx, firebase=self.firebase, userdata=context.userdata, config=self.config)<br><br>    @function_tool()<br>    async def intent_is_reservation(self, context: RunContext[UserData]):<br>        context.userdata.intent = &quot;reservation&quot;<br>        return ReservationAgent(chat_ctx=self.session._chat_ctx, firebase=self.firebase, userdata=context.userdata, config=self.config)</pre><p>With the help of the instructions, its possible to determine which tool to call, and thereby how to route to the next agent.</p><p>Here are the <strong>OrderAgent</strong> for orders, for reservations we use <strong>ReservationAgent</strong> and to ensure we captured the right details the <strong>ConfirmationAgent</strong>.</p><pre>class OrderAgent(BaseRestaurantAgent):<br>    def __init__(self, chat_ctx, firebase, userdata: UserData, config: AgentConfig):<br>        super().__init__(chat_ctx, firebase, userdata, config)<br>        <br>        # Get menu information from Firebase<br>        menu_text = firebase.get_menu_text()<br>        <br>        self.instructions = (<br>            f&quot;You&#39;re a friendly cafe staff member taking orders. Chat naturally with customers about &quot;<br>            f&quot;what they&#39;d like to eat or drink. If you need their name or phone for the order, ask casually. &quot;<br>            f&quot;Only ask for information you actually need - don&#39;t interrogate them. Be conversational and helpful, &quot;<br>            f&quot;like you&#39;re talking to a neighbor who stopped by for coffee.\n\n&quot;<br>            f&quot;Our Menu Today:\n{menu_text}\n\n&quot;<br>            f&quot;GUIDELINES:\n&quot;<br>            f&quot;- Help customers choose from our available menu items\n&quot;<br>            f&quot;- Ask about quantity and any modifications\n&quot;<br>            f&quot;- Use shared tools to collect customer info (name, phone)\n&quot;<br>            f&quot;- When order is complete, use finalize_order to proceed to confirmation\n&quot;<br>            f&quot;- Suggest popular items if customers seem unsure\n&quot;<br>            f&quot;- Mention loyalty points for returning customers&quot;<br>        )<br><br>    @function_tool()<br>    async def add_item(self, context: RunContext[UserData], item: str, quantity: int):<br>        context.userdata.current_order.append({&quot;item&quot;: item, &quot;quantity&quot;: quantity})<br>        return self._handoff_if_done()<br><br>    @function_tool()<br>    async def set_payment_method(self, context: RunContext[UserData], method: str):<br>        context.userdata.payment_method = method<br>        return self._handoff_if_done()<br><br>    @function_tool()<br>    async def finalize_order(self, context: RunContext[UserData]):<br>        &quot;&quot;&quot;Hand off to ConfirmationAgent to review order details&quot;&quot;&quot;<br>        return ConfirmationAgent(<br>            chat_ctx=self.session._chat_ctx,<br>            firebase=self.firebase,<br>            userdata=context.userdata,<br>            config=self.config<br>        )<br><br>    def _handoff_if_done(self):<br>        &quot;&quot;&quot;Check if enough info is collected&quot;&quot;&quot;<br>        if self.userdata.customer_name and self.userdata.customer_phone and self.userdata.current_order:<br>            return &quot;You may now confirm the order.&quot;<br>        return None<br><br>class ReservationAgent(BaseRestaurantAgent):<br>    def __init__(self, chat_ctx, firebase, userdata: UserData, config: AgentConfig):<br>        super().__init__(chat_ctx, firebase, userdata, config)<br>        self.instructions = (<br>            &quot;You&#39;re a friendly cafe staff member helping with table reservations. Chat naturally about &quot;<br>            &quot;when they&#39;d like to come in and how many people. Ask for their name and phone in a casual way &quot;<br>            &quot;when you need it. Be warm and welcoming, like you&#39;re genuinely excited to have them visit.&quot;<br>        )<br><br>    @function_tool()<br>    async def set_reservation_details(self, context: RunContext[UserData], date: str, time: str, party_size: int):<br>        context.userdata.reservation_date = date<br>        context.userdata.reservation_time = time<br>        context.userdata.party_size = party_size<br>        return self._handoff_if_done()<br><br>    @function_tool()<br>    async def confirm_reservation(self, context: RunContext[UserData]):<br>        &quot;&quot;&quot;Hand off to ConfirmationAgent to review reservation details&quot;&quot;&quot;<br>        return ConfirmationAgent(chat_ctx=self.session._chat_ctx, firebase=self.firebase, userdata=context.userdata, config=self.config)<br><br>    def _handoff_if_done(self):<br>        if (<br>            self.userdata.customer_name<br>            and self.userdata.customer_phone<br>            and self.userdata.reservation_date<br>            and self.userdata.reservation_time<br>            and self.userdata.party_size &gt; 0<br>        ):<br>            return &quot;You can now use `confirm_reservation` to save this.&quot;<br>        return None<br><br><br>class ConfirmationAgent(BaseRestaurantAgent):<br>    def __init__(self, chat_ctx, firebase, userdata: UserData, config: AgentConfig):<br>        super().__init__(chat_ctx, firebase, userdata, config)<br>        self.instructions = (<br>            &quot;You&#39;re a friendly cafe staff member double-checking the order or reservation. &quot;<br>            &quot;Be conversational and natural - like you&#39;re just making sure you got everything right. &quot;<br>            &quot;Only mention the key details that matter (what they ordered, when they&#39;re coming, etc.). &quot;<br>            &quot;Don&#39;t repeat obvious information. Sound like a real person, not a robot reading a checklist.&quot;<br>        )<br><br>    async def on_enter(self):<br>        &quot;&quot;&quot;Present key information for confirmation in a natural way&quot;&quot;&quot;<br>        # Create a natural summary focusing on key details<br>        if hasattr(self.userdata, &#39;current_order&#39;) and self.userdata.current_order:<br>            # For orders - focus on items and pickup details<br>            order_summary = self._create_natural_order_summary()<br>            await self.session.generate_reply(<br>                instructions=f&quot;Casually confirm the order details: {order_summary}. &quot;<br>                &quot;Sound natural and friendly, like you&#39;re just double-checking you got their order right.&quot;,<br>            )<br>        elif hasattr(self.userdata, &#39;reservation_date&#39;) and self.userdata.reservation_date:<br>            # For reservations - focus on time and party size<br>            reservation_summary = self._create_natural_reservation_summary()<br>            await self.session.generate_reply(<br>                instructions=f&quot;Casually confirm the reservation: {reservation_summary}. &quot;<br>                &quot;Sound warm and welcoming, like you&#39;re looking forward to seeing them.&quot;,<br>            )<br>        else:<br>            await self.session.generate_reply(<br>                instructions=&quot;Something seems to be missing. Let me help you complete your order or reservation.&quot;,<br>            )<br><br>    def _create_natural_order_summary(self) -&gt; str:<br>        &quot;&quot;&quot;Create a natural summary of the order focusing on key details&quot;&quot;&quot;<br>        items = []<br>        if hasattr(self.userdata, &#39;current_order&#39;) and self.userdata.current_order:<br>            for item in self.userdata.current_order:<br>                qty = item.get(&#39;quantity&#39;, 1)<br>                name = item.get(&#39;item&#39;, &#39;&#39;)<br>                if qty &gt; 1:<br>                    items.append(f&quot;{qty} {name}&quot;)<br>                else:<br>                    items.append(name)<br>        <br>        order_text = &quot;, &quot;.join(items) if items else &quot;your order&quot;<br>        <br>        # Add name if we have it<br>        name_part = &quot;&quot;<br>        if hasattr(self.userdata, &#39;customer_name&#39;) and self.userdata.customer_name:<br>            name_part = f&quot; for {self.userdata.customer_name}&quot;<br>        <br>        return f&quot;{order_text}{name_part}&quot;<br><br>    def _create_natural_reservation_summary(self) -&gt; str:<br>        &quot;&quot;&quot;Create a natural summary of the reservation focusing on key details&quot;&quot;&quot;<br>        parts = []<br>        <br>        if hasattr(self.userdata, &#39;reservation_date&#39;) and self.userdata.reservation_date:<br>            parts.append(f&quot;on {self.userdata.reservation_date}&quot;)<br>        <br>        if hasattr(self.userdata, &#39;reservation_time&#39;) and self.userdata.reservation_time:<br>            parts.append(f&quot;at {self.userdata.reservation_time}&quot;)<br>        <br>        if hasattr(self.userdata, &#39;party_size&#39;) and self.userdata.party_size:<br>            people = &quot;person&quot; if self.userdata.party_size == 1 else &quot;people&quot;<br>            parts.append(f&quot;for {self.userdata.party_size} {people}&quot;)<br>        <br>        if hasattr(self.userdata, &#39;customer_name&#39;) and self.userdata.customer_name:<br>            parts.append(f&quot;under {self.userdata.customer_name}&quot;)<br>        <br>        return &quot;table &quot; + &quot; &quot;.join(parts) if parts else &quot;your reservation&quot;<br><br>    @function_tool()<br>    async def confirm_order(self, context: RunContext[UserData]):<br>        &quot;&quot;&quot;Confirm and save the order to Firebase&quot;&quot;&quot;<br>        try:<br>            if not (context.userdata.customer_name and context.userdata.customer_phone and <br>                    hasattr(context.userdata, &#39;current_order&#39;) and context.userdata.current_order):<br>                return &quot;I just need to get your name and phone number to complete this order.&quot;<br>            <br>            from app.models.restaurant import CustomerOrder, OrderItem<br>            from datetime import datetime<br>            import uuid<br>            <br>            # Convert current_order items to OrderItem objects<br>            order_items = []<br>            for item_data in context.userdata.current_order:<br>                order_item = OrderItem(<br>                    menu_item_id=item_data.get(&#39;item&#39;, &#39;&#39;),<br>                    quantity=item_data.get(&#39;quantity&#39;, 1),<br>                    unit_price=0.0,  # You&#39;ll need to look up the actual price<br>                    modifications=item_data.get(&#39;modifications&#39;, [])<br>                )<br>                order_items.append(order_item)<br>            <br>            # Create CustomerOrder object<br>            order = CustomerOrder(<br>                id=str(uuid.uuid4()),<br>                customer_phone=context.userdata.customer_phone,<br>                customer_name=context.userdata.customer_name,<br>                items=order_items,<br>                order_time=datetime.now(),<br>                status=&#39;pending&#39;,<br>                payment_method=getattr(context.userdata, &#39;payment_method&#39;, &#39;cash&#39;),<br>                call_id=getattr(context.userdata, &#39;call_id&#39;, &#39;&#39;),<br>                agent_id=getattr(context.userdata, &#39;agent_id&#39;, &#39;&#39;),<br>                special_instructions=getattr(context.userdata, &#39;special_instructions&#39;, &#39;&#39;)<br>            )<br>            <br>            await self.firebase.create_order(order)<br>            return &quot;Perfect! Your order is all set. We&#39;ll have it ready for you soon!&quot;<br>            <br>        except Exception as e:<br>            logger.error(f&quot;Failed to save order: {e}&quot;)<br>            return &quot;Oops, something went wrong on our end. Let me try that again for you.&quot;<br><br>    @function_tool()<br>    async def confirm_reservation(self, context: RunContext[UserData]):<br>        &quot;&quot;&quot;Confirm and save the reservation to Firebase&quot;&quot;&quot;<br>        try:<br>            if not (context.userdata.customer_name and context.userdata.customer_phone and <br>                    hasattr(context.userdata, &#39;reservation_date&#39;) and context.userdata.reservation_date and<br>                    hasattr(context.userdata, &#39;reservation_time&#39;) and context.userdata.reservation_time and<br>                    hasattr(context.userdata, &#39;party_size&#39;) and context.userdata.party_size &gt; 0):<br>                return &quot;I just need a few more details to get your table reserved.&quot;<br>            <br>            await self.firebase.save_reservation(context.userdata)<br>            return &quot;Great! Your table is reserved. We&#39;re looking forward to seeing you!&quot;<br>            <br>        except Exception as e:<br>            logger.error(f&quot;Failed to save reservation: {e}&quot;)<br>            return &quot;Oops, something went wrong on our end. Let me try that again for you.&quot;<br><br>    @function_tool()<br>    async def request_correction(self, context: RunContext[UserData], field: str, new_value: str):<br>        &quot;&quot;&quot;Allow customer to correct specific information&quot;&quot;&quot;<br>        field_mapping = {<br>            &#39;name&#39;: &#39;customer_name&#39;,<br>            &#39;phone&#39;: &#39;customer_phone&#39;, <br>            &#39;email&#39;: &#39;customer_email&#39;,<br>            &#39;date&#39;: &#39;reservation_date&#39;,<br>            &#39;time&#39;: &#39;reservation_time&#39;,<br>            &#39;party_size&#39;: &#39;party_size&#39;<br>        }<br>        <br>        if field in field_mapping:<br>            attr_name = field_mapping[field]<br>            if field == &#39;party_size&#39;:<br>                setattr(context.userdata, attr_name, int(new_value))<br>            else:<br>                setattr(context.userdata, attr_name, new_value)<br>            return f&quot;Got it, changed to {new_value}. Does everything look right now?&quot;<br>        <br>        return &quot;Just let me know what you&#39;d like to change - your name, phone, date, time, or party size.&quot;<br><br>    @function_tool()<br>    async def cancel_request(self) -&gt; str:<br>        &quot;&quot;&quot;Cancel the current request&quot;&quot;&quot;<br>        return &quot;No problem! What else can I help you with?&quot;</pre><p>The confirmation agent is added in to ensure the details captured are correct and we don’t end up with wrong details. The LLM will ensure it’s natural and less repetitive. You will also notice we are using the confirmation agent to save to firebase everything else saves to the session, to reduce on latency problems caused by database saves and the rest.</p><h3>Configuration</h3><p>Now that the agents are set up, we need to add it in to the entrypoint where we also define our config. We load the sensitive keys using a config. Instead of loading everything one by one.</p><pre>import os<br>from dataclasses import dataclass<br>from typing import Optional<br>import logging<br><br>logger = logging.getLogger(__name__)<br><br>@dataclass<br>class AgentConfig:<br>    &quot;&quot;&quot;Configuration for agent STT, LLM, TTS, and VAD settings&quot;&quot;&quot;<br>    # Required fields (no defaults) - must come first<br>    openai_api_key: str<br>    deepgram_api_key: str<br>    cartesia_api_key: str<br>    <br>    # Optional fields with defaults - must come after required fields<br>    openai_model: str = &quot;gpt-4o-mini&quot;<br>    cartesia_voice_id: Optional[str] = None<br>    vad_model: str = &quot;silero&quot;<br>    firebase_service_account_path: str = &quot;service.json&quot;<br>    sip_phone_number: Optional[str] = None<br>    sip_trunk_address: Optional[str] = None<br>    sip_username: Optional[str] = None<br>    sip_password: Optional[str] = None<br>    sip_outbound_trunk_id: Optional[str] = None<br><br>def load_config() -&gt; AgentConfig:<br>    &quot;&quot;&quot;Load configuration from environment variables&quot;&quot;&quot;<br>    <br>    # Required API keys<br>    openai_api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>    deepgram_api_key = os.getenv(&quot;DEEPGRAM_API_KEY&quot;) <br>    cartesia_api_key = os.getenv(&quot;CARTESIA_API_KEY&quot;)<br>    <br>    if not openai_api_key:<br>        raise ValueError(&quot;OPENAI_API_KEY environment variable is required&quot;)<br>    if not deepgram_api_key:<br>        raise ValueError(&quot;DEEPGRAM_API_KEY environment variable is required&quot;)<br>    if not cartesia_api_key:<br>        raise ValueError(&quot;CARTESIA_API_KEY environment variable is required&quot;)<br>    <br>    # Optional configurations with defaults<br>    openai_model = os.getenv(&quot;OPENAI_MODEL&quot;, &quot;gpt-4o-mini&quot;)<br>    cartesia_voice_id = os.getenv(&quot;CARTESIA_VOICE_ID&quot;)<br>    firebase_service_account = os.getenv(&quot;FIREBASE_SERVICE_ACCOUNT_PATH&quot;, &quot;service.json&quot;)<br>    <br>    # SIP configurations<br>    sip_phone_number = os.getenv(&quot;SIP_PHONE_NUMBER&quot;)<br>    sip_trunk_address = os.getenv(&quot;SIP_TRUNK_ADDRESS&quot;)<br>    sip_username = os.getenv(&quot;SIP_USERNAME&quot;)<br>    sip_password = os.getenv(&quot;SIP_PASSWORD&quot;)<br>    sip_outbound_trunk_id = os.getenv(&quot;SIP_OUTBOUND_TRUNK_ID&quot;)<br>    <br>    logger.info(f&quot;Loaded config - OpenAI model: {openai_model}&quot;)<br>    <br>    return AgentConfig(<br>        openai_api_key=openai_api_key,<br>        openai_model=openai_model,<br>        deepgram_api_key=deepgram_api_key,<br>        cartesia_api_key=cartesia_api_key,<br>        cartesia_voice_id=cartesia_voice_id,<br>        firebase_service_account_path=firebase_service_account,<br>        sip_phone_number=sip_phone_number,<br>        sip_trunk_address=sip_trunk_address,<br>        sip_username=sip_username,<br>        sip_password=sip_password,<br>        sip_outbound_trunk_id=sip_outbound_trunk_id<br>    )<br><br>def validate_config(config: AgentConfig) -&gt; bool:<br>    &quot;&quot;&quot;Validate that all required configuration is present&quot;&quot;&quot;<br>    required_fields = [<br>        config.openai_api_key,<br>        config.deepgram_api_key, <br>        config.cartesia_api_key<br>    ]<br>    <br>    if not all(required_fields):<br>        logger.error(&quot;Missing required API keys in configuration&quot;)<br>        return False<br>        <br>    logger.info(&quot;Configuration validation passed&quot;)<br>    return True</pre><p>We also load our firebase manager and add in the service key path.</p><pre># Initialize Firebase manager<br> firebase = FirebaseManager(config.firebase_service_account_path)</pre><p>After this, we load SIP configuration which holds the phone number and the details we want. We will talk about SIP in details later on</p><pre>sip_handler = SipCallHandler(firebase)<br>        <br># Set up SIP trunk on first run<br>await sip_handler.setup_sip_trunk(config)<br><br># Create call info (SIP info automatically handled by LiveKit when sip_enabled=True)<br>call_info = {<br>    &quot;call_id&quot;: ctx.room.name,<br>    &quot;caller_number&quot;: getattr(ctx.job, &#39;sip&#39;, {}).get(&#39;from_number&#39;, &#39;unknown&#39;) if hasattr(ctx.job, &#39;sip&#39;) else &quot;web_user&quot;,<br>    &quot;called_number&quot;: getattr(ctx.job, &#39;sip&#39;, {}).get(&#39;to_number&#39;, &#39;restaurant&#39;) if hasattr(ctx.job, &#39;sip&#39;) else &quot;restaurant&quot;,<br>    &quot;call_type&quot;: &quot;sip_call&quot; if hasattr(ctx.job, &#39;sip&#39;) and ctx.job.sip else &quot;web_session&quot;<br>}</pre><p>We also initialize our user data ensuring its unique for every conversation by adding in the room id.</p><pre># Create UserData instance for the session<br>userdata = UserData(<br>    call_id=call_info[&quot;call_id&quot;],<br>    caller_number=call_info[&quot;caller_number&quot;],<br>    agent_id=&quot;restaurant-assistant&quot;,<br>    session_id=call_info[&quot;call_id&quot;],<br>    intent=&quot;incoming_call&quot;<br>)</pre><p>Once this is complete we can set up the agents, since we have a intent agent to determine what the caller wants, we can initialize the IntentClassifier agent and it will route the caller to the right agent. After that we add in the AgentSession, to coordinate the agents and maintain state. And finally initialize the session.</p><pre>intent_classifier = IntentClassifierAgent(<br>    chat_ctx=None,  # Will be set by session<br>    firebase=firebase,<br>    userdata=userdata,<br>    config=config<br>)<br><br># Start the agent session<br>session = AgentSession[UserData](userdata=userdata)<br><br>await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)<br><br># Start the agent session with error handling<br>try:<br>    await session.start(<br>        agent=intent_classifier,  # Start with the intent classifier<br>        room=ctx.room,<br>    )<br>    <br>    <br>except Exception as e:<br>    # Handle agent session errors<br>    logger.error(f&quot;Agent session error: {e}&quot;)<br>    await error_handler.handle_agent_error(e, session.run_context, intent_classifier)<br>    raise</pre><p>Finally with the entry point complete, we send it to our worker</p><pre>if __name__ == &quot;__main__&quot;:<br>    # Configure CLI options for SIP support<br>    cli.run_app(WorkerOptions(<br>        entrypoint_fnc=entrypoint,<br>        load_fnc=calculate_worker_load,<br>        num_idle_processes=2,  # Keep 2 processes warm<br>        load_threshold=0.8,  # Mark as unavailable at 80% load<br>        job_memory_warn_mb=1000,  # Warn at 1GB memory usage<br>        job_memory_limit_mb=2000,  <br>        max_retry=3,<br>        port=8081,<br>    ))</pre><h3>FreeSwitch Configuration</h3><p>Now we have the app set up and is able to run without any issues and records the data to firebase, but the idea was to explain how to connect SIP to Livekit, and deploy it to Google Cloud. To ensure there are no issues on production we need to set up a local freeswitch server to connect to.</p><p>So what is FreeSwitch you might ask.</p><p>FreeSwitch is the software that allows a caller to connect to Livekit agents over the internet using your phone and not via the web. In other words its the bridge between the traditional SIP with modern WebRTC which LiveKit is.</p><p>To be able to handle this we need to tell Freeswitch how to connect to our Livekit server and not connect to any other server. We will set up the config using the old way, XML.</p><p>It uses the <em>vars.xml</em> which acts as keys store and the <em>freeswitch.xml</em> which houses all settings. The <em>vars.xml</em> which will get its values securely from the .<em>env</em></p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;include&gt;<br>  &lt;!-- FreeSWITCH Variables for Restaurant AI --&gt;<br>  <br>  &lt;!-- Network settings --&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;default_password=$${FREESWITCH_DEFAULT_PASSWORD}&quot;/&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;domain=$${FREESWITCH_DOMAIN}&quot;/&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;domain_name=$${FREESWITCH_DOMAIN}&quot;/&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;hold_music=$${FREESWITCH_HOLD_MUSIC}&quot;/&gt;<br>  <br>  &lt;!-- SIP settings --&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;external_rtp_ip=auto-nat&quot;/&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;external_sip_ip=auto-nat&quot;/&gt;<br>  <br>  &lt;!-- Codec preferences --&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;global_codec_prefs=G722,opus@48000h@20i,PCMA,PCMU,GSM&quot;/&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;outbound_codec_prefs=G722,opus@48000h@20i,PCMA,PCMU,GSM&quot;/&gt;<br>  <br>  &lt;!-- Restaurant specific settings --&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;restaurant_name=$${RESTAURANT_NAME}&quot;/&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;livekit_url=$${LIVEKIT_URL}&quot;/&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;livekit_api_key=$${LIVEKIT_API_KEY}&quot;/&gt;<br>  &lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;livekit_secret=$${LIVEKIT_API_SECRET}&quot;/&gt;<br>  <br>&lt;/include&gt;</pre><p>The settings</p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;document type=&quot;freeswitch/xml&quot;&gt;<br>  <br>  &lt;section name=&quot;configuration&quot; description=&quot;Various Configuration&quot;&gt;<br>    <br>    &lt;!-- Event Socket (for LiveKit integration) --&gt;<br>    &lt;configuration name=&quot;event_socket.conf&quot; description=&quot;Socket Client&quot;&gt;<br>      &lt;settings&gt;<br>        &lt;param name=&quot;nat-map&quot; value=&quot;false&quot;/&gt;<br>        &lt;param name=&quot;listen-ip&quot; value=&quot;0.0.0.0&quot;/&gt;<br>        &lt;param name=&quot;listen-port&quot; value=&quot;8021&quot;/&gt;<br>        &lt;param name=&quot;password&quot; value=&quot;ClueCon&quot;/&gt;<br>        &lt;param name=&quot;apply-inbound-acl&quot; value=&quot;loopback.auto&quot;/&gt;<br>        &lt;param name=&quot;stop-on-bind-error&quot; value=&quot;true&quot;/&gt;<br>      &lt;/settings&gt;<br>    &lt;/configuration&gt;<br><br>    &lt;!-- SIP Profile for incoming calls --&gt;<br>    &lt;configuration name=&quot;sofia.conf&quot; description=&quot;sofia Endpoint&quot;&gt;<br>      &lt;global_settings&gt;<br>        &lt;param name=&quot;log-level&quot; value=&quot;0&quot;/&gt;<br>        &lt;param name=&quot;abort-on-empty-external-ip&quot; value=&quot;true&quot;/&gt;<br>        &lt;param name=&quot;auto-restart&quot; value=&quot;false&quot;/&gt;<br>      &lt;/global_settings&gt;<br>      <br>      &lt;profiles&gt;<br>        &lt;profile name=&quot;external&quot;&gt;<br>          &lt;gateways&gt;<br>            &lt;!-- Add your SIP provider gateway here --&gt;<br>            &lt;gateway name=&quot;restaurant-sip&quot;&gt;<br>              &lt;param name=&quot;username&quot; value=&quot;your-sip-username&quot;/&gt;<br>              &lt;param name=&quot;password&quot; value=&quot;your-sip-password&quot;/&gt;<br>              &lt;param name=&quot;realm&quot; value=&quot;your-sip-provider.com&quot;/&gt;<br>              &lt;param name=&quot;proxy&quot; value=&quot;your-sip-provider.com&quot;/&gt;<br>              &lt;param name=&quot;register&quot; value=&quot;true&quot;/&gt;<br>              &lt;param name=&quot;expire-seconds&quot; value=&quot;600&quot;/&gt;<br>              &lt;param name=&quot;retry-seconds&quot; value=&quot;30&quot;/&gt;<br>            &lt;/gateway&gt;<br>          &lt;/gateways&gt;<br>          <br>          &lt;settings&gt;<br>            &lt;param name=&quot;context&quot; value=&quot;public&quot;/&gt;<br>            &lt;param name=&quot;rfc2833-pt&quot; value=&quot;101&quot;/&gt;<br>            &lt;param name=&quot;sip-port&quot; value=&quot;5060&quot;/&gt;<br>            &lt;param name=&quot;dialplan&quot; value=&quot;XML&quot;/&gt;<br>            &lt;param name=&quot;dtmf-duration&quot; value=&quot;2000&quot;/&gt;<br>            &lt;param name=&quot;codec-prefs&quot; value=&quot;PCMU,PCMA&quot;/&gt;<br>            &lt;param name=&quot;use-rtp-timer&quot; value=&quot;true&quot;/&gt;<br>            &lt;param name=&quot;rtp-timer-name&quot; value=&quot;soft&quot;/&gt;<br>            &lt;param name=&quot;manage-presence&quot; value=&quot;false&quot;/&gt;<br>            &lt;param name=&quot;inbound-codec-negotiation&quot; value=&quot;generous&quot;/&gt;<br>            &lt;param name=&quot;nonce-ttl&quot; value=&quot;60&quot;/&gt;<br>            &lt;param name=&quot;auth-calls&quot; value=&quot;false&quot;/&gt;<br>            &lt;param name=&quot;auth-all-packets&quot; value=&quot;false&quot;/&gt;<br>            &lt;param name=&quot;ext-rtp-ip&quot; value=&quot;auto-nat&quot;/&gt;<br>            &lt;param name=&quot;ext-sip-ip&quot; value=&quot;auto-nat&quot;/&gt;<br>            &lt;param name=&quot;rtp-timeout-sec&quot; value=&quot;300&quot;/&gt;<br>            &lt;param name=&quot;rtp-hold-timeout-sec&quot; value=&quot;1800&quot;/&gt;<br>            &lt;param name=&quot;tls&quot; value=&quot;false&quot;/&gt;<br>            &lt;param name=&quot;inbound-late-negotiation&quot; value=&quot;true&quot;/&gt;<br>            &lt;param name=&quot;inbound-zrtp-passthru&quot; value=&quot;true&quot;/&gt;<br>          &lt;/settings&gt;<br>        &lt;/profile&gt;<br>      &lt;/profiles&gt;<br>    &lt;/configuration&gt;<br><br>    &lt;!-- Modules to load --&gt;<br>    &lt;configuration name=&quot;modules.conf&quot; description=&quot;Modules&quot;&gt;<br>      &lt;modules&gt;<br>        &lt;!-- Core modules --&gt;<br>        &lt;load module=&quot;mod_console&quot;/&gt;<br>        &lt;load module=&quot;mod_logfile&quot;/&gt;<br>        &lt;load module=&quot;mod_enum&quot;/&gt;<br>        &lt;load module=&quot;mod_cdr_csv&quot;/&gt;<br>        &lt;load module=&quot;mod_event_socket&quot;/&gt;<br>        <br>        &lt;!-- Media/codec modules --&gt;<br>        &lt;load module=&quot;mod_native_file&quot;/&gt;<br>        &lt;load module=&quot;mod_sndfile&quot;/&gt;<br>        &lt;load module=&quot;mod_tone_stream&quot;/&gt;<br>        &lt;load module=&quot;mod_local_stream&quot;/&gt;<br>        &lt;load module=&quot;mod_dptools&quot;/&gt;<br>        <br>        &lt;!-- SIP module --&gt;<br>        &lt;load module=&quot;mod_sofia&quot;/&gt;<br>        <br>        &lt;!-- Dialplan modules --&gt;<br>        &lt;load module=&quot;mod_dialplan_xml&quot;/&gt;<br>        <br>        &lt;!-- Codec modules --&gt;<br>        &lt;load module=&quot;mod_g711&quot;/&gt;<br>        &lt;load module=&quot;mod_g729&quot;/&gt;<br>        &lt;load module=&quot;mod_opus&quot;/&gt; <br>        &lt;load module=&quot;mod_amr&quot;/&gt;<br>      &lt;/modules&gt;<br>    &lt;/configuration&gt;<br><br>  &lt;/section&gt;<br><br>  &lt;!-- Dialplan for routing calls to LiveKit --&gt;<br>  &lt;section name=&quot;dialplan&quot; description=&quot;Regex/XML Dialplan&quot;&gt;<br>    &lt;context name=&quot;public&quot;&gt;<br>      <br>      &lt;!-- Route incoming calls to restaurant assistant --&gt;<br>      &lt;extension name=&quot;restaurant-assistant&quot;&gt;<br>        &lt;condition field=&quot;destination_number&quot; expression=&quot;^(restaurant|1234567890)$&quot;&gt;<br>          &lt;action application=&quot;answer&quot;/&gt;<br>          &lt;action application=&quot;sleep&quot; data=&quot;1000&quot;/&gt;<br>          &lt;action application=&quot;set&quot; data=&quot;call_direction=inbound&quot;/&gt;<br>          &lt;action application=&quot;set&quot; data=&quot;restaurant_call=true&quot;/&gt;<br>          &lt;!-- This will be handled by LiveKit SIP integration --&gt;<br>          &lt;action application=&quot;socket&quot; data=&quot;127.0.0.1:8080 async full&quot;/&gt;<br>        &lt;/condition&gt;<br>      &lt;/extension&gt;<br>      <br>      &lt;!-- Default handler --&gt;<br>      &lt;extension name=&quot;default&quot;&gt;<br>        &lt;condition field=&quot;destination_number&quot; expression=&quot;^.*$&quot;&gt;<br>          &lt;action application=&quot;answer&quot;/&gt;<br>          &lt;action application=&quot;playback&quot; data=&quot;tone_stream://%(2000,4000,440,480);loops=3&quot;/&gt;<br>          &lt;action application=&quot;hangup&quot;/&gt;<br>        &lt;/condition&gt;<br>      &lt;/extension&gt;<br>      <br>    &lt;/context&gt;<br>  &lt;/section&gt;<br><br>&lt;/document&gt;</pre><p>I will explain each section to show how it will be used to ensure everything works as expected.</p><p>So we have two sections, the configuration and the dialplan</p><pre>&lt;document type=&quot;freeswitch/xml&quot;&gt;<br>  &lt;section name=&quot;configuration&quot;&gt;...&lt;/section&gt;<br>  &lt;section name=&quot;dialplan&quot;&gt;...&lt;/section&gt;<br>&lt;/document&gt;</pre><ol><li><strong>Configuration</strong>: Defines system wide settings</li><li><strong>Dialplan</strong>: Handles the routing of outgoing and incoming calls and how the call should behave.</li></ol><p><strong>Event Socket</strong></p><pre>&lt;configuration name=&quot;event_socket.conf&quot;&gt;<br>  ...<br>&lt;/configuration&gt;</pre><p>This configuration allows our app to connect to Freeswitch over a TCP connection and control the calls programmatically. Inside it we have the following options</p><ol><li><strong><em>listen-ip=”0.0.0.0&quot;</em></strong></li></ol><p>Listens on all interfaces for socket clients.</p><p>2. <strong><em>listen-port=”8021&quot;</em></strong></p><p>Default port for ESL (Event Socket Library) clients.</p><p>3.<strong><em> password=”ClueCon”</em></strong></p><p>Default password (change this in production!).</p><p>4. <strong><em>apply-inbound-acl=”loopback.auto”</em></strong></p><p>Allows us to test the app locally. You can download the app from playstore to test it out and add in the config details to connect</p><p>5.<strong><em> stop-on-bind-error=”true”</em></strong></p><p>Prevents FreeSWITCH from starting if socket can’t bind</p><h3>SIP Setup</h3><p>The config sets up the <strong>SIP endpoint</strong> that FreeSWITCH uses to receive/make calls via SIP.</p><pre>&lt;configuration name=&quot;sofia.conf&quot;&gt;<br>  ...<br>&lt;/configuration&gt;</pre><p>It is made up of two parts mainly:</p><ol><li><strong>global_settings</strong></li></ol><pre># Prevents startup errors if the external IP is not detected.<br># Its turned off for debugging<br>&lt;param name=&quot;auto-restart&quot; value=&quot;false&quot;/&gt;<br>&lt;param name=&quot;abort-on-empty-external-ip&quot; value=&quot;true&quot;/&gt;</pre><p>2. <strong>profiles</strong></p><p>We are able to define our connection to a SIP like Twilio or we set up our own PBX. Mainly for registration. You will mainly see the following realm, proxy – usually the SIP domain/hostname from our provider.</p><pre>&lt;gateway name=&quot;restaurant-sip&quot;&gt;<br>  ...<br>&lt;/gateway&gt;</pre><p>Inside the profiles are the settings.</p><pre>&lt;param name=&quot;sip-port&quot; value=&quot;5060&quot;/&gt;<br>&lt;param name=&quot;codec-prefs&quot; value=&quot;$${global_codec_prefs}&quot;/&gt;<br>&lt;param name=&quot;context&quot; value=&quot;public&quot;/&gt;</pre><p>The sip-port=&quot;5060&quot; → default unencrypted SIP port, this matches with what we set in docker compose. context=&quot;public&quot; → all calls to this profile land in the <strong>public dialplan context</strong>. We also set the audio codecs, codec-prefs → allowed audio codecs (PCMU = G.711 µ-law) actually stands for <strong>Pulse Code Modulation µ-law</strong>. G.711 is the standard telephony audio. Its latency is very low with a bitrate of <strong>64kbps. </strong>Its quality is not HD though but very good for testing. <br>The problem we might have is that Livekit uses Opus codec while on the SIP side PCMU is used. Freeswitch will handle the transcoding between Opus and PMCU. auth-calls=&quot;false&quot; → disable auth for inbound calls. We will enable it when deploying to production. rtp-timeout-sec → number of seconds to wait before we drop the call.</p><p><strong>Modules</strong></p><p>Tells FreeSwitch which plugins to load. In our config we are using the following plugins.</p><p><strong>mod_sofia</strong>: The SIP stack. Required for SIP functionality.</p><p><strong>mod_event_socket</strong>: Enables Event Socket for control/monitoring.</p><p><strong>mod_g711</strong>, <strong>mod_g729</strong>, <strong>mod_amr</strong>: Audio codecs for transcoding.</p><p><strong>mod_dialplan_xml</strong>: Processes the XML dialplan.</p><p><strong>mod_console, mod_logfile</strong>: Mainly for logging.</p><pre>&lt;configuration name=&quot;modules.conf&quot;&gt;<br>  ...<br>&lt;/configuration&gt;</pre><p>The current flow being SIP → media → call routing → external control.</p><p><strong>DialPlan: Routing the call</strong></p><p>The config defines how the call is routed. And we use extension to define how it flows.</p><pre>&lt;section name=&quot;dialplan&quot;&gt;<br>  &lt;context name=&quot;public&quot;&gt;...&lt;/context&gt;<br>&lt;/section&gt;</pre><p>Currently there are 2:</p><p><strong>restaurant-assistant.</strong></p><p>This is a very critical section of the app because it sends the media in this case the voice to our LiveKit server we have built. The flow is that when a call comes in freeswitch via the port 5060, it will check whether the number matches with the number we set in. (<em>You can change that to your test number</em>). Once it matches it will route the call control and media via the socket app to a service listening on port 127.0.0.1:8080 . This will happen back and forth to allow for the voice call to happen.</p><pre>&lt;extension name=&quot;restaurant-assistant&quot;&gt;<br>  &lt;condition field=&quot;destination_number&quot; expression=&quot;^(restaurant|$${RESTAURANT_PHONE_NUMBER})$&quot;&gt;<br>    ...<br>    &lt;action application=&quot;socket&quot; data=&quot;backend:8080 async full&quot;/&gt;<br>  &lt;/condition&gt;<br>&lt;/extension&gt;</pre><p>It is made up of the following components.</p><p><em>answer</em>: Answers the SIP call</p><p><em>sleep 1000</em>: Pause briefly (allow connection to settle)</p><p><em>set call_direction=inbound</em>: This is an optional field and it sets the call metadata</p><p><em>set restaurant_call=true</em>: Handles the routing logic</p><p><em>socket 127.0.0.1:8080 async full</em>: Hands off call control to our livekit server</p><p><strong>default</strong></p><p>This section handles all invalid calls and handles them gracefully. It answers sends a fake ring and hangs up after 3 retries.</p><pre>&lt;extension name=&quot;default&quot;&gt;<br>  ...<br>&lt;/extension&gt;</pre><p>Now a very critical part we forgot is the <em>vars.xml . </em>It makes use of .env variables. We can then change these based on whether we are building locally or in production.</p><pre>&lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;livekit_url=$${LIVEKIT_URL}&quot;/&gt;<br>&lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;livekit_api_key=$${LIVEKIT_API_KEY}&quot;/&gt;<br>&lt;X-PRE-PROCESS cmd=&quot;set&quot; data=&quot;livekit_secret=$${LIVEKIT_API_SECRET}&quot;/&gt;</pre><h3><strong>Testing</strong></h3><p>To be able to test the locally using <a href="https://play.google.com/store/apps/details?id=com.zoiper.android.app&amp;hl=en">Zoiper</a> which will call into our FreeSwitch server and connect to our assistant and mimic a production call to get any bugs that may come up.</p><h3>Deployment</h3><p>To connect to SIP you would need to choose a provider either one of these</p><ol><li>Twilio</li><li>Telnyx</li><li>Plivo</li></ol><p>You will get the SIP URI, and a phone number after purchasing. You can then associate the phone number with the URI depending on whether its outbound or inbound.</p><p>Now with all the configuration set up, it needs to be pushed to production. We have made our app to use environment keys so using secrets is going to be good because we can leverage google secret manager and call it from Cloud run to use in a secure way. Cloud build will be good since we can set up a trigger to make a new build from a PR merge on the main branch. The reason for this is that is will auto scale</p><p>As for GKE which allows for a more fine grained control is the best use case for production based assistant that serves different ports to millions of users. I will be writing more on this on the next article</p><h3>Conclusion</h3><p>Building agents is getting better with time and definitely easier the problem is how those agents scale in production and how the intergrate with traditional more common based technologies. Knowing how to do this well is extremely crucial for a service that not only works but a service that is almost a copy if not better than traditional service. The only reason why someone will use your app. <br>FreeSwitch is a great service but there are other alternative like</p><p>1. <strong>Kamailio/OpenSIPs</strong>: Extremely performant due to its lightweight. It needs to be paired with FreeSwitch since it does not handle RTP/media. It can also scaled to thousands of calls concurrently</p><p>2. <strong>JANUS</strong>: Small and provides low latency WebRTC to SIP bridging, though it only supports SIP compared to FreeSwitch.</p><p>3. <strong>Twilio</strong>: This is a fully cloud based service its very performant supports Global telephony but very expensive</p><p>You can get the link to the repo here and play around with.</p><p><a href="https://github.com/BrianMwas/vocare">GitHub - BrianMwas/vocare: Livekit application configured to use FreeSwitch</a></p><p>If you’d like to chat on what you are building hit me up on <a href="https://www.linkedin.com/in/mwangi-brian/">LinkedIn</a></p><p>Keep building! 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efaedf34757e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better Navigation in Flutter using GetX]]></title>
            <link>https://medium.com/@brianmwangi_dev/better-navigation-in-flutter-using-getx-ceeedd5c8f28?source=rss-28225805d05b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceeedd5c8f28</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Brian Mwangi]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 15:08:10 GMT</pubDate>
            <atom:updated>2021-08-11T02:52:30.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v-o6vclVBmTm1Pe2" /><figcaption>Photo by <a href="https://unsplash.com/@ed259?utm_source=medium&amp;utm_medium=referral">Ed 259</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Learn how to make a customized robust navigation system for your application by using GetX library. You will be able to use guards and leverage dependency injection so easy you’ll love it.</p><h3>Introduction</h3><p>Navigation in a small application is not that hard you only need to use the standard navigation that flutter comes packaged with. But when your project grows you’ll want to add authentication, authorizations, dynamic links with all of this you’d probably want less time thinking how navigation is going to work with all of this and spend more time building your business logic. GetX does a good job of helping you do this using middlewares and bindings, child routes.</p><h3>Get Started</h3><p>This post assumes you already have a flutter project created so we won’t go through creating one. You however need to add get package to your pubspec.yaml file.</p><p>Your pubspec.yaml file should have the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*rAUiHaFA5yIkFORwiM-_cg.png" /></figure><p>After doing this you are all set to go now you can go and warm up with some coffee.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26ufhEUSE22cPmYiQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26ufhEUSE22cPmYiQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F26ufhEUSE22cPmYiQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/f22dae764dfe5c31b214870a46948b4d/href">https://medium.com/media/f22dae764dfe5c31b214870a46948b4d/href</a></iframe><h3>Defining our Routes</h3><p>Getx navigation needs to be setup just before our app can use its functionalities. So replace <strong>MaterialApp</strong> in main.dart file with <strong>GetMaterialApp. </strong>This will allow us to use getx navigation functionalities. Notice the changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0ffbb905cba525843f6db6d0e705336/href">https://medium.com/media/d0ffbb905cba525843f6db6d0e705336/href</a></iframe><p>This is what you’ll have with a new flutter project but we’ll change <strong>MaterialApp</strong> widget to be the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1a34aace051e1bf25aee8f5cd8d330b/href">https://medium.com/media/a1a34aace051e1bf25aee8f5cd8d330b/href</a></iframe><p>So now you can separate your pages and use unique links to specify which one goes to which page using the <strong>GetPage</strong> name field. The links and pages can be separated into two different files or can be combined to one file. GetPage has the following properties that you can use.</p><p>For nested children it has a <strong>children</strong> property that allows you to associate a <strong>parent</strong> page with its <strong>children</strong> pages such as when you are using bottom bars or Tabs nested children will come in well.</p><h3>Getx Routing</h3><p>Navigating from one page to another is fairly simple you make use of <strong>Get.toNamed</strong> and pass in the link you don’t have to worry about forgetting which link is was since the links are globally passed. Hence moving to the dashboard would be as simple as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f83e3bb93613c1dfcf7876da634a3c4c/href">https://medium.com/media/f83e3bb93613c1dfcf7876da634a3c4c/href</a></iframe><h3>Passing Data between Routes.</h3><p>Its not always about changing screens but about the data between the screens. Sometimes we need to pass the data between the routes either when we want to go to a new screen go back, move a couple of steps backward until a certain predicate or condition is passed, All of these scenarios can be covered. Here’s a simple way to do it.</p><p>Data is passed as a map of string as the name or key and its value as the data you want to send. The arguments take a dynamic type meaning they can type of data from String, integers, double, a List.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eacf7b8685830e3e5aa60676e76a1e50/href">https://medium.com/media/eacf7b8685830e3e5aa60676e76a1e50/href</a></iframe><p>This method applies to all routing mechanism such as pop, offAllNamed etc.</p><h3>Bindings</h3><p>You can add dependency injection required for you page using Get bindings. You create the binding by extending the Bindings class and inject all dependencies there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27e71be39568dd3027d8781692736e7f/href">https://medium.com/media/27e71be39568dd3027d8781692736e7f/href</a></iframe><p>Get page can accept more than one binding. For example you can add more than one binding as an array passed to <strong>bindings. </strong>Or you can pass a single binding with binding property.</p><h3><strong>Setting Router Guards</strong></h3><p>As with any application you might need to add authentication and authorization. Getx allows you to add this by using <strong>Middlewares</strong>. You can add the middleware by extending the GetMiddleware class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68b6ae8d032e3ac26d75010100e17741/href">https://medium.com/media/68b6ae8d032e3ac26d75010100e17741/href</a></iframe><p>You can then add the middleware to where you want it applied in this case you can add it in the dashboard page route. The GetPage accepts an array of middlewares. Each middleware has an optional parameter that can be used to dictate the order in which the middlewares should be run. By default it is set to zero. But if we have another middleware we can set the priority.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07e5ccfcb884409c5c7de5195000da2f/href">https://medium.com/media/07e5ccfcb884409c5c7de5195000da2f/href</a></iframe><p>All authentication guards have the following functions that you can override based on particular scenarios.</p><p><strong>Redirect. </strong>When you make a route call this function is called first before any bindings and dependencies are injected. Its the best place to make authentication and authorization calls. It returns <strong>RouteSettings </strong>which take in route name. You can use the name to dictate where you want to redirect the client.</p><p><strong>OnPageCalled. </strong>This function is called before the widget is built. This function allows you to pass necessary data. For example you would want to add username as a title to the <strong>AppBar</strong>.</p><p><strong>OnBindingsStart. </strong>All pages that need a controller or a service would need dependencies will need to be added using bindings. Any validations can be done from within this function.</p><p><strong>OnPageBuildStart. </strong>This function is called right after the bindings initialize and before the page is built.</p><p><strong>OnPageDispose. </strong>Called right after disposing any controllers.</p><h3><strong>Page Transitions.</strong></h3><p>Getx helps create nice routing animations by passing a simple transition to Get navigate function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8544fd97bdccdfb479e139403fb31b6/href">https://medium.com/media/e8544fd97bdccdfb479e139403fb31b6/href</a></iframe><p>Using a good routing system allows for easy navigation within your application. For our next tutorial we will see how we can use Firebase messaging and dynamic links to dynamically move within the app from sent links and notifications.</p><p>You can find the full source code here.</p><p><a href="https://github.com/BrianMwas/GetxRouting.git">GitHub - BrianMwas/GetxRouting: Simple app showcasing Getx routing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceeedd5c8f28" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>