<?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 Abdullah Irfan on Medium]]></title>
        <description><![CDATA[Stories by Abdullah Irfan on Medium]]></description>
        <link>https://medium.com/@abdullahirfan99_80517?source=rss-c3537bc6965f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_JSqOqGPU_AZE9ud</url>
            <title>Stories by Abdullah Irfan on Medium</title>
            <link>https://medium.com/@abdullahirfan99_80517?source=rss-c3537bc6965f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:03:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdullahirfan99_80517/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[Making OpenAI Realtime Voice Agent Interruptible]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/making-openai-realtime-voice-agent-interruptible-cdb08e23e87b?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdb08e23e87b</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 17:01:00 GMT</pubDate>
            <atom:updated>2026-03-01T17:01:00.799Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHHcac_N1z3Y8WKVbSW6DA.png" /><figcaption>Image generated through OpenAI</figcaption></figure><p>In the <a href="https://medium.com/@abdullahirfan99_80517/upgrading-realtime-voice-to-our-agent-with-openai-realtime-e0aef09e84f7">previous article</a>, we upgraded our voicebot to use OpenAI Realtime. The browser stopped handling speech recognition and text-to-speech. Instead, we streamed raw PCM audio to the backend, relayed it over WebSocket to OpenAI, and received AI-generated voice responses back in real time. Even though voice wasn’t robitic not but still soemthing felt artificial. If the assistant started speaking and the user tried to interrupt, nothing happened. The model would continue talking until the response finished. That’s not how humans converse. In a real conversation, if someone starts speaking over you, you stop.</p><p>So the next step wasn’t about better models or better prompts. It was about conversation dynamics. We needed barge-in. The first architectural change happened on the backend. Previously, we had disabled turn detection entirely:</p><pre>turn_detection: null</pre><p>This meant the client was responsible for deciding when speech ended and when a response should be created. That worked, but it made interruption awkward because the server had no idea when the user began speaking again. We replaced that with server-side voice activity detection. In our constants, we introduced:</p><pre>TURN_DETECTION_SERVER_VAD: {<br>  type: &quot;server_vad&quot;,<br>  threshold: 0.5,<br>  prefix_padding_ms: 300,<br>  silence_duration_ms: 500,<br>  create_response: false,<br>  interrupt_response: true,<br>}</pre><p>And wired it into the realtime session update. The important line here is not the threshold tuning. It’s this:</p><pre>interrupt_response: true</pre><p>That flag tells OpenAI that if new speech begins, the active assistant response may be interrupted. But allowing interruption is only half the problem. We also need to tell the server exactly where to cut the current response. That’s where conversation.item.truncate comes in. We updated the backend relay to allow this event through:</p><pre>REALTIME_EVENTS.CONVERSATION_ITEM_TRUNCATE</pre><p>Without that, the frontend wouldn’t be allowed to request truncation. Then the real work moved to the client. Inside useRealtimeSession, when we receive:</p><pre>input_audio_buffer.speech_started</pre><p>we treat that as a hard interruption signal. The user has started speaking while the assistant is still talking. At that moment, we:</p><ol><li>Stop local playback immediately.</li><li>Calculate how much assistant audio has actually been played.</li><li>Send a truncate event to OpenAI with the precise playback duration.</li></ol><p>The truncate call looks like this:</p><pre>sendEvent({<br>  type: REALTIME.CONVERSATION_ITEM_TRUNCATE,<br>  item_id: currentAssistantItemIdRef.current,<br>  content_index: 0,<br>  audio_end_ms: getPlayedAudioMs(),<br>});</pre><p>That audio_end_ms matters more than it seems. We’re not just telling the server to stop. We’re telling it exactly how far into the response the user heard. This keeps conversation state consistent inside the model. There’s another subtle issue most people miss. Even after you truncate server-side, OpenAI may still stream a few audio deltas already in flight. If you don’t guard against that, the assistant will resume speaking for a fraction of a second.</p><p>So we added a mute mechanism, when we truncate an assistant item, we store its ID in a ref. During playback, if an incoming audio delta belongs to that same item, we simply ignore it. When a new assistant item begins, the mute resets. It’s a small detail, but without it, interruption feels unreliable. We also adjusted how speech-stop works. With server VAD enabled, the backend now detects when speech ends. So when the client receives:</p><pre>input_audio_buffer.speech_stopped</pre><p>we no longer manually commit audio. We simply send:</p><pre>sendEvent({ type: REALTIME.RESPONSE_CREATE });</pre><p>Server VAD owns the boundary detection. We still own when to request a response. That separation keeps orchestration clean.</p><p>Manual stop via UI still performs a commit explicitly. But natural end-of-speech relies on server detection now. The result feels completely different.</p><ol><li>The assistant starts speaking.</li><li>The user interrupts.</li><li>Playback stops instantly.</li><li>The assistant listens again.</li></ol><p>There is no overlap. No waiting for audio to finish. No desynchronization between client and server. It finally behaves like a conversation instead of a push-to-play audio system. Architecturally, this change didn’t touch our REST agent loop, tool execution layer, or model abstraction. The agent runtime remains exactly as before. We upgraded only the realtime transport and session control. Because it means the architecture is layered correctly. Voice transport evolves independently from reasoning orchestration.</p><p>Now we have:</p><ul><li>Realtime audio streaming</li><li>Server-side speech detection</li><li>True barge-in</li><li>Clean truncation</li><li>Stable playback control</li></ul><p>And the system still remains modular. This is the first moment where the voice interface actually feels interactive instead of scripted.</p><p>If you enjoyed this journey, please show some love by liking and sharing the article! The code for this story is availble in <a href="https://github.com/AbdullahDev0/medium-voicebot">GitHub Repo</a>’s feature/voice-interruption branch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdb08e23e87b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading Realtime Voice to Our Agent with OpenAI Realtime]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/upgrading-realtime-voice-to-our-agent-with-openai-realtime-e0aef09e84f7?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0aef09e84f7</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 17:01:02 GMT</pubDate>
            <atom:updated>2026-02-26T17:01:02.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCGULKn4LpxsBYF4BwhFig.png" /><figcaption>Image generated through OpenAI</figcaption></figure><p>In the previous article, we upgraded our voicebot into an agent. The backend could orchestrate tools, switch between local Ollama and cloud models, and execute multi-step reasoning loops. Architecturally, it was solid. But the voice layer was still stuck in the browser. Speech recognition was handled by SpeechRecognition, and responses were spoken using speechSynthesis. That worked, but it felt mechanical. There was a visible “thinking” gap between text generation and speech. The tone felt robotic. And browser APIs vary in quality across platforms. So in this step, we removed browser STT and TTS entirely and introduced a realtime voice pipeline powered by OpenAI Realtime.</p><h3>A Parallel Realtime Path</h3><p>Previously, voice flowed like this:</p><p>Browser STT → REST → LLM → Text → Browser TTS</p><p>Now, we added a second path:</p><p>Browser Mic → WebSocket → OpenAI Realtime → Audio → Browser Playback</p><p>The REST /respond and /agent endpoints still exist. Realtime is simply another mode. It allows experimentation without breaking the existing agent runtime.</p><h3>Updates in Backend</h3><p>On the backend, we introduced a new module under src/realtime. Instead of HTTP controllers, this module exposes a WebSocket endpoint:</p><pre>/ws/realtime</pre><p>When a client connects, the backend opens its own WebSocket connection to OpenAI Realtime and relays messages between them. Immediately after connection, the backend sends a session configuration:</p><pre>const session = {<br>  type: &#39;realtime&#39;,<br>  input_audio_format: &#39;pcm16&#39;,<br>  output_audio_format: &#39;pcm16&#39;,<br>  output_modalities: [&#39;audio&#39;],<br>  voice: config.realtime.voice,<br>  turn_detection: null<br>};<br>openAiWs.send(JSON.stringify({<br>  type: &#39;session.update&#39;,<br>  session<br>}));</pre><p>Now the browser does not configure the session. The backend does. That means:</p><ul><li>Voice selection is server-controlled</li><li>Transcription model is server-controlled</li><li>Secrets stay server-side</li></ul><p>The backend also restricts which client events are allowed to pass through. Only audio append, commit, response creation, and cancel events are forwarded. Everything else is blocked. This prevents the browser from mutating the session unexpectedly.</p><h3>Updates in Frontend</h3><p>Instead of calling SpeechRecognition, we now capture raw microphone data using the Web Audio API. Inside useRealtimeSession, we downsample to 24kHz and convert Float32 samples to PCM16:</p><pre>processor.onaudioprocess = (event) =&gt; {<br>  const input = event.inputBuffer.getChannelData(0);<br>  const pcm16 = floatTo16BitPCM(input);<br>  const base64 = encodeBase64(pcm16);<br>sendEvent({<br>    type: &#39;input_audio_buffer.append&#39;,<br>    audio: base64<br>  });<br>};</pre><p>The audio is streamed continuously over WebSocket. When the user stops speaking, we explicitly tell OpenAI to process it:</p><pre>sendEvent({ type: &#39;input_audio_buffer.commit&#39; });<br>sendEvent({ type: &#39;response.create&#39; });</pre><p>That replaces browser STT completely. The model transcribes and reasons in one unified pipeline.</p><h3>Receiving and Playing AI Audio</h3><p>OpenAI Realtime returns audio chunks in:</p><pre>response.output_audio.delta</pre><p>We decode PCM16 and push it into the Web Audio playback buffer:</p><pre>if (event.type === &#39;response.output_audio.delta&#39;) {<br>  const pcm = decodeBase64(event.delta);<br>  playPcmAudio(pcm);<br>}</pre><p>This replaces speechSynthesis. There is no text-to-speech bridge anymore. The voice you hear is generated directly by the model.</p><h3>Why OpenAI Realtime Feels Different</h3><p>Browser TTS feels robotic because it reads text after the model has already finished thinking. It has no emotional continuity with the reasoning process. OpenAI Realtime behaves differently. The model reasons and speaks within the same generation stream. The tone feels more conversational. Sentences often include natural pauses, subtle sentiment, and conversational framing.</p><p>Instead of:</p><p><em>The weather in Faisalabad is 15°C with fog.</em></p><p>It might respond like:</p><p><em>It’s a bit foggy in Faisalabad right now, around 15 degrees Celsius. Doesn’t look like rain at the moment.</em></p><p>That small difference changes perception completely. It feels closer to human speech patterns rather than a robotic readout. Also, because audio is streamed incrementally, playback begins earlier. There is less visible “thinking silence.” The assistant starts speaking as the model generates. That significantly improves perceived latency.</p><h3>Architectural Impact</h3><p>From a code perspective, we didn’t touch:</p><ul><li>The agent tool loop</li><li>The Brave search integration</li><li>The REST-based normal mode</li><li>The model provider abstraction</li></ul><p>We added a new transport layer for voice. The system now looks like this:</p><ul><li>REST runtime for text + agent</li><li>WebSocket relay for realtime audio</li><li>Shared configuration layer</li><li>Shared model abstraction</li></ul><h3>Summarizing</h3><p>The browser no longer transcribes, the browser no longer synthesizes. It streams audio and plays audio and everything else is AI-driven. This is a major shift from “voice-enabled chatbot” to “AI-native voice interface.”</p><p>If you enjoyed this journey, please show some love by liking and sharing the article! The code for this story is availble in <a href="https://github.com/AbdullahDev0/medium-voicebot">GitHub Repo</a>’s feature/openAI-voice-agent branch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0aef09e84f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading Voicebot to an Agent with Local Ollama and Cloud LLMs]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/upgrading-voicebot-to-an-agent-with-local-ollama-and-cloud-llms-f4a2dac0fe7c?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a2dac0fe7c</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 17:01:02 GMT</pubDate>
            <atom:updated>2026-02-25T17:01:02.618Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBQD7kC17vs4qJaNUv9DGw.png" /><figcaption>Image generated through OpenAI</figcaption></figure><p>In the <a href="https://medium.com/@abdullahirfan99_80517/running-voicebot-on-local-llm-using-ollama-d51252e4be81">previous article</a>, we introduced a backend LLM gateway and made it configurable enough to switch between cloud and local models. That gave us flexibility. The frontend stayed untouched, and the backend became the intelligence boundary. Now we are extending that backend to support agent behavior. The model can now decide when to call tools, the backend executes those tools, feeds results back, and only then returns a final answer.</p><h3>Updates in the Backend</h3><p>We didn’t rewrite everything. We added a second execution path. The controller now exposes an agent endpoint:</p><pre>@Post(&quot;agent&quot;)<br>async agent(@Body() dto: LlmRequestDto) {<br>  const text = await this.llmService.requestAgentResponse(dto.input);<br>  return { text };<br>}</pre><p>Inside requestAgentResponse, the backend runs a loop. The model either asks for a tool or returns a final answer. If it asks for a tool, the backend executes it and feeds the result back into the model. For local models (Ollama), we enforce strict JSON output:</p><pre>const SYSTEM_PROMPT = `<br>You must respond with a single JSON object.<br>Tool call:<br>{<br>  &quot;type&quot;: &quot;tool&quot;,<br>  &quot;name&quot;: &quot;web_search&quot;,<br>  &quot;arguments&quot;: { &quot;query&quot;: &quot;...&quot;, &quot;count&quot;: 5 }<br>}<br>Final answer:<br>{<br>  &quot;type&quot;: &quot;final&quot;,<br>  &quot;answer&quot;: &quot;...&quot;<br>}<br>`;</pre><p>Then we parse and loop:</p><pre>const parsed = parseAgentAction(rawOutput);<br>if (parsed.type === &quot;tool&quot;) {<br>  const toolResult = await toolsService.runTool(parsed);<br>  history.push(toolResult);<br>  continue;<br>}<br>if (parsed.type === &quot;final&quot;) {<br>  return parsed.answer;<br>}</pre><p>That loop — not the prompt — is what makes this behave like an agent.</p><h3>Why We Integrated Brave Search</h3><p>An agent needs something real to reason about. Web search is the most practical starting point. We chose Brave Search because it provides structured JSON results without scraping. The integration is lightweight and predictable:</p><pre>async webSearch(query: string) {<br>  const response = await fetch(<br>    `${config.brave.baseUrl}/res/v1/web/search?q=${encodeURIComponent(query)}&amp;count=${config.brave.count}`,<br>    {<br>      headers: {<br>        &quot;X-Subscription-Token&quot;: config.brave.apiKey,<br>      },<br>    }<br>  );<br>return response.json();<br>}</pre><p>The model never talks to Brave directly. It only decides <em>when</em> to use the tool. The backend owns execution and response shaping.</p><p>That separation is important. It keeps control in the server.</p><h3>Testing with Local Ollama on Raspberry Pi</h3><p>We deployed Ollama on a Raspberry Pi 4 and ran a lightweight model:</p><pre>qwen2.5:0.5b</pre><p>For normal chat, it worked reasonably well. For agent mode, it struggled. The biggest issue was JSON discipline. Even with strict instructions, the model sometimes returned extra text before JSON, partial JSON, or multiple blocks. Occasionally it ignored the schema entirely. That breaks the loop because the backend depends on parsing a clean structured response.</p><p>When web search results were returned, the model sometimes echoed raw JSON results instead of synthesizing them. For example, instead of summarizing weather data, it would respond with something like:</p><pre>[<br>  {<br>    &quot;title&quot;: &quot;Faisalabad, Pakistan Hourly Weather Forecast | Weather Underground&quot;,<br>    &quot;url&quot;: &quot;...&quot;,<br>    &quot;description&quot;: &quot;Generally cloudy...&quot;<br>  }<br>]</pre><p>That’s because agent reasoning isn’t reasoning, it’s copying. It’s a model limitation rather than an architectural failure. Smaller models struggle with:</p><ul><li>Strict structured output</li><li>Multi-step reasoning loops</li><li>Tool result synthesis</li><li>Schema obedience under constraints</li></ul><p>Agent loops amplify those weaknesses because every step depends on correct formatting.</p><h3>Switching to OpenAI Nano</h3><p>When we switched to:</p><pre>OPENAI_MODEL=gpt-5-nano</pre><p>the behavior changed significantly.</p><p>The model requested tools correctly, respected the schema, and synthesized answers from Brave results instead of copying them. For the same weather query, it returned something like:</p><p><em>Here’s a quick update for Faisalabad today:</em></p><p><em>– Current conditions: around 59°F (15°C) with fog.</em></p><p><em>– No precipitation expected.</em></p><p><em>– Light winds.</em></p><p><em>Would you like hourly details?</em></p><p>OpenAI nano handled:</p><ul><li>Tool invocation</li><li>Structured response flow</li><li>Multi-step reasoning</li><li>Result synthesis</li></ul><p>without formatting failures. The backend loop stayed the same. Only the model changed.</p><h3>Summarizing</h3><p>The architecture is solid. The agent loop works. The tool execution works. The difference comes from model capability. Smaller local models are fine for chat. Stronger models handle structured agent behavior far better. This doesn’t mean local inference is useless. It’s excellent for development and experimentation. But if you require reliable tool orchestration, structured reasoning, and multi-step workflows, model strength matters. Thus</p><ul><li>Local lightweight models can run the system</li><li>Cloud nano models handle agent loops more reliably</li></ul><p>If you enjoyed this journey, please show some love by liking and sharing the article! The code for this story is availble in <a href="https://github.com/AbdullahDev0/medium-voicebot">GitHub Repo</a>’s feature/add-agent-support branch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a2dac0fe7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Voicebot on Local LLM Using Ollama]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/running-voicebot-on-local-llm-using-ollama-d51252e4be81?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d51252e4be81</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 17:01:02 GMT</pubDate>
            <atom:updated>2026-02-25T03:45:45.552Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4iRX8gbQ-YKtKqikI2E7w.png" /><figcaption>Image generated through OpenAI</figcaption></figure><p>In the <a href="https://medium.com/@abdullahirfan99_80517/building-a-backend-llm-gateway-for-our-voicebot-using-nestjs-281c4d44ea4b">previous article</a>, we introduced a backend LLM gateway using NestJS. The frontend sends text to /api/llm/respond, and the backend forwards that request to a configured model provider. At that point, the backend was still pointing to a cloud API. Now we take the next logical step: make the model layer configurable enough to support a local LLM without changing frontend logic. Not only this helps in ensuring data privacy, for beginner developers who are focused on building demo system that doesn’t need high accuracy.</p><h3>Updates in the Backend</h3><p>Previously, our LLM service was tightly aligned with OpenAI’s Responses API. The base URL and model were configured, but the structure implicitly assumed a cloud provider. To support local models, we made two small but important adjustments:</p><ol><li>The base URL became fully configurable.</li><li>The Authorization header became optional.</li></ol><p>The updated service logic now looks like this:</p><pre>async generate(input: string): Promise&lt;string&gt; {<br>  const response = await fetch(config.llm.baseUrl, {<br>    method: &quot;POST&quot;,<br>    headers: {<br>      &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      ...(config.llm.apiKey &amp;&amp; {<br>        Authorization: `Bearer ${config.llm.apiKey}`,<br>      }),<br>    },<br>    body: JSON.stringify({<br>      model: config.llm.model,<br>      prompt: input,<br>      stream: false,<br>    }),<br>  });</pre><pre>  const data = await response.json();<br>  return this.extractText(data);<br>}</pre><p>Notice two details.</p><p>First, we are no longer hardcoding an OpenAI endpoint. Second, the Authorization header is only attached if an API key exists. That makes the service compatible with:</p><ul><li>Cloud providers (with API key)</li><li>Local Ollama (no API key)</li><li>Any HTTP-based LLM endpoint</li></ul><p>The frontend still calls /api/llm/respond. Nothing changed there.</p><h3>Updating Environment Configuration</h3><p>Previously, our environment variables looked like this:</p><pre>OPENAI_API_KEY=sk-...<br>OPENAI_MODEL=gpt-4.1-mini<br>OPENAI_BASE_URL=https://api.openai.com/v1/responses</pre><p>To switch to local Ollama, we update them to:</p><pre>LLM_BASE_URL=http://127.0.0.1:11434/api/generate<br>LLM_MODEL=qwen2.5:3b<br>LLM_API_KEY=</pre><p>Restart the backend, and the system now talks to your local machine instead of the cloud. No controller changes. No frontend changes. That’s the benefit of introducing the gateway earlier.</p><h3>Installing Ollama on Your Local Machine</h3><p>If you’re on macOS or Linux, installation is straightforward:</p><pre>curl -fsSL https://ollama.com/install.sh | sh</pre><p>Start the service:</p><pre>ollama serve</pre><p>By default, Ollama runs on:</p><pre>http://127.0.0.1:11434</pre><p>Now pull a model.</p><p>For development machines with decent RAM:</p><pre>ollama pull qwen2.5:3b</pre><p>If RAM is limited:</p><pre>ollama pull qwen2.5:0.5b</pre><p>If you want stronger reasoning and your machine can handle it:</p><pre>ollama pull llama3:8b</pre><p>Before integrating with the backend, test it directly:</p><pre>curl http://127.0.0.1:11434/api/generate -d &#39;{<br>  &quot;model&quot;: &quot;qwen2.5:3b&quot;,<br>  &quot;prompt&quot;: &quot;Explain DNS in 2 lines&quot;,<br>  &quot;stream&quot;: false<br>}&#39;</pre><p>If you get JSON output with generated text, the model is ready. At this point, your voicebot backend can use it.</p><h3>Running on Raspberry Pi (Optional)</h3><p>Like If you want to run inference on inexpensive hardware or want to mess around and have spare hardware available at your disposal, Ollama can also run on a Raspberry Pi 4. I documented the full setup, including system tuning and performance considerations, <a href="https://medium.com/@abdullahirfan99_80517/from-high-costs-to-homegrown-building-a-custom-web-server-on-a-budget-c8523c4c0485">in this article</a>. On a Pi with 4GB RAM, smaller models like qwen2.5:0.5b are realistic. Expect slower response times compared to desktop or cloud machines. Once the Pi exposes an HTTP endpoint, it’s accessible within Pi but not on external network/local devices. One way is if you follow the Pi tutorial then setup the cloudflare tunnel. Otherway is to expose the port through:</p><p>Create the drop-in directory</p><pre>sudo mkdir -p /etc/systemd/system/ollama.service.d</pre><p>Create a file that sets OLLAMA_HOST to all interfaces</p><pre>sudo tee /etc/systemd/system/ollama.service.d/host.conf &gt; /dev/null &lt;&lt;&#39;EOF&#39;<br>[Service]<br>Environment=&quot;OLLAMA_HOST=0.0.0.0:11434&quot;<br>EOF</pre><p><em>(You can also use 0.0.0.0 without :11434, but including the port makes it explicit.)</em></p><p>Reload systemd and restart Ollama</p><pre>sudo systemctl daemon-reload<br>sudo systemctl restart ollama</pre><p>Verify it’s listening on the LAN</p><pre>ss -tulpen | grep 11434</pre><p>You should see something like 0.0.0.0:11434 or *:11434. Test from your laptop, replace with your Pi IP:</p><pre>curl http://192.168.100.71:11434/api/tags</pre><p>The in ENV simply update:</p><pre>LLM_BASE_URL=http://PI_IP:11434/api/generate<br>LLM_MODEL=qwen2.5:0.5b</pre><p>Restart the backend and your voicebot now runs on the Pi.</p><h3>What Actually Changed Architecturally</h3><p>This step is not about Ollama itself. It’s about the backend becoming provider-agnostic. Previously it was Backend → OpenAI now it’s Backend → Configured LLM Endpoint. The voice console does not care where the model runs. The state machine does not care. The transcript system does not care. We swapped the intelligence layer without rewriting the system.</p><h3>Performance Reality</h3><p>Local models are slower than cloud models. The first request may take longer due to model loading. CPU usage will spike. Response times depend entirely on hardware. But for development, testing, and experimentation, local inference is extremely useful. You can iterate freely without worrying about token costs.</p><h3>Where This Leads</h3><p>Now that the backend supports both cloud and local models, we can experiment more aggressively. We can benchmark models. We can compare response quality. We can introduce routing logic later. Most importantly, the architecture remains stable.</p><p>If you enjoyed this journey, please show some love by liking and sharing the article! The code for this story is availble in <a href="https://github.com/AbdullahDev0/medium-voicebot">GitHub Repo</a>’s feature/local-llm-setup branch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d51252e4be81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Backend LLM Gateway for Our Voicebot Using NestJS]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/building-a-backend-llm-gateway-for-our-voicebot-using-nestjs-281c4d44ea4b?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/281c4d44ea4b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 17:01:01 GMT</pubDate>
            <atom:updated>2026-02-23T17:01:01.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAqfCMQTDMam8Sk9R4XHvg.png" /><figcaption>Image generated through OpenAI</figcaption></figure><p>In the <a href="https://medium.com/@abdullahirfan99_80517/building-a-frontend-voicebot-console-using-react-and-openai-999846e18c7b">previous article</a>, we built a browser-based voicebot console using React, Vite, and OpenAI. It could capture microphone input, convert speech to text, send it to an LLM, speak the response back, and maintain a transcript — all inside the browser. However the OpenAI call was happening directly from the frontend. That means the API key lived in the browser. That means no usage control, no centralized logging, no rate limiting, no structured validation.</p><p>So in this article, we evolve the architecture. We move the LLM layer from frontend to a NestJS backend and introduce a proper client-server boundary. This is where the voicebot stops being a demo and starts becoming infrastructure.</p><h3>Why Frontend LLM Calls Don’t Scale</h3><p>When everything runs in the browser, it feels simple. You write a fetch call to OpenAI, pass the transcript, and play back the response. Done. But in real systems, simplicity can be dangerous. You cannot safely expose API keys. You cannot control cost per user. You cannot log usage per request. You cannot apply rate limiting. You cannot introduce analytics later without rewriting the architecture.</p><p>And the moment you want streaming, tool calling, conversation memory, or user-level billing — you realize the browser cannot be your intelligence layer. So instead of React talking directly to OpenAI, we introduce a gateway of React → NestJS → OpenAI</p><h3>What Changed in the Frontend</h3><p>The frontend no longer knows anything about OpenAI.</p><p>Inside src/services/llm.ts, the request now looks like this:</p><pre>export async function requestAssistantResponse(input: string) {<br>  const response = await fetch(<br>    `${config.apiBaseUrl}/api/llm/respond`,<br>    {<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      },<br>      body: JSON.stringify({ input }),<br>    }<br>  );</pre><pre>  const data = await response.json();<br>  return data.text;<br>}</pre><p>Notice what disappeared. There is no OpenAI base URL. No Authorization header. No model selection logic. No provider mapping. The frontend simply sends text to /api/llm/respond and waits for { text }. The voice orchestration remains exactly the same. The state machine still transitions from LISTENING to THINKING to SPEAKING. Transcript logic is unchanged. Microphone monitoring is unchanged. Only the intelligence boundary moved. And that’s the point. Good architecture allows movement without breaking behavior.</p><h3>Introducing the LLM Module in NestJS</h3><p>On the backend, we introduced a dedicated llm module. This is not just a controller with a quick fetch call. It’s a structured layer.</p><p>There is a DTO that defines the request shape:</p><pre>export class LlmRequestDto {<br>  input: string;<br>}</pre><p>The controller exposes a single endpoint:</p><pre>@Post(&quot;respond&quot;)<br>async respond(@Body() dto: LlmRequestDto) {<br>  const text = await this.llmService.generate(dto.input);<br>  return { text };<br>}</pre><p>The service handles the OpenAI call. That logic now lives entirely in the backend:</p><pre>async generate(input: string): Promise&lt;string&gt; {<br>  const response = await fetch(<br>    `${config.openai.baseUrl}/responses`,<br>    {<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        Authorization: `Bearer ${config.openai.apiKey}`,<br>      },<br>      body: JSON.stringify({<br>        model: config.openai.model,<br>        input,<br>        store: false,<br>      }),<br>    }<br>  );</pre><pre>  const data = await response.json();<br>  return this.extractText(data);<br>}</pre><p>Now the API key is server-side. The model is server-side. The base URL is server-side. The frontend cannot access any of it.</p><h3>Defensive Parsing Matters in Voice Systems</h3><p>LLM responses are not guaranteed to follow one rigid structure. If you assume output_text will always exist, your voicebot will eventually fail in silence. In the service layer, the response is parsed defensively. It checks for output_text, and if not found, traverses the output array to locate text segments. If nothing valid exists, it throws an explicit error.</p><p>In voice applications, silent failures are worse than crashes. If the assistant transitions to SPEAKING but has no text, your state machine breaks. The user hears nothing. The UI appears frozen.</p><h3>Environment-Based Configuration</h3><p>The backend now requires:</p><ul><li>OPENAI_API_KEY</li><li>OPENAI_MODEL</li><li>OPENAI_BASE_URL</li></ul><p>This allows different models per environment. You can run a cheaper model locally and a more capable one in production. You can even switch providers without touching frontend code.</p><h3>Latency and Tradeoffs</h3><p>Yes, adding a backend introduces an extra network hop. The request now goes from browser to server and then to OpenAI before returning. In practice, this adds a few milliseconds in most deployments. Compared to LLM response time, this overhead is negligible. However you gain the ability to introduce streaming later. You gain centralized logging. You gain rate limiting. You gain the ability to attach user IDs and track token consumption. You gain the ability to cache responses if needed.</p><h3>What This Really Means</h3><p>The voice console still looks the same. The orb still animates. The transcript still grows. The state machine still behaves predictably. But under the hood, something fundamental changed. We introduced a boundary between orchestration and intelligence. The frontend handles voice flow. The backend handles reasoning. That separation is what allows this system to evolve into a true voice agent.</p><h3>Where This Leads Next</h3><p>Now that LLM calls live in the backend, we can extend the system without touching the React architecture. We can introduce streaming responses. We can add tool calling. We can integrate web search. We can store conversation history in a database. We can log every request for analytics. None of that requires redesigning the UI anymore. This is how systems are built that grow.</p><p>If you enjoyed this journey, please show some love by liking and sharing the article! The code for this story is availble in <a href="https://github.com/AbdullahDev0/medium-voicebot">GitHub Repo</a>’s feature/be-addition branch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=281c4d44ea4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Frontend Voicebot Console Using React and OpenAI]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/building-a-frontend-voicebot-console-using-react-and-openai-999846e18c7b?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/999846e18c7b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 17:01:01 GMT</pubDate>
            <atom:updated>2026-02-19T17:01:01.473Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTsHTbZfMHSETIu0p3Xh3Q.png" /><figcaption>Image generated through OpenAI</figcaption></figure><p>This is first story of a new series on building voice agents; here we will be building a voice Bot system step by step. This is the <a href="https://medium.com/@abdullahirfan99_80517/building-a-voice-agent-architecture-a-step-by-step-guide-using-react-nest-llms-and-backend-cd19b0ebd6ca">index page/story</a> and all stories linked to this series will be updated here. In this story, we will create a frontend-only voice Bot console using React, Vite and OpenAI. The purpose is not to build a production-ready system, but to put correct architecture in place so that it can be extended later with backend, streaming and analytics.</p><p>The application will:</p><ul><li>Capture microphone input</li><li>Convert speech to text</li><li>Send text to LLM</li><li>Play response as audio</li><li>Maintain transcript</li><li>Manage conversation state explicitly</li></ul><p>Everything will run inside browser and before there is any argument on Open AIs real-time voice APIs, yes, they exist but the purpose here is to:</p><ol><li>Build system from base so we know how flow originally started</li><li>Design the system to run locally first, this helps control costs and demonstrates a working architecture before introducing production infrastructure</li></ol><h3>Application Flow</h3><p>At high level, flow looks like this:</p><ol><li>User clicks voice orb</li><li>Browser starts speech recognition</li><li>Final transcript is captured</li><li>Input is sent to LLM</li><li>Response is appended to transcript</li><li>Response is spoken using TTS</li><li>System returns to idle state</li></ol><p>Instead of mixing this logic inside components, everything is driven by a voice state machine.</p><h3>Voice State Machine</h3><p>We define following states:</p><pre>IDLE<br>LISTENING<br>THINKING<br>SPEAKING<br>ERROR</pre><p>Inside App.tsx:</p><pre>const [status, setStatus] = useState&lt;VoiceState&gt;(STATES.IDLE);</pre><p>When speech starts:</p><pre>setStatus(STATES.LISTENING);</pre><p>When final transcript is received:</p><pre>setStatus(STATES.THINKING);</pre><p>After LLM response:</p><pre>setStatus(STATES.SPEAKING);</pre><p>When speech playback ends:</p><pre>setStatus(STATES.IDLE);</pre><p>Using single state instead of multiple Boolean flags keeps system predictable. In voice systems, state clarity is important because input and output are asynchronous.</p><h3>Speech Recognition Hook</h3><p>Instead of calling window.SpeechRecognition directly inside component, it is wrapped inside useSpeechRecognition hook.</p><p>Hook accepts callbacks:</p><pre>useSpeechRecognition({<br>  onStart,<br>  onEnd,<br>  onInterim,<br>  onFinal,<br>  onError,<br>});</pre><p>Internally it:</p><ul><li>Detects browser support</li><li>Initializes recognition instance</li><li>Handles interim and final transcripts</li><li>Cleans up on unmount</li></ul><p>This allows UI to remain unaware of browser-specific APIs. Later, if we replace browser STT with Whisper or any external provider, we only modify hook implementation.</p><h3>Text To Speech Hook</h3><p>Similarly, useTextToSpeech wraps speechSynthesis.</p><pre>const { speak } = useTextToSpeech();</pre><p>speak() returns a Promise. This allows us to wait for speech completion before transitioning back to IDLE.</p><pre>setStatus(STATES.SPEAKING);<br>await speak(responseText);<br>setStatus(STATES.IDLE);</pre><p>Without Promise handling, system may return to idle while audio is still playing.</p><h3>LLM Abstraction Layer</h3><p>Now comes important part — LLM integration.</p><p>Instead of directly calling OpenAI from component, we created a provider map:</p><pre>const providers: Record&lt;string, (input: string) =&gt; Promise&lt;string&gt;&gt; = {<br>  openai: requestOpenAi,<br>};</pre><p>And a single-entry function:</p><pre>export const requestAssistantResponse = async ({<br>  input,<br>  provider = LLM.DEFAULT_PROVIDER,<br>}) =&gt; {<br>  const resolver = providers[provider];<br>  if (!resolver) {<br>    throw new Error(ERRORS.LLM_UNSUPPORTED);<br>  }<br>  return resolver(input);<br>};</pre><p>UI only calls requestAssistantResponse. It does not know which provider is being used.</p><p>Currently we use OpenAI Responses API:</p><pre>POST /v1/responses</pre><p>Response is parsed defensively because output format may vary depending on model.</p><p>If no valid text is found, error is thrown explicitly.</p><p>This structure allows us to later add:</p><ul><li>Anthropic</li><li>Azure OpenAI</li><li>Local LLM</li><li>Any other provider</li></ul><p>Without touching UI logic.</p><h3>Transcript Management</h3><p>Transcript items are stored as:</p><pre>{<br>  id,<br>  role,<br>  text,<br>  time<br>}</pre><p>When adding new items, we ensure transcript length does not exceed predefined limit:</p><pre>if (next.length &gt; LIMITS.MAX_TRANSCRIPTS) {<br>  return next.slice(next.length - LIMITS.MAX_TRANSCRIPTS);<br>}</pre><p>This prevents uncontrolled memory growth in long sessions.</p><h3>Theme and Configuration</h3><p>Theme preference is stored in localStorage and applied using data attribute on document root. Configuration such as OpenAI API key and model is stored in config file.</p><h3>What We Achieved</h3><p>We now have:</p><ul><li>Explicit voice state management</li><li>Abstracted STT and TTS layers</li><li>Provider-agnostic LLM integration</li><li>Controlled transcript memory</li><li>Modular structure</li></ul><p>Even though everything runs in browser, structure resembles production-grade voice orchestration.</p><p>In next story, we can move LLM integration to NestJS backend and introduce streaming responses.</p><p>This will allow us to evolve this console into a complete voice Bot agent system.</p><p>If you enjoyed this journey, please show some love by liking and sharing the article! The code for this story is availble in <a href="https://github.com/AbdullahDev0/medium-voicebot">GitHub Repo</a>’s main branch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=999846e18c7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Voice Agent Architecture: A Step-by-Step Guide Using React/Nest, LLMs, and Backend…]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/building-a-voice-agent-architecture-a-step-by-step-guide-using-react-nest-llms-and-backend-cd19b0ebd6ca?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd19b0ebd6ca</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[voice-assistant]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 22:59:48 GMT</pubDate>
            <atom:updated>2026-02-18T22:59:48.088Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building a Voice Agent Architecture: A Step-by-Step Guide Using React/Nest, LLMs, and Backend Gateways</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-oPNf3fpMGLJNNFCe5X9w.png" /><figcaption>Image generated through OpenAI</figcaption></figure><p>If you are here, you already know what an agent is and what it can do. The real concern is implementation — how do we build one properly in TypeScript? This series begins with a voice bot and gradually transforms it into a structured voice agent capable of handling real-world scenarios. Each part builds on the previous one, focusing on architecture, orchestration, and extensibility. This story is an index for the series and will be updated as new stories are added.</p><h3>Series Outline</h3><ol><li><strong>Basic Voicebot</strong>: Creating a browser-based voice interface with explicit state management, abstracted STT/TTS layers, and provider-agnostic LLM integration.</li></ol><h3>Feedback &amp; Collaboration</h3><p>“Being critical isn’t the same as being disrespectful.” ― A.D. Aliwat, In Limbo</p><p>Open communication is important when working through architecture decisions. If you see room for improvement, have a different approach in mind, or believe a certain implementation can be structured better, feel free to share it. System design is rarely absolute, and there are always tradeoffs involved. Constructive feedback and alternative perspectives help strengthen the foundation of what we are building here. If something can be done more efficiently or more cleanly, let’s discuss it and refine it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd19b0ebd6ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From High Costs to Homegrown: Building a Custom Web Server on a Budget]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/from-high-costs-to-homegrown-building-a-custom-web-server-on-a-budget-c8523c4c0485?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8523c4c0485</guid>
            <category><![CDATA[diy]]></category>
            <category><![CDATA[self-hosting]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[web-server]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Sat, 05 Apr 2025 04:43:41 GMT</pubDate>
            <atom:updated>2025-04-05T04:43:41.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*loh3EmAgmNCf4_rd" /></figure><p>I’ve always been intrigued by the idea of hosting my own projects, but the market options often felt like a constant hit to my wallet. I started out with Digital Ocean, which is known for its stability and reliable service. However, even their cheapest plan at $5 just didn’t cut it for me. I found myself needing the $12 plan — with 1 vCPU and 2GB of RAM — to comfortably run multiple projects simultaneously. While Digital Ocean’s service was undeniably robust, my use case wasn’t production oriented. I was simply testing out ideas and experimenting with random projects. The expense, in the end, felt more like an unnecessary burden than an investment.</p><p>I also looked into Oracle’s free resources. The idea of accessing free resources was appealing, but the signup process turned out to be a headache. They don’t accept virtual cards, and even when I tried with a physical card, it took several attempts just to get through. And when I finally managed to create free account, I was disappointed to discover that there was actually nothing to claim as no free resources were available in any available domain.</p><p>There are other alternatives out there, like fly.io, which tout themselves as free or lower-cost solutions. However, after reading through various forum discussions, I learned about their limited resources, hidden charges, and poor customer support. This further pushed me away from the idea of relying on these services for my experimental projects.</p><p>That’s when a thought hit me: I had a spare Raspberry Pi 4 lying around. Instead of throwing money at expensive, conventional solutions, why not put this little device to good use and build my own custom web server?</p><h3>Feasibility Analysis</h3><p>Evaluating these two options meant taking a close look at various aspects of performance and cost. Here’s a medium-format breakdown of my comparison between the DigitalOcean droplet and the Raspberry Pi 4:</p><p><strong>Core Count</strong><br> • <strong>DigitalOcean Droplet:</strong> Comes with 1 vCPU, which represents one high-performance core; virtualization helps with burst performance for single-threaded tasks.<br> • <strong>Raspberry Pi 4:</strong> Offers 4 physical cores that enable true parallelism, making it more suitable for multi-threaded applications.</p><p><strong>Single-Core Performance</strong><br> • <strong>DigitalOcean Droplet:</strong> Provides very high single-core performance thanks to high clock speeds, larger caches, and server-level optimizations.<br> • <strong>Raspberry Pi 4:</strong> Delivers moderate performance that’s sufficient for lightweight tasks, though its per-core performance is lower than that of a server-grade CPU.</p><p><strong>Multi-Core Performance</strong><br> • <strong>DigitalOcean Droplet:</strong> Limited by its single vCPU configuration, so parallel execution is constrained unless you scale out with additional droplets.<br> • <strong>Raspberry Pi 4:</strong> Excels in multi-threaded tasks with four cores, even if each core isn’t as powerful as a server-grade CPU.</p><p><strong>Memory</strong><br> • <strong>DigitalOcean Droplet:</strong> Equipped with 2 GiB of DDR4 RAM, often running at faster speeds and sometimes featuring error-correcting technology in a data center environment.<br> • <strong>Raspberry Pi 4:</strong> Comes with 4 GiB LPDDR4. Although it offers more memory in capacity, the speeds are lower, and it isn’t optimized for heavy-duty, sustained workloads.</p><p><strong>Storage &amp; I/O Performance</strong><br> • <strong>DigitalOcean Droplet:</strong> Uses a 50 GiB fast SSD that benefits from high IOPS and low latency, often backed by NVMe or enterprise-grade storage.<br> • <strong>Raspberry Pi 4:</strong> Typically relies on a microSD card or USB-attached storage, which is considerably slower in throughput and latency.</p><p><strong>Network Bandwidth</strong><br> • <strong>DigitalOcean Droplet:</strong> Boasts 2,000 GiB monthly bandwidth on high-speed data center networks that provide low latency and high reliability — ideal for heavy traffic loads.<br> • <strong>Raspberry Pi 4:</strong> Uses Gigabit Ethernet or Wi-Fi via a consumer-grade interface, which is generally less reliable and lower in performance compared to data center networks.</p><p><strong>Load Handling (CPU)</strong><br> • <strong>DigitalOcean Droplet:</strong> Excels at single-threaded tasks with high per-core performance, but its single vCPU limits workload distribution.<br> • <strong>Raspberry Pi 4:</strong> Superior for parallel and multi-threaded tasks thanks to its four cores, though each core may lag in performance compared to the server-grade CPU found in the droplet.</p><p><strong>Bandwidth Impact</strong><br> • <strong>DigitalOcean Droplet:</strong> With high network throughput and reliability, it’s ideal for applications that require heavy data transfer and low latency.<br> • <strong>Raspberry Pi 4:</strong> Better suited for local or less bandwidth-intensive tasks; network performance can become a bottleneck for high data-volume or low-latency applications.</p><p><strong>Ideal Use Cases</strong><br> • <strong>DigitalOcean Droplet:</strong> Designed for production web servers, databases, compute-intensive applications, high I/O tasks, and scenarios demanding robust network performance.<br> • <strong>Raspberry Pi 4:</strong> Perfect for prototyping, education, IoT projects, and local server projects where energy efficiency, cost, and hands-on experimentation outweigh raw performance.</p><p>For my testing and experimental projects, the Raspberry Pi 4 clearly aligned more with my needs. It provided a cost-effective and flexible platform, allowing me to explore and iterate without the pressure of production-level demands and hefty expenses.</p><p>Next, I’ll describe how I set up the environment on my Raspberry Pi. I opted for Raspberry Pi OS due to its efficiency and community support. Here’s how I went about it:</p><h3>Setting Up Apache2</h3><p>I installed Apache2 to serve as my web server. I followed the instructions from the official Raspberry Pi documentation, which you can find <a href="https://www.raspberrypi.com/documentation/computers/remote-access.html#set-up-an-apache-web-server">here</a>. The process was straightforward:</p><p><strong>Update and Upgrade the System</strong></p><pre>sudo apt-get update<br>sudo apt-get upgrade -y</pre><p><strong>Install Apache2</strong></p><pre>sudo apt-get install -y apache2</pre><p><strong>Verify the Installation</strong><br>Open your web browser and type in your Raspberry Pi’s IP address. You should see the Apache2 default page, which confirms that the server is up and running.</p><h3>Installing Docker on Raspberry Pi</h3><p>To containerize my projects, I set up Docker on my Raspberry Pi. Here are the detailed commands I used:</p><p><strong>Update Package Lists and Install Prerequisites</strong></p><pre>sudo apt-get update<br>sudo apt-get install -y ca-certificates curl gnupg</pre><p><strong>Add Docker’s Official GPG Key</strong></p><pre>sudo curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.gpg<br>sudo chmod a+r /etc/apt/keyrings/docker.gpg</pre><p><strong>Set Up the Stable Repository</strong></p><pre>echo &quot;deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian bullseye stable&quot; | sudo tee /etc/apt/sources.list.d/docker.list &gt; /dev/null</pre><p><strong>Install Docker Engine and Related Packages</strong></p><pre>sudo apt-get update<br>sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin</pre><p>Once installed, I confirmed Docker was working by running:</p><pre>sudo docker run hello-world</pre><h3>Setting Up NVM, NodeJS, and PM2</h3><p>For managing Node.js versions and running my applications, I set up NVM, Node.js, and PM2. Here’s how I did it:</p><h4>1. Install NVM (Node Version Manager)</h4><p>I installed NVM using the official installation script:</p><pre>curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash</pre><p>After running the script, I refreshed my shell configuration:</p><pre>export NVM_DIR=&quot;$HOME/.nvm&quot;<br>[ -s &quot;$NVM_DIR/nvm.sh&quot; ] &amp;&amp; \. &quot;$NVM_DIR/nvm.sh&quot;</pre><p>You can verify the installation with:</p><pre>command -v nvm</pre><h4>2. Install Node.js Using NVM</h4><p>I then installed Node.js (the latest version or a version of your choice) with:</p><pre>nvm install node</pre><p>This command downloads and installs the latest stable Node.js version. You can switch between versions using nvm use &lt;version&gt; if needed.</p><h4>3. Install PM2 to Manage Node.js Applications</h4><p>PM2 is an excellent process manager for Node.js apps. I installed it globally using npm:</p><pre>npm install -g pm2</pre><p>After installation, I started my Node.js application with PM2, for example:</p><pre>pm2 start app.js --name my-app</pre><h4>4. Configure PM2 to Retain Processes on Raspberry Pi Restart</h4><p>To ensure that PM2 restarts your processes after a reboot, you need to generate and configure a startup script:</p><pre>pm2 startup systemd</pre><p>This command outputs a line that you need to run with superuser privileges. After executing it, save the current process list:</p><pre>pm2 save</pre><p>Now, whenever Raspberry Pi restarts, PM2 will automatically reload saved processes.</p><p>I started exploring ways to expose my Raspberry Pi — which was already set up as a local environment — to the internet as a proper web server. I considered three approaches:</p><h3>Exposing Ports Through Local IPs</h3><p>I first thought about simply forwarding ports on my router so that external traffic could reach my Raspberry Pi via its local IP. However, I quickly realized that:</p><p><strong>ISP Limitations:</strong> Many ISPs block incoming traffic on common ports (like 80 for HTTP or 443 for HTTPS), making it unreliable to host a server directly from a home network.</p><p><strong>Security Risks:</strong> Exposing my device directly to the internet meant I would be opening it up to potential attacks. Any vulnerability in my OS or applications could be exploited by malicious actors.</p><p>This approach simply didn’t meet my security and reliability needs.</p><h3>Using Ngrok</h3><p>I had used Ngrok in the past, and it was a tempting option since it creates a secure tunnel from a public URL to my local server. However, I ran into some limitations:</p><p><strong>Single Port Limitation:</strong> The free version of Ngrok supports tunnelling only one port at a time, which isn’t ideal if I have multiple services running.</p><p><strong>Free Usage Issues:</strong> The free plan comes with restrictions on session duration and bandwidth, and I sometimes experienced interruptions that made it unsuitable for an always-on setup.</p><p>While Ngrok worked well for temporary testing, its restrictions led me to look for a more robust solution.</p><h3>Using Cloudflare Tunnel</h3><p>Since I already had my DNS configured with Cloudflare, I decided to use Cloudflare Tunnel (cloudflared) for a more secure and integrated solution. Here’s how I set it up step by step:</p><h4>Installing Cloudflared on My Raspberry Pi</h4><p><strong>Download and Install the Cloudflared Binary</strong><br>I downloaded the ARM version and set the proper permissions:</p><pre>sudo wget -O /usr/local/bin/cloudflared https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm <br>sudo chmod +x /usr/local/bin/cloudflared</pre><p><strong>Authenticate with Cloudflare</strong><br>Next, I ran:</p><pre>sudo cloudflared tunnel login</pre><p>This command opened a browser window where I logged into my Cloudflare account and selected the domain I wanted to use. After authentication, a certificate file was saved on my Pi.</p><p><strong>Create a Named Tunnel</strong><br>I created a tunnel by executing:</p><pre>sudo cloudflared tunnel create mytunnel</pre><p>This generated a tunnel ID that I used in the configuration file.</p><p><strong>Configure the Tunnel (Ingress Rules)</strong><br>I created a configuration file at /etc/cloudflared/config.yml with the following content:</p><pre>tunnel: &lt;your-tunnel-id&gt; <br>credentials-file: /root/.cloudflared/&lt;your-tunnel-id&gt;.json  <br>ingress:<br>   - hostname: example.com<br>     service: http://localhost<br>   - service: http_status:404</pre><p>I replaced &lt;your-tunnel-id&gt; with the actual tunnel ID and example.com with my domain name. This configuration routes traffic from my domain to the Apache server running on my Pi.</p><p><strong>Set Up Apache to Serve My HTML File</strong><br>I ensured Apache was installed:</p><pre>sudo apt-get install -y apache2</pre><p>Then, I replaced the default Apache index file with my custom HTML page. I edited the file at /var/www/html/index.html:</p><pre>&lt;!DOCTYPE html&gt; <br>&lt;html lang=&quot;en&quot;&gt; <br>&lt;head&gt;<br>   &lt;meta charset=&quot;UTF-8&quot;&gt;<br>   &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;<br>   &lt;title&gt;My Homegrown Web Server&lt;/title&gt;<br>&lt;/head&gt; <br>&lt;body&gt;<br>   &lt;h1&gt;Welcome to my custom Raspberry Pi Web Server!&lt;/h1&gt;<br>   &lt;p&gt;This server is powered by Cloudflare Tunnel, keeping it secure and accessible.&lt;/p&gt; <br>&lt;/body&gt; <br>&lt;/html&gt;</pre><p>I then restarted Apache to apply the changes:</p><pre>sudo systemctl restart apache2</pre><p><strong>Run the Tunnel<br></strong>Finally, I started the Cloudflare Tunnel with:</p><pre>sudo cloudflared tunnel run mytunnel</pre><p>With this command running, my domain now securely forwards traffic to my Apache server on the Raspberry Pi.</p><p>Each method had its trade-offs, but using Cloudflare Tunnel aligned best with my need for security, reliability, and ease of integration with my existing DNS setup.</p><p>Concluding this article, I transformed my Raspberry Pi into a fully functional web server by installing Raspberry Pi OS and Apache2 (following the official guide), configuring Docker for containerized projects, and setting up NVM, Node.js, and PM2 — with startup scripts — to keep my apps running persistently. For secure external access, I evaluated several options and ultimately chose Cloudflare Tunnel: I installed cloudflared, authenticated with my Cloudflare account, created a named tunnel, and set up ingress rules to route my domain traffic to my Apache server hosting a custom HTML page.</p><p>If you enjoyed this journey, please show some love by liking and sharing the article! 😊❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8523c4c0485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain and ReactJS based Reusable AI Chat Component]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/langchain-and-reactjs-based-reusable-ai-chat-component-7e0127007cc5?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e0127007cc5</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <category><![CDATA[ai-chatbot]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 09:41:12 GMT</pubDate>
            <atom:updated>2025-02-02T09:41:12.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uAXqx5tuA2u8DbnL.jpg" /><figcaption>Photo generated by Bing</figcaption></figure><h3>Introduction</h3><p>Last year, I was experimenting with <strong>React</strong> and <strong>LangChain</strong> while building an AI chatbot. I successfully designed the UI, but I hit a roadblock when it came to making it functional. Recently, I revisited the project and decided to turn it into a <strong>fully reusable package</strong> so that others could use it as a foundation for their own AI chat applications.</p><p>This led to the creation of <strong>langchain-chatbot-react-app</strong>, now available as an <strong>NPM package</strong> and <strong>directly usable as a script in HTML files</strong>!</p><h3>💡 How to Install</h3><p>You can install it via NPM:</p><pre>npm i langchain-chatbot-react-app</pre><p>Or, if you prefer, you can use it directly in an HTML file via the <strong>UMD build</strong>:</p><pre>&lt;script src=&quot;path/to/langchain-chatbot-react-app.umd.js&quot;&gt;&lt;/script&gt;</pre><h3>How This Package is Built</h3><h3>📦 Tech Stack &amp; Architecture</h3><p>This package is built using:</p><ul><li><strong>React + TypeScript</strong>: Ensures type safety and modularity.</li><li><strong>LangChain</strong>: Provides AI-driven natural language processing.</li><li><strong>UMD Compatibility</strong>: Can be used both in React projects and as a standalone script.</li><li><strong>Webpack</strong>: Bundles the project for optimized performance.</li><li><strong>Jest &amp; React Testing Library</strong>: Ensures component reliability.</li><li><strong>Husky + Linting</strong>: Enforces code quality before commits.</li></ul><h3>📁 Code Structure</h3><p>The project is structured as follows:</p><ul><li><strong>index.tsx</strong> → Main entry point.</li><li><strong>App.tsx</strong> → Core chat interface component.</li><li><strong>components/</strong> → Reusable UI components.</li><li><strong>umd.tsx</strong> → Standalone version for direct HTML use.</li><li>webpack.umd.config.js → Webpack config for UMD builds.</li></ul><p>With this setup, the package is both developer-friendly and easy to integrate into different environments.</p><h3>Features</h3><p>This chatbot component was originally built to accommodate four different chat modes:</p><h3>1️⃣ Simple Chat</h3><p>A basic chat mode where users can interact with an AI model for standard question-answer interactions. This is best suited for general-purpose AI conversations.</p><h3>2️⃣ Contextual Chat</h3><p>This mode allows the AI to maintain conversation history, enabling it to understand context across multiple messages. This is great for scenarios where users need ongoing discussions without losing past context.</p><h3>3️⃣ Document-Based Chat</h3><p>Users can upload PDF documents, and the AI will retrieve relevant information from the document. This is powered by <strong>vector stores using PostgreSQL/Redis</strong>, ensuring efficient search and retrieval.</p><h3>4️⃣ Agent-Assisted Chat with Tavily Search</h3><p>For real-time answers, the chatbot integrates with <strong>Tavily search</strong>, allowing it to fetch live information from the web. This makes it ideal for retrieving the latest news, research, and other dynamic data.</p><h3>Step-by-Step: How to Use It</h3><h3>📌 Using in a React Project</h3><p>Install the package:</p><pre>npm install langchain-chatbot-react-app</pre><p>Import and use it in your React component:</p><pre>import Chatbot from &quot;langchain-chatbot-react-app&quot;;<br><br>function App() {<br>    return &lt;Chatbot endpoint=&quot;https://your-api.com/chat&quot; /&gt;;<br>}<br>export default App;</pre><h3>📌 Using as a Standalone Script in HTML</h3><p>Add React and the chatbot script to your HTML file:</p><pre>&lt;script src=&quot;https://unpkg.com/react@18/umd/react.production.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://unpkg.com/react-dom@18/umd/react-dom.production.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;path/to/langchain-chatbot-react-app.umd.js&quot;&gt;&lt;/script&gt;</pre><ol><li>Add a root div and initialize the chatbot:</li></ol><pre>&lt;div id=&quot;chat-root&quot;&gt;&lt;/div&gt; &lt;script&gt;     window.LangChainReactApp.mountApp({         endpoint: &quot;https://your-api.com/chat&quot;,         titleText: &quot;AI Chatbot&quot;,         placeholder: &quot;Type your message...&quot;     }); &lt;/script&gt;</pre><p>This makes it incredibly easy to integrate the chatbot into any webpage <strong>without needing a React build process</strong>!</p><h3>Show Some Love! ❤️</h3><p>If you find this project useful:</p><ul><li><strong>Clap</strong> for this article on Medium to support my work!</li><li><strong>Give a ⭐️ star</strong> on the <a href="https://github.com/AbdullahDev0/langchain-chatbot-react-app">GitHub repo</a>!</li></ul><p>Your feedback and contributions are welcome! 🚀 Let me know how you’re using this package and what features you’d like to see next. Happy coding! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e0127007cc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain with NestJS (Node framework): Talk with documents part 2]]></title>
            <link>https://medium.com/@abdullahirfan99_80517/langchain-with-nestjs-node-framework-talk-with-documents-part-2-980ef5f02b3a?source=rss-c3537bc6965f------2</link>
            <guid isPermaLink="false">https://medium.com/p/980ef5f02b3a</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Abdullah Irfan]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 17:02:21 GMT</pubDate>
            <atom:updated>2024-03-21T17:02:21.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uL-PMverwhhS5OJR" /></figure><p>This is the fourth story on series <a href="https://medium.com/@abdullahirfan99_80517/langchain-with-nestjs-node-framework-4b1cec5affd9"><strong>LangChain with NestJS (Node framework)</strong></a>, and is focused on enhancing our initially built simple chatbot endpoint to be able to respond to questions from specific documents. Last time we were able to create vector store from PDF file and perform similarity search on hardcoded string. Today we will be updating code of endpoint to upload file from postman and utilize that file to create vector store and then create another endpoint to talk with the document.</p><p>To get the file from user, we will be using multer, a path will be specified to store the file and file will be renamed to random string before being stored to avoid any file overwrite due to same names. Then the file name will be passed to the service and with last code story we will create our vector store. So the code for controller will be:</p><pre>@Post(&#39;upload-document&#39;)<br>@UseInterceptors(<br>  FileInterceptor(&#39;file&#39;, {<br>    storage: diskStorage({<br>      destination: PDF_BASE_PATH,<br>      filename: (req, file, callback) =&gt; {<br>        const randomName = Array(32)<br>          .fill(null)<br>          .map(() =&gt; Math.round(Math.random() * 16).toString(16))<br>          .join(&#39;&#39;);<br>        callback(null, `${randomName}${extname(file.originalname)}`);<br>      },<br>    }),<br>  }),<br>)<br>@HttpCode(200)<br>async loadPDF(<br>  @Body() documentDto: DocumentDto,<br>  @UploadedFile() file: Express.Multer.File,<br>) {<br>  if (file.filename) {<br>    documentDto.file = file.filename;<br>  }<br>  return await this.langchainChatService.uploadPDF(documentDto);<br>}</pre><p>Now we will create an endpoint at /api/v1/langchain-chat/document-chat to get user query, get relevant data from vector store on the query and pass it to LangChain with query for an answer. Here for similarity search we are getting three results (no specific reason for it) and stringifying the data because LangChain invoke method can’t process JSON data that is going to be used by template variable. So our service code is:</p><pre>async documentChat(basicMessageDto: BasicMessageDto) {<br>    try {<br>      const documentContext = await this.vectorStoreService.similaritySearch(<br>        basicMessageDto.user_query,<br>        3,<br>      );<br><br>      const chain = this.loadSingleChain(<br>        TEMPLATES.DOCUMENT_CONTEXT_CHAT_TEMPLATE,<br>      );<br><br>      const response = await chain.invoke({<br>        context: JSON.stringify(documentContext),<br>        question: basicMessageDto.user_query,<br>      });<br>      return this.successResponse(response);<br>    } catch (e: unknown) {<br>      this.exceptionHandling(e);<br>    }<br>  }</pre><p>And the DOCUMENT_CONTEXT_CHAT_TEMPLATE enum value is:</p><pre>DOCUMENT_CONTEXT_CHAT_TEMPLATE = `Answer the question based only on the following context:<br> {context}<br> <br> Question: {question}`,</pre><p>With this, we are ready to consume our endpoints. Let’s start with upload document, the endpoint for it is /api/v1/langchain-chat/upload-document and the postman response is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6z0VGgLVhI0nUoq412ffQ.png" /><figcaption>Document upload response</figcaption></figure><p>Next, we will talk with this PDF, the postman response of query is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tv08G7ozAX0pIsYb0_2XzQ.png" /><figcaption>Response based on document</figcaption></figure><p>So we did get the response, now is it really close to what PDF said or did the we get a hallucination (LLM hallucination refers to instances where a large language model (LLM) like ChatGPT generates incorrect, fabricated, or misleading information while presenting it as factual).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*ThWzKBxWRWTfttsxaKP1Yw.png" /><figcaption>Paper chunk on Naive RAG</figcaption></figure><p>So as it can be observed from PDF text (mentioned in image above), the answer is quite close to what PDF said.</p><p>While writing this code, several refactoring&#39;s were done, so the code from last stories has changed. This story code (the story doesn’t cover all aspects of code, review branch code from <a href="https://github.com/AbdullahDev0/nestjs-langchain">GitHub</a>) is available on <a href="https://github.com/AbdullahDev0/nestjs-langchain">GitHub</a> in <strong>feature/chat-with-docs-part-2</strong> branch. If you appreciate this work, please show your support by clapping for the story and starring the repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=980ef5f02b3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>