Hi, is it possible to have AI Agent that chats in ...
# ask-ai
h
Hi, is it possible to have AI Agent that chats in text messages and use tools, using the livekit sdk in typescript?
t
Thanks for reaching out, Valentin. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking whether you can build an AI agent that chats via text messages and calls tools using the LiveKit TypeScript SDK — yes, you can. What you can do with LiveKit Agents in TypeScript: • Handle text chat: agents can receive text messages on the
lk.chat
topic and generate text replies (they can also interrupt speech if needed). • Trigger tools/function calls: define tools with
llm.tool()
(use Zod for schema validation) and the agent can call those tools during reply generation; tool outputs are fed back into the LLM context. • Generate replies programmatically: use
generateReply()
or custom callbacks to control how messages are processed and when tools run. If you want, I can: • Share a short TypeScript example showing a text-only agent that calls a simple tool, or • Ask a couple quick questions to tailor the example (e.g., do you need the agent to run on server-side only, which LLM provider you plan to use, and what kind of tool actions you need). Which would you prefer? Sources: Text and transcriptions | LiveKit docs | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Agent speech and audio | LiveKit docs
h
the issue is that the Session is waiting for TTS by some reason and fails for that. Can you create me a TS example with very simple tool like dice roll or whatever, just to make sure it works fine. for the LLM it doesn't matter gpt-4o would be ok, I guess...
t
Below is a minimal TypeScript example demonstrating a LiveKit Agent that: • Listens for text chat (
lk.chat
) messages • Uses a simple dice-roll tool via
llm.tool()
• Generates a text reply only (no TTS), so the Session won't wait for speech Adjust imports and config to match your environment (API keys, LLM provider). This example focuses on the agent logic that avoids TTS by sending only text responses.
Copy code
// Minimal LiveKit Agent (TypeScript) — text-only + simple dice tool

import { Agent, llm } from "livekit-agents"; // adjust package name if needed
import { z } from "zod";

// Simple dice-roll tool
const rollDiceTool = llm.tool(
  {
    name: "roll_dice",
    description: "Roll N dice with M sides each, return results and sum",
    inputSchema: z.object({
      count: z.number().int().min(1).max(10).optional().default(1),
      sides: z.number().int().min(2).max(100).optional().default(6),
    }),
  },
  async ({ input }) => {
    const count = input.count ?? 1;
    const sides = input.sides ?? 6;
    const rolls: number[] = [];
    for (let i = 0; i < count; i++) {
      rolls.push(Math.floor(Math.random() * sides) + 1);
    }
    const sum = rolls.reduce((a, b) => a + b, 0);
    return { rolls, sum };
  }
);

// Create an agent configured for text-only replies
const agent = new Agent({
  // LLM configuration: use gpt-4o or another provider as needed
  // Example shape — replace with your actual provider config
  llm: {
    model: "gpt-4o",
    // apiKey: process.env.OPENAI_API_KEY, // configure as required
  },
  tools: [rollDiceTool],
  // Ensure agent does not auto-generate speech or TTS:
  // - If the SDK has a specific option to disable speech, set it here.
  // - Otherwise, ensure replies are generated as text and not sent to a TTS step.
  // (This example forces text replies in the handler below.)
});

// Handler: process incoming text chat messages and reply using generateReply()
agent.onIncomingText(async (ctx) => {
  // ctx contains the message, session, and helpers
  const msg = ctx.message.text.trim();

  // Simple intent detection: call roll_dice when user asks to roll
  if (/roll/i.test(msg)) {
    // Example: parse "roll 2d6" or default to 1d6
    const match = msg.match(/(\d+)\s*d\s*(\d+)/i);
    const count = match ? parseInt(match[1], 10) : 1;
    const sides = match ? parseInt(match[2], 10) : 6;

    // Use the tool via a function call from the LLM by providing a prompt that
    // instructs the model to call `roll_dice`. Alternatively, call the tool directly.
    // Here we call the tool directly to avoid any TTS or extra behavior.
    const toolResult = await rollDiceTool.run({ count, sides });

    const replyText = `Rolled ${count}d${sides}: [${toolResult.rolls.join(
      ", "
    )}] (sum: ${toolResult.sum})`;

    // Send a text-only reply back to the session/user.
    // Use ctx.session.sendText(...) or appropriate SDK method to reply with text only.
    // Replace `sendText` with the correct API for sending chat messages in your SDK.
    await ctx.session.sendText(replyText);

    return;
  }

  // Default behavior: ask clarifying question or echo
  await ctx.session.sendText("Send 'roll' or 'roll 2d6' to roll dice.");
});

// Start the agent (server-side)
async function start() {
  await agent.start();
  console.log("Agent started (text-only, dice tool enabled).");
}

start().catch((err) => {
  console.error("Agent failed to start:", err);
});
Notes and tips: • Use the SDK method that explicitly sends chat/text messages (example used
ctx.session.sendText
). Ensure that method does not trigger TTS. If your SDK has a message payload field like
contentType
or
mode
, set it to text-only. • If the session still waits for TTS, inspect the session/message metadata to ensure no
speak
,
tts
, or audio fields are included when sending replies. • If your Agent has an option to disable speech generation globally, enable it in the agent configuration. If you want, I can: • Convert this into a complete runnable example tailored to your LiveKit package versions and LLM provider settings, or • Show how to explicitly set message metadata to ensure no TTS is triggered. Which would help more?