Sooner or later, many engineering teams face the same question: We already have a working app—how can we add an AI chat or voice assistant without rebuilding the UI or disrupting the backend?

You do not need a greenfield rewrite, a new database schema, or changes to your existing REST or GraphQL controllers. Instead, treat the LLM as a command compiler and keep command execution in the browser. This lets you add a text-and-voice assistant while leaving the app’s APIs, authentication flow, and state management intact.

The Mental Model: Two Problems, Not One

When a user opens a chat bubble, taps the microphone, and says “Remind me to buy milk tomorrow,” two distinct jobs happen behind the scenes:

  1. Translate natural language into a structured command. A thin server route sends the request to an LLM.
  2. Execute that command in the existing app. The browser uses the app’s current services, state, and authenticated session.
[User types or speaks in the chat popup]
        │
        ▼
[Thin /api/chat route] ──► LLM (emits tool call: addTodo({ title: "Buy milk", dueDate: "2025-11-21" }))
        │
        ▼
[Browser command dispatcher] ──► Calls the existing todoService and /api/todos
        │
        ▼
[Existing UI updates through its normal state and authentication flow]

The important boundary is that /api/chat does not call /api/todos. The browser remains responsible for calling the application APIs, so its authentication cookies or tokens, request headers, error handling, and reactive UI updates continue to work as before.

Step 1: Solve Browser Execution First

Before connecting an LLM, build a deterministic command dispatcher in the front end. Test it with hardcoded inputs first. This separates ordinary application bugs from mistakes in model-generated commands and gives you a reliable foundation for the AI layer.

Define a Single Command Schema

Export the Zod command schemas so the browser dispatcher and AI route share a single contract:

// src/commands/todoCommands.ts
import { z } from 'zod';

export const CommandSchemas = {
  addTodo: z.object({
    title: z
      .string()
      .min(1)
      .describe('Concise task title without filler words like "remind me to"'),
    dueDate: z
      .string()
      .regex(/^\d{4}-\d{2}-\d{2}$/)
      .optional()
      .describe('ISO date YYYY-MM-DD when a deadline or relative day is mentioned'),
  }),
  toggleTodo: z.object({
    id: z.string().describe('Exact ID of the matching task from the current UI list'),
  }),
  deleteTodo: z.object({
    id: z.string().describe('Exact ID of the matching task from the current UI list'),
  }),
};

export type CommandName = keyof typeof CommandSchemas;

Route Validated Commands to Your Existing Service

The dispatcher validates each payload, calls the existing todoService, and refreshes the UI through the app’s normal state flow:

// src/commands/dispatchCommand.ts
import { CommandSchemas, type CommandName } from './todoCommands';
import { todoService } from '../services/todoService';

export async function dispatchCommand(
  name: CommandName,
  rawInput: unknown,
  onTodosChanged: () => Promise<void> | void
) {
  const schema = CommandSchemas[name];
  if (!schema) {
    return { ok: false, error: `Unsupported command: ${name}` };
  }

  const parsed = schema.safeParse(rawInput);
  if (!parsed.success) {
    return { ok: false, error: 'Invalid arguments', issues: parsed.error.flatten() };
  }

  switch (name) {
    case 'addTodo': {
      const created = await todoService.create(parsed.data);
      await onTodosChanged();
      return { ok: true, data: created };
    }
    case 'toggleTodo': {
      const updated = await todoService.toggle(parsed.data.id);
      await onTodosChanged();
      return { ok: true, data: updated };
    }
    case 'deleteTodo': {
      await todoService.remove(parsed.data.id);
      await onTodosChanged();
      return { ok: true, deletedId: parsed.data.id };
    }
  }
}

Step 2: Teach the LLM What Commands Exist

Once dispatchCommand works reliably, add a stateless /api/chat endpoint. This keeps the LLM API key on the server while exposing CommandSchemas as client-side tools. Because the tools have no server-side execute handler, each tool call streams back to the browser for execution.

Two pieces of context make the model much more reliable:

  • Today’s date (for example, "Thursday, 2025-11-20"), so relative phrases such as “tomorrow” resolve correctly.
  • The current tasks (currentTodos), so a request such as “mark the coffee beans task done” maps to an exact task ID instead of a guess.
// app/api/chat/route.ts
import { streamText, tool, convertToModelMessages, type UIMessage } from 'ai';
import { google } from '@ai-sdk/google';
import { CommandSchemas } from '@/commands/todoCommands';

export async function POST(req: Request) {
  const {
    messages,
    currentTodos,
    today,
  }: {
    messages: UIMessage[];
    currentTodos: Array<{ id: string; title: string; completed: boolean }>;
    today: string; // e.g., "Thursday, 2025-11-20"
  } = await req.json();

  const result = streamText({
    model: google('gemini-2.5-flash'),
    system: `You are a helpful assistant inside a To-Do app.
Today is ${today}.
Current tasks in the UI: ${JSON.stringify(currentTodos ?? [])}

Guidelines:
- Answer general questions directly in plain text without calling tools.
- When creating, toggling, or deleting tasks, call the matching tool using exact IDs from the current tasks list.
- Strip filler phrases like "remind me to" so task titles stay clean.
- If a task reference is ambiguous or missing, ask a brief clarifying question rather than guessing an ID.`,
    messages: await convertToModelMessages(messages),
    tools: {
      addTodo: tool({
        description: 'Create a new task when the user asks to add, schedule, or be reminded of something.',
        inputSchema: CommandSchemas.addTodo,
      }),
      toggleTodo: tool({
        description: 'Toggle completion state of an existing task using its exact ID.',
        inputSchema: CommandSchemas.toggleTodo,
      }),
      deleteTodo: tool({
        description: 'Delete an existing task using its exact ID.',
        inputSchema: CommandSchemas.deleteTodo,
      }),
    },
  });

  return result.toUIMessageStreamResponse();
}

Step 3: Add Voice Input and a Floating Chat Popup

Mount a position: fixed chat overlay so the existing page layout stays untouched. For voice input, use the browser’s SpeechRecognition API to place a transcript in the text field before submission.

Browser support for SpeechRecognition varies, so treat voice as a progressive enhancement: keep text input available, and hide or disable the microphone when the API is unavailable.

// src/components/ChatPopup.tsx
import React, { useState } from 'react';
import { useChat } from '@ai-sdk/react';
import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls } from 'ai';
import { dispatchCommand } from '../commands/dispatchCommand';
import type { CommandName } from '../commands/todoCommands';
import type { TodoItem } from '../services/todoService';

interface ChatPopupProps {
  todos: TodoItem[];
  onTodosChanged: () => Promise<void> | void;
}

export const ChatPopup: React.FC<ChatPopupProps> = ({ todos, onTodosChanged }) => {
  const [open, setOpen] = useState(false);
  const [input, setInput] = useState('');
  const [listening, setListening] = useState(false);

  const { messages, sendMessage, addToolOutput, status } = useChat({
    transport: new DefaultChatTransport({ api: '/api/chat' }),
    sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls,
    async onToolCall({ toolCall }) {
      if (toolCall.dynamic) return;

      const result = await dispatchCommand(
        toolCall.toolName as CommandName,
        toolCall.input,
        onTodosChanged
      );

      addToolOutput({
        tool: toolCall.toolName,
        toolCallId: toolCall.toolCallId,
        output: result,
      });
    },
  });

  const handleVoiceInput = () => {
    const SpeechRecognitionCtor =
      (window as unknown as {
        SpeechRecognition?: new () => {
          lang: string;
          interimResults: boolean;
          onstart: (() => void) | null;
          onend: (() => void) | null;
          onerror: (() => void) | null;
          onresult: ((e: { results: ArrayLike<ArrayLike<{ transcript: string }>> }) => void) | null;
          start: () => void;
        };
        webkitSpeechRecognition?: new () => {
          lang: string;
          interimResults: boolean;
          onstart: (() => void) | null;
          onend: (() => void) | null;
          onerror: (() => void) | null;
          onresult: ((e: { results: ArrayLike<ArrayLike<{ transcript: string }>> }) => void) | null;
          start: () => void;
        };
      }).SpeechRecognition ||
      (window as unknown as {
        webkitSpeechRecognition?: new () => {
          lang: string;
          interimResults: boolean;
          onstart: (() => void) | null;
          onend: (() => void) | null;
          onerror: (() => void) | null;
          onresult: ((e: { results: ArrayLike<ArrayLike<{ transcript: string }>> }) => void) | null;
          start: () => void;
        };
      }).webkitSpeechRecognition;

    if (!SpeechRecognitionCtor) return;

    const rec = new SpeechRecognitionCtor();
    rec.lang = 'en-US';
    rec.interimResults = false;
    rec.onstart = () => setListening(true);
    rec.onend = () => setListening(false);
    rec.onerror = () => setListening(false);
    rec.onresult = (e) => {
      const text = e.results[0]?.[0]?.transcript?.trim();
      if (text) setInput(text);
    };
    rec.start();
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim() || status === 'streaming') return;

    const now = new Date();
    const weekday = now.toLocaleDateString('en-CA', { weekday: 'long' });
    const localDate = [
      now.getFullYear(),
      String(now.getMonth() + 1).padStart(2, '0'),
      String(now.getDate()).padStart(2, '0'),
    ].join('-');
    const today = `${weekday}, ${localDate}`;

    sendMessage(
      { text: input.trim() },
      { body: { currentTodos: todos, today } }
    );
    setInput('');
  };

  if (!open) {
    return (
      <button
        type="button"
        onClick={() => setOpen(true)}
        style=
      >
        Chat & Voice
      </button>
    );
  }

  return (
    <div
      style=
    >
      <div style=>
        <strong>Assistant</strong>
        <button type="button" onClick={() => setOpen(false)}>✕</button>
      </div>

      <div style=>
        {messages.map((m) => (
          <div key={m.id} style=>
            <strong>{m.role === 'user' ? 'You' : 'AI'}:</strong>{' '}
            {m.parts.map((part, idx) =>
              part.type === 'text' ? <span key={idx}>{part.text}</span> : null
            )}
          </div>
        ))}
      </div>

      <form onSubmit={handleSubmit} style=>
        <input
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask a question or speak a task..."
          style=
        />
        <button type="button" onClick={handleVoiceInput}>
          {listening ? 'Listening...' : 'Mic'}
        </button>
        <button type="submit" disabled={status === 'streaming'}>
          Send
        </button>
      </form>
    </div>
  );
};

Why This Pattern Scales

Starting with deterministic client-side commands and layering natural-language translation on top keeps the system predictable:

  • Clear debugging boundaries: You can determine whether the model produced the wrong tool call or the existing service returned an error.
  • Incremental expansion: Each new capability requires a schema, a dispatcher case, and a tool definition in /api/chat.
  • Existing authorization stays in place: Commands run through the same browser session and application services as manual actions.
  • The AI layer remains replaceable: The application depends on a small command contract rather than model-specific behavior throughout the codebase.

Keep the Boundary Deliberate

This pattern works best when commands represent actions the UI already knows how to perform. The LLM interprets intent; it does not become a second application backend. Continue to validate every payload, enforce authorization in the existing API, and ask for clarification when a request is ambiguous.

That separation is the main advantage: you can make an established application easier to use with natural language and voice without giving up the architecture that already makes it reliable.