<?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 Soham Yeola on Medium]]></title>
        <description><![CDATA[Stories by Soham Yeola on Medium]]></description>
        <link>https://medium.com/@yeolasoham27?source=rss-a4b8e6255d12------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*B0Fslw5L_anRvbjU</url>
            <title>Stories by Soham Yeola on Medium</title>
            <link>https://medium.com/@yeolasoham27?source=rss-a4b8e6255d12------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:39:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yeolasoham27/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building AI-Powered Angular Apps with LLM Integration]]></title>
            <link>https://medium.com/@yeolasoham27/building-ai-powered-angular-apps-with-llm-integration-29c1a97c250f?source=rss-a4b8e6255d12------2</link>
            <guid isPermaLink="false">https://medium.com/p/29c1a97c250f</guid>
            <dc:creator><![CDATA[Soham Yeola]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 03:15:02 GMT</pubDate>
            <atom:updated>2026-04-28T03:15:02.641Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>With AI becoming mainstream, Angular developers have a unique opportunity to build intelligent, context-aware applications. In this guide, we’ll cover integrating Open AI, Claude, and Gemini APIs into Angular apps — including streaming responses, RAG patterns, and keeping token costs sane.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mv3jAzWOIbsQd8VSGvHpA.png" /></figure><h3>What Does “LLM Integration” Actually Mean?</h3><p>Before we write a single line of code, let’s get the terminology straight.</p><p>A <strong>Large Language Model (LLM)</strong> is an AI system trained on massive amounts of text data to understand and generate human language. Open AI&#39;s GPT-4o, Anthropic’s Claude, and Google’s Gemini are the most prominent examples today. They power everything from chatbots to code assistants to document summarizers.</p><p><strong>LLM Integration</strong> means connecting your Angular application to one of these models via an API, so your app can send a question (called a <em>prompt</em>) and receive an intelligent, context-aware response. Think of it as giving your web application the ability to think, reason, and converse — without you needing to train any AI model yourself.</p><p>The key concepts you’ll encounter throughout this guide are:</p><p><strong>Tokens</strong> — The units LLMs use to process text. A token is roughly 4 characters or 0.75 words. Every API call consumes tokens, and you’re billed for them.</p><p><strong>Streaming</strong> — Instead of waiting for the full response before rendering, streaming sends tokens to your UI one-by-one as they’re generated — exactly like how ChatGPT types out responses in real time.</p><p><strong>RAG (Retrieval-Augmented Generation)</strong> — A pattern where you supply the LLM with relevant documents from your own data before asking it a question. This lets the model answer questions about <em>your</em> content without expensive fine-tuning.</p><p><strong>Context Window</strong> — The maximum amount of text (in tokens) an LLM can process in a single call. Think of it as the model’s short-term memory for that conversation.</p><h3>Why This Matters Right Now</h3><p>We’re at an inflection point. A year ago, integrating an LLM into a production app felt experimental — the APIs were unstable, the costs were unpredictable, and the developer tooling was immature. That has changed dramatically.</p><p>Today, every major cloud provider has production-grade LLM APIs. Pricing has dropped by 90%+ compared to early GPT-4 days. The developer experience has matured: streaming APIs, function calling, structured outputs, and multi-modal inputs are all table-stakes features now.</p><p>For Angular developers specifically, this matters because the enterprise apps where Angular dominates — internal tools, dashboards, customer portals, admin systems — are exactly the category where AI adds the most immediate value. Imagine a data dashboard that answers questions about its own charts. A customer support portal where the agent gets real-time AI-suggested responses. An internal knowledge base that actually understands natural language queries instead of forcing users to guess the right keyword.</p><p>The question is no longer <em>whether</em> to integrate LLMs into Angular apps. It’s <em>how</em> to do it cleanly, efficiently, and at manageable cost.</p><h3>Why Angular + LLMs Make Sense</h3><p>Angular’s opinionated structure — dependency injection, RxJS, services — maps surprisingly well to the async, event-driven nature of LLM APIs. Streaming tokens feel right at home inside Observables. Services are the perfect home for your API clients. TypeScript’s strong typing helps you model prompt/response contracts clearly, reducing runtime surprises when the API response shape changes.</p><h3>Setting Up Your LLM Service Layer</h3><p>The first principle: <strong>never call an LLM API directly from a component</strong>. Always abstract it behind a service. This gives you a single place to handle retries, token tracking, error normalization, and provider swapping.</p><pre>// src/app/services/llm.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient, HttpHeaders } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { environment } from &#39;../../environments/environment&#39;;</pre><pre>export interface LLMMessage {<br>  role: &#39;user&#39; | &#39;assistant&#39; | &#39;system&#39;;<br>  content: string;<br>}</pre><pre>export interface LLMResponse {<br>  content: string;<br>  model: string;<br>  usage: {<br>    promptTokens: number;<br>    completionTokens: number;<br>    totalTokens: number;<br>  };<br>}</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class LLMService {<br>  constructor(private http: HttpClient) {}<br>}</pre><p>This base layer defines two shared interfaces — LLMMessage and LLMResponse — that every provider-specific service will honour. LLMMessage models a single turn in a conversation, with a role (who sent it) and content (what was said). LLMResponse normalizes the output across providers, since OpenAI, Claude, and Gemini all return usage data in slightly different shapes. By agreeing on these interfaces upfront, your components stay completely decoupled from whichever LLM you&#39;re talking to.</p><blockquote><strong><em>Security Note:</em></strong><em> Never ship API keys in your Angular frontend. Always proxy requests through your own backend (Node.js, Django, etc.). The examples below assume you have a backend proxy at </em><em>/api/llm.</em></blockquote><h3>Integrating OpenAI, Claude, and Gemini</h3><h3>OpenAI (GPT-4o)</h3><pre>// openai.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable, map } from &#39;rxjs&#39;;<br>import { LLMMessage, LLMResponse } from &#39;./llm.service&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class OpenAIService {<br>  private readonly apiUrl = &#39;/api/openai/chat&#39;;</pre><pre>  constructor(private http: HttpClient) {}</pre><pre>  chat(messages: LLMMessage[], model = &#39;gpt-4o&#39;): Observable&lt;LLMResponse&gt; {<br>    return this.http.post&lt;any&gt;(this.apiUrl, { model, messages }).pipe(<br>      map(res =&gt; ({<br>        content: res.choices[0].message.content,<br>        model: res.model,<br>        usage: {<br>          promptTokens: res.usage.prompt_tokens,<br>          completionTokens: res.usage.completion_tokens,<br>          totalTokens: res.usage.total_tokens,<br>        },<br>      }))<br>    );<br>  }<br>}</pre><p>The OpenAI service is the most straightforward of the three. It POSTs to your backend proxy, which forwards the request to api.openai.com. The RxJS map operator reshapes the raw API response into our unified LLMResponse interface. Notice res.choices[0] — OpenAI supports generating multiple response candidates simultaneously, so it always returns an array; we take the first. The model parameter defaults to gpt-4o but can be overridden at the call site to use cheaper variants like gpt-4o-mini for simpler tasks.</p><h3>Anthropic Claude</h3><pre>// claude.service.ts<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class ClaudeService {<br>  private readonly apiUrl = &#39;/api/claude/messages&#39;;</pre><pre>  constructor(private http: HttpClient) {}</pre><pre>  chat(messages: LLMMessage[], model = &#39;claude-sonnet-4-20250514&#39;): Observable&lt;LLMResponse&gt; {<br>    const body = {<br>      model,<br>      max_tokens: 1024,<br>      messages: messages.filter(m =&gt; m.role !== &#39;system&#39;),<br>      system: messages.find(m =&gt; m.role === &#39;system&#39;)?.content,<br>    };</pre><pre>    return this.http.post&lt;any&gt;(this.apiUrl, body).pipe(<br>      map(res =&gt; ({<br>        content: res.content[0].text,<br>        model: res.model,<br>        usage: {<br>          promptTokens: res.usage.input_tokens,<br>          completionTokens: res.usage.output_tokens,<br>          totalTokens: res.usage.input_tokens + res.usage.output_tokens,<br>        },<br>      }))<br>    );<br>  }<br>}</pre><p>Claude’s API has one important structural difference from OpenAI: the system prompt is a top-level field, not a message with role: &#39;system&#39;. This service handles that automatically — it filters system messages out of the messages array and hoists the system content to the dedicated system field. Passing a system message inside the messages array to Claude&#39;s API will throw a validation error, so this transformation is essential. The explicit max_tokens: 1024 is intentional — always cap this to prevent runaway response lengths, which we&#39;ll expand on in the cost management section.</p><h3>Google Gemini</h3><pre>// gemini.service.ts<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class GeminiService {<br>  private readonly apiUrl = &#39;/api/gemini/generate&#39;;</pre><pre>  constructor(private http: HttpClient) {}</pre><pre>  chat(messages: LLMMessage[]): Observable&lt;LLMResponse&gt; {<br>    const contents = messages<br>      .filter(m =&gt; m.role !== &#39;system&#39;)<br>      .map(m =&gt; ({<br>        role: m.role === &#39;assistant&#39; ? &#39;model&#39; : &#39;user&#39;,<br>        parts: [{ text: m.content }],<br>      }));</pre><pre>    return this.http.post&lt;any&gt;(this.apiUrl, {<br>      model: &#39;gemini-2.0-flash&#39;,<br>      contents,<br>    }).pipe(<br>      map(res =&gt; ({<br>        content: res.candidates[0].content.parts[0].text,<br>        model: &#39;gemini-2.0-flash&#39;,<br>        usage: {<br>          promptTokens: res.usageMetadata.promptTokenCount,<br>          completionTokens: res.usageMetadata.candidatesTokenCount,<br>          totalTokens: res.usageMetadata.totalTokenCount,<br>        },<br>      }))<br>    );<br>  }<br>}</pre><p>Gemini has the most unique message format of the three. Where OpenAI and Claude use role: &#39;assistant&#39;, Gemini uses role: &#39;model&#39; — so we translate that in the map. Gemini also wraps message content inside a parts array to support multi-modal inputs (text, images, audio) in the same message. The response structure mirrors this — res.candidates[0].content.parts[0].text drills through candidates → content → parts to reach the actual text. gemini-2.0-flash is Gemini&#39;s lightweight, fast model and is the most cost-effective of all three providers for most tasks.</p><h3>Handling Streaming Responses</h3><p>Streaming is what separates a great AI UX from a frustrating one. Nobody wants to stare at a spinner for 10 seconds. With streaming, tokens appear in real time — just like ChatGPT. Angular’s HttpClient doesn&#39;t natively support SSE (Server-Sent Events), but we can use the browser&#39;s native fetch API with ReadableStream, wrapped in an RxJS Observable so it stays idiomatic Angular.</p><h3>Streaming with Fetch + RxJS</h3><pre>// streaming.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class StreamingService {</pre><pre>  streamChat(messages: { role: string; content: string }[]): Observable&lt;string&gt; {<br>    return new Observable(observer =&gt; {<br>      const controller = new AbortController();</pre><pre>      fetch(&#39;/api/openai/stream&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        body: JSON.stringify({ messages }),<br>        signal: controller.signal,<br>      }).then(async response =&gt; {<br>        if (!response.ok) {<br>          observer.error(new Error(`HTTP error: ${response.status}`));<br>          return;<br>        }</pre><pre>        const reader = response.body!.getReader();<br>        const decoder = new TextDecoder();</pre><pre>        while (true) {<br>          const { done, value } = await reader.read();<br>          if (done) { observer.complete(); break; }</pre><pre>          const chunk = decoder.decode(value);<br>          const lines = chunk.split(&#39;\n&#39;).filter(l =&gt; l.startsWith(&#39;data: &#39;));</pre><pre>          for (const line of lines) {<br>            const data = line.replace(&#39;data: &#39;, &#39;&#39;).trim();<br>            if (data === &#39;[DONE]&#39;) { observer.complete(); return; }</pre><pre>            try {<br>              const parsed = JSON.parse(data);<br>              const token = parsed.choices?.[0]?.delta?.content;<br>              if (token) observer.next(token);<br>            } catch { /* skip malformed chunks */ }<br>          }<br>        }<br>      }).catch(err =&gt; {<br>        if (err.name !== &#39;AbortError&#39;) observer.error(err);<br>      });</pre><pre>      // Cleanup on unsubscribe<br>      return () =&gt; controller.abort();<br>    });<br>  }<br>}</pre><p>This is the heart of the streaming implementation. LLM streaming APIs use the SSE (Server-Sent Events) format — a plain HTTP connection that stays open, with the server pushing data: {...} lines as each token is generated. The ReadableStream reader loop consumes these in real time, and each token is pushed into the RxJS Observable via observer.next(token). The AbortController is the critical cleanup mechanism — when the Angular component unsubscribes (e.g., user navigates away), the return () =&gt; controller.abort() teardown function kills the in-flight HTTP request immediately. Without this, the browser would keep the connection alive even after the component is destroyed, wasting bandwidth and causing potential memory leaks.</p><h3>Streaming Component</h3><pre>// chat.component.ts<br>@Component({<br>  selector: &#39;app-chat&#39;,<br>  template: `<br>    &lt;div class=&quot;chat-container&quot;&gt;<br>      &lt;div class=&quot;messages&quot;&gt;<br>        &lt;div *ngFor=&quot;let msg of messages&quot; [class]=&quot;&#39;message &#39; + msg.role&quot;&gt;<br>          {{ msg.content }}<br>        &lt;/div&gt;<br>        &lt;div *ngIf=&quot;streamingContent&quot; class=&quot;message assistant streaming&quot;&gt;<br>          {{ streamingContent }}<br>          &lt;span class=&quot;cursor&quot;&gt;▌&lt;/span&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;input-area&quot;&gt;<br>        &lt;textarea [(ngModel)]=&quot;userInput&quot; (keydown.enter)=&quot;sendMessage($event)&quot;&gt;&lt;/textarea&gt;<br>        &lt;button (click)=&quot;sendMessage()&quot; [disabled]=&quot;isStreaming&quot;&gt;Send&lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class ChatComponent implements OnDestroy {<br>  messages: { role: string; content: string }[] = [];<br>  userInput = &#39;&#39;;<br>  streamingContent = &#39;&#39;;<br>  isStreaming = false;<br>  private streamSub?: Subscription;</pre><pre>  constructor(private streamingService: StreamingService) {}</pre><pre>  sendMessage(event?: KeyboardEvent) {<br>    if (event?.shiftKey) return;<br>    event?.preventDefault();<br>    if (!this.userInput.trim() || this.isStreaming) return;</pre><pre>    const userMessage = { role: &#39;user&#39;, content: this.userInput.trim() };<br>    this.messages.push(userMessage);<br>    this.userInput = &#39;&#39;;<br>    this.isStreaming = true;<br>    this.streamingContent = &#39;&#39;;</pre><pre>    this.streamSub = this.streamingService.streamChat(this.messages)<br>      .subscribe({<br>        next: token =&gt; this.streamingContent += token,<br>        error: err =&gt; {<br>          console.error(&#39;Stream error:&#39;, err);<br>          this.isStreaming = false;<br>        },<br>        complete: () =&gt; {<br>          this.messages.push({ role: &#39;assistant&#39;, content: this.streamingContent });<br>          this.streamingContent = &#39;&#39;;<br>          this.isStreaming = false;<br>        }<br>      });<br>  }</pre><pre>  ngOnDestroy() { this.streamSub?.unsubscribe(); }<br>}</pre><p>The component maintains two separate text buffers: messages (the committed conversation history) and streamingContent (the currently-streaming response). As each token arrives via observer.next, it&#39;s appended to streamingContent, giving the user that live typing effect. When the stream completes, streamingContent is moved into messages as a proper assistant turn, and the buffer is cleared. The blinking ▌ cursor in the template is a small UX touch — it makes the in-progress response visually distinguishable from completed messages. The ngOnDestroy unsubscribe is critical: without it, navigating away mid-stream would leave the Observable active in the background, draining resources silently.</p><h3>Implementing RAG (Retrieval-Augmented Generation)</h3><h3>What is RAG and Why Use It?</h3><p>Imagine you’ve built an HR portal and want employees to ask natural language questions about company policies. The LLM has no idea what your policies say — they weren’t in its training data. You have two options: fine-tune the model on your documents (weeks of work, thousands of dollars, requires ML expertise) or use RAG (a few hours of work, a vector database, and a well-crafted prompt).</p><p>RAG works in three steps. First, every document in your knowledge base is converted into a mathematical representation called an <em>embedding</em> — a vector of numbers that captures the semantic meaning of the text. These embeddings are stored in a vector database (Pinecone, Weaviate, pgvector, etc.). When a user asks a question, that question is also embedded, and the vector database finds the most semantically similar documents. Those documents are then injected directly into the LLM prompt as context, and the model answers based on what it just read.</p><p>The flow looks like this:</p><pre>User Query → Embed Query → Vector Search → Retrieve Top-K Docs → Inject into Prompt → LLM Response</pre><p>The magic of RAG is that the LLM doesn’t need to “know” anything in advance — it reads the relevant documents you hand it and synthesizes an answer. It’s like an open-book exam rather than a memorization test. And because your documents live in your own database, you can update them any time without touching the model.</p><h3>RAG Service in Angular</h3><pre>// rag.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { switchMap, Observable } from &#39;rxjs&#39;;</pre><pre>export interface Document {<br>  id: string;<br>  content: string;<br>  metadata: Record&lt;string, any&gt;;<br>  score?: number;<br>}</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class RagService {<br>  constructor(private http: HttpClient) {}</pre><pre>  retrieveRelevantDocs(query: string, topK = 5): Observable&lt;Document[]&gt; {<br>    return this.http.post&lt;Document[]&gt;(&#39;/api/rag/search&#39;, { query, topK });<br>  }</pre><pre>  buildRagPrompt(userQuery: string, docs: Document[]): string {<br>    const context = docs<br>      .map((d, i) =&gt; `[Source ${i + 1}]: ${d.content}`)<br>      .join(&#39;\n\n&#39;);</pre><pre>    return `You are a helpful assistant. Answer the question using ONLY the provided context.<br>If the answer is not in the context, say &quot;I don&#39;t have enough information to answer that.&quot;</pre><pre>CONTEXT:<br>${context}</pre><pre>QUESTION: ${userQuery}</pre><pre>ANSWER:`;<br>  }</pre><pre>  query(userQuery: string): Observable&lt;{ answer: string; sources: Document[] }&gt; {<br>    return this.retrieveRelevantDocs(userQuery).pipe(<br>      switchMap(docs =&gt; {<br>        const prompt = this.buildRagPrompt(userQuery, docs);<br>        return this.http.post&lt;{ answer: string }&gt;(&#39;/api/llm/chat&#39;, {<br>          messages: [{ role: &#39;user&#39;, content: prompt }]<br>        }).pipe(<br>          switchMap(res =&gt; [{ answer: res.answer, sources: docs }] as any)<br>        );<br>      })<br>    );<br>  }<br>}</pre><p>The RagService composes the three RAG steps into a clean RxJS pipeline using switchMap. retrieveRelevantDocs hits your backend, which handles the actual embedding and vector search — Angular stays out of the ML work entirely. buildRagPrompt is where prompt engineering happens. Notice the explicit instruction: &quot;Answer the question using ONLY the provided context.&quot; This is called <em>grounding</em>, and it&#39;s what prevents the LLM from hallucinating answers that aren&#39;t supported by your documents. The fallback instruction — &quot;I don&#39;t have enough information&quot; — is equally important. Without it, LLMs tend to guess confidently rather than admit uncertainty. The score field on each Document tells you how semantically close that document was to the query, letting you filter out low-relevance results before they inflate your token count.</p><h3>Displaying RAG Results with Source Citations</h3><pre>// rag-chat.component.ts<br>@Component({<br>  selector: &#39;app-rag-chat&#39;,<br>  template: `<br>    &lt;div class=&quot;rag-response&quot; *ngIf=&quot;lastResponse&quot;&gt;<br>      &lt;p class=&quot;answer&quot;&gt;{{ lastResponse.answer }}&lt;/p&gt;<br>      &lt;details class=&quot;sources&quot;&gt;<br>        &lt;summary&gt;📚 {{ lastResponse.sources.length }} sources used&lt;/summary&gt;<br>        &lt;div *ngFor=&quot;let src of lastResponse.sources; let i = index&quot; class=&quot;source&quot;&gt;<br>          &lt;strong&gt;Source {{ i + 1 }}:&lt;/strong&gt;<br>          &lt;p&gt;{{ src.content | slice:0:200 }}...&lt;/p&gt;<br>          &lt;small&gt;{{ src.metadata[&#39;filename&#39;] }} — Score: {{ src.score | number:&#39;1.2-2&#39; }}&lt;/small&gt;<br>        &lt;/div&gt;<br>      &lt;/details&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class RagChatComponent {<br>  lastResponse?: { answer: string; sources: Document[] };</pre><pre>  constructor(private ragService: RagService) {}</pre><pre>  ask(query: string) {<br>    this.ragService.query(query).subscribe(res =&gt; {<br>      this.lastResponse = res;<br>    });<br>  }<br>}</pre><p>The source citation UI uses the HTML &lt;details&gt; element — a semantically correct, accessible disclosure widget with no JavaScript needed. Showing citations isn&#39;t just a nice-to-have; in production RAG systems, they&#39;re often a trust requirement. They let users verify answers, spot outdated content, and understand why the model responded the way it did. The similarity score displayed alongside each source is especially useful during development — it quickly reveals when your retrieval is pulling in off-topic documents, which is usually the first thing to debug when RAG answers feel wrong.</p><h3>Managing Token Costs</h3><p>Token cost management is one of the most underestimated concerns in LLM application development. Unlike traditional APIs where you pay per request, LLM APIs charge based on how much text flows through them — every word in your prompt and every word in the response costs money. This creates some non-obvious failure modes: a well-intentioned feature that passes long conversation histories to the API can quietly run up costs 10x faster than you’d expect.</p><p>The good news is that there are well-established techniques to keep costs under control without degrading user experience. Let’s walk through each one.</p><h3>1. Real-Time Token Tracking</h3><p>The first step is visibility. You can’t manage what you can’t measure. Every LLM API response includes usage metadata — how many tokens were in the prompt, how many in the response. Your application should capture and record this on every single API call.</p><p>Each provider has different pricing tiers. As of mid-2025, gpt-4o costs around $2.50 per million input tokens and $10 per million output tokens. Claude Sonnet is in a similar range. Gemini Flash, however, is dramatically cheaper at roughly $0.10 input / $0.40 output — making it an excellent default choice for high-frequency, lower-complexity tasks. A TokenTrackerService that records each call with its model, token counts, and calculated dollar cost gives you an in-app usage dashboard and lets you set per-session or per-user spending thresholds before they become a billing surprise.</p><pre>// token-tracker.service.ts<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class TokenTrackerService {<br>  private usage: { date: string; tokens: number; cost: number }[] = [];</pre><pre>  private readonly pricing = {<br>    &#39;gpt-4o&#39;: { input: 2.50, output: 10.00 },<br>    &#39;claude-sonnet-4-20250514&#39;: { input: 3.00, output: 15.00 },<br>    &#39;gemini-2.0-flash&#39;: { input: 0.10, output: 0.40 },<br>  };</pre><pre>  track(model: string, promptTokens: number, completionTokens: number) {<br>    const p = this.pricing[model as keyof typeof this.pricing] ?? { input: 5, output: 15 };<br>    const cost = (promptTokens / 1_000_000) * p.input +<br>                 (completionTokens / 1_000_000) * p.output;</pre><pre>    this.usage.push({ date: new Date().toISOString(), tokens: promptTokens + completionTokens, cost });<br>    console.debug(`[Tokens] ${model}: ${promptTokens}→${completionTokens} | $${cost.toFixed(6)}`);<br>  }</pre><pre>  getTotalCost(): number {<br>    return this.usage.reduce((sum, u) =&gt; sum + u.cost, 0);<br>  }</pre><pre>  getTodayTokens(): number {<br>    const today = new Date().toDateString();<br>    return this.usage<br>      .filter(u =&gt; new Date(u.date).toDateString() === today)<br>      .reduce((sum, u) =&gt; sum + u.tokens, 0);<br>  }<br>}</pre><p>The tracker keeps a running log of every call, calculates the dollar cost using provider-specific rates, and exposes methods to query totals by time period. The console.debug line gives you instant per-call cost visibility during development — when you see a single call logging $0.004, you know to rethink whether that feature should be calling a cheaper model instead. In production, persist this log to a backend and surface it in an admin dashboard.</p><h3>2. Prompt Caching — Stop Paying for the Same Answer Twice</h3><p>Many LLM-powered features send nearly identical prompts repeatedly. A FAQ chatbot might receive the same five questions dozens of times per hour. A document summarizer called on the same file twice in quick succession is pure waste. Prompt caching solves this by storing the LLM’s response the first time a prompt is seen, and returning the cached result immediately on subsequent identical calls — without touching the API at all.</p><p>The key insight is that the LLM doesn’t need to “think” again if it’s seen the exact same question before. The answer is deterministic enough at a given temperature setting that returning a cached response is completely legitimate. For FAQ-style bots or document analysis tools with repeated queries, cache hit rates of 60–70% are realistic in production, translating directly to 60–70% cost reduction on those features.</p><pre>// prompt-cache.service.ts<br>import { Injectable, signal } from &#39;@angular/core&#39;;</pre><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class PromptCacheService {<br>  private cache = new Map&lt;string, { response: string; timestamp: number; hits: number }&gt;();<br>  private readonly TTL_MS = 5 * 60 * 1000; // 5 minutes<br>  cacheHits = signal(0);<br>  cacheMisses = signal(0);</pre><pre>  private hashPrompt(prompt: string): string {<br>    let hash = 0;<br>    for (let i = 0; i &lt; prompt.length; i++) {<br>      hash = ((hash &lt;&lt; 5) - hash) + prompt.charCodeAt(i);<br>      hash |= 0;<br>    }<br>    return hash.toString();<br>  }</pre><pre>  get(prompt: string): string | null {<br>    const key = this.hashPrompt(prompt);<br>    const entry = this.cache.get(key);<br>    if (!entry || Date.now() - entry.timestamp &gt; this.TTL_MS) return null;<br>    entry.hits++;<br>    this.cacheHits.update(n =&gt; n + 1);<br>    return entry.response;<br>  }</pre><pre>  set(prompt: string, response: string) {<br>    const key = this.hashPrompt(prompt);<br>    this.cache.set(key, { response, timestamp: Date.now(), hits: 0 });<br>    this.cacheMisses.update(n =&gt; n + 1);<br>  }<br>}</pre><p>Angular Signals make cache statistics reactive — your UI can display live cache hit rates as a cost-reduction metric. The 5-minute TTL is a sensible default for most use cases; tune it based on how often your underlying data changes.</p><h3>3. Conversation Summarization — Defeating Context Bloat</h3><p>Every message in a conversation is re-sent to the API with the next message. This is how LLMs maintain conversational memory — but it means a 50-turn conversation is sending 50 messages’ worth of tokens on every single API call. The cost compounds linearly with conversation length.</p><p>The solution is automatic summarization. When conversation history crosses a threshold, the older messages are collapsed into a summary using a single LLM call. The conversation continues with that summary as its starting point, and only the most recent messages in full detail. Users experience seamless continuity; your token bill doesn’t spiral.</p><pre>// context-manager.service.ts<br>@Injectable({ providedIn: &#39;root&#39; })<br>export class ContextManagerService {<br>  private readonly SUMMARY_THRESHOLD = 15;</pre><pre>  constructor(private openAI: OpenAIService) {}</pre><pre>  async pruneHistory(messages: LLMMessage[]): Promise&lt;LLMMessage[]&gt; {<br>    if (messages.length &lt; this.SUMMARY_THRESHOLD) return messages;</pre><pre>    const toSummarize = messages.slice(0, -6);<br>    const recent = messages.slice(-6);</pre><pre>    const summaryPrompt: LLMMessage[] = [{<br>      role: &#39;user&#39;,<br>      content: `Summarize this conversation in 3-4 sentences, preserving key facts:\n\n${<br>        toSummarize.map(m =&gt; `${m.role}: ${m.content}`).join(&#39;\n&#39;)<br>      }`<br>    }];</pre><pre>    return new Promise(resolve =&gt; {<br>      this.openAI.chat(summaryPrompt).subscribe(res =&gt; {<br>        resolve([<br>          { role: &#39;system&#39;, content: `Previous conversation summary: ${res.content}` },<br>          ...recent<br>        ]);<br>      });<br>    });<br>  }<br>}</pre><p>The most recent 6 messages are always kept verbatim — this preserves the immediate context the model needs for coherent replies. Everything older is compressed into one system message. This caps your effective context size regardless of how long the conversation runs. For multi-turn support bots, this technique alone can cut per-session token consumption by 60% on conversations longer than 20 turns.</p><h3>4. Right-Sizing Your Model Choice</h3><p>Not every task needs the most powerful model. A well-designed LLM application routes different task types to the appropriate model tier. Use flagship models (GPT-4o, Claude Sonnet) for nuanced reasoning, long-form generation, or complex instructions. Use lightweight models (GPT-4o-mini, Gemini Flash) for classification, intent detection, short summarization, or simple formatting tasks.</p><p>The capability gap between these tiers is smaller than you’d expect for simple tasks, but the cost difference is enormous — often 10–20x cheaper. A practical approach: classify the user’s intent first using a cheap model, then decide which model to invoke for the actual response. The classification call costs almost nothing and can save dramatically on the response.</p><h3>5. Setting Hard Token Limits</h3><p>Always pass max_tokens explicitly on every API call. Without it, the model generates as many tokens as it wants — and a verbose model answering a simple question can easily produce 3,000 tokens when 200 would have sufficed. Set conservative limits based on your expected response length, then adjust upward only when needed. For a chatbot, 512 tokens is usually plenty. For a document summarizer, 1,024–2,048. For code generation, you might need 4,096. Having explicit limits prevents runaway generations from appearing as silent billing surprises at end of month.</p><h3>Putting It All Together: Architecture Overview</h3><pre>┌─────────────────────────────────────────┐<br>│           Angular Application           │<br>│                                         │<br>│  ChatComponent / RagChatComponent       │<br>│       ↓             ↓                   │<br>│  StreamingService   RagService          │<br>│       ↓             ↓                   │<br>│  TokenTracker ← LLMService (abstraction)│<br>│       ↓             ↓                   │<br>│  PromptCache   ContextManager           │<br>└──────────────────┬──────────────────────┘<br>                   │ HTTP (proxied)<br>┌──────────────────▼──────────────────────┐<br>│           Your Backend Proxy            │<br>│    (Node.js / Django / any server)      │<br>│         Holds API Keys Securely         │<br>└──────┬──────────┬──────────┬────────────┘<br>       │          │          │<br>   OpenAI      Claude     Gemini</pre><p>Every component talks only to services. Every service routes through the abstraction layer. The backend proxy is the only thing that ever sees your API keys. Cost tracking, caching, and context pruning operate as cross-cutting concerns at the service layer — invisible to components, transparent to the rest of the stack.</p><h3>What to Build Next</h3><p>Once these building blocks are in place, the possibilities expand rapidly:</p><ul><li><strong>A document Q&amp;A system</strong> powered by RAG over your company’s knowledge base</li><li><strong>A code review assistant</strong> embedded directly into your development workflow</li><li><strong>A customer support chatbot</strong> with streaming responses and source citations</li><li><strong>A multi-model router</strong> that selects the most cost-efficient model for each query type</li><li><strong>An analytics dashboard</strong> that allows users to ask natural language questions about their own data</li></ul><p>The patterns here — service abstraction, RxJS streaming, RAG retrieval, token tracking — are the foundation for all of them.</p><h3>Key Takeaways</h3><p>As you reach the end of this guide, a few core principles should remain central:</p><ul><li><strong>Abstraction is foundational.</strong> Route all LLM interactions through a <strong>service layer</strong>, not directly from components — ensuring flexibility, maintainability, and provider independence.</li><li><strong>Streaming is the default UX.</strong> Progressive responses make applications feel <strong>significantly faster and more responsive</strong>, regardless of total latency.</li><li><strong>RAG over fine-tuning (for most cases).</strong> It is <strong>cheaper, faster to iterate, and more transparent</strong>, grounding outputs in retrievable data.</li><li><strong>Token cost is an engineering responsibility.</strong> Actively manage usage through <strong>tracking, caching, context pruning, and model selection</strong>.</li><li><strong>Security is non-negotiable.</strong> Keep <strong>API keys on the server</strong> and <strong>proxy all LLM requests</strong> through your backend.</li></ul><p>These are not optimizations — they are <strong>foundational decisions</strong> that directly impact <strong>scalability, cost, and long-term maintainability</strong>.</p><h3><strong>Final Thought</strong></h3><p>Integrating LLMs into Angular isn’t magic — it’s just good service design applied to a new kind of API. The streaming pattern slots cleanly into RxJS. RAG is HTTP + smart prompting. Token cost management is observability with a pricing formula attached.</p><p>Start small: pick one provider, add the service layer, wire up streaming in one component. Then expand from there. The architecture above scales from a weekend project to a production application without needing to be rebuilt.</p><p>Happy building. 🚀</p><p><strong>Tags:</strong> Angular AI LLM OpenAI Claude Gemini TypeScript RAG Web Development Machine Learning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29c1a97c250f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>