Most email support tutorials stop at "receive the email, send a reply." The interesting problem is everything in between: understanding the customer's issue, looking up their order, deciding whether to replace or refund, composing a personalized response, and updating your systems — all without a human in the loop.

In this tutorial, we will build an AI email support agent that does exactly that. An inbound customer email arrives, an AI agent reasons through the problem using function calling, takes action (replacement, exchange, refund), sends a reply, and resolves the ticket. Every step streams to a three-panel dashboard in real time. The whole thing runs locally with zero credentials in demo mode, and switches to live email and AI inference with a single environment variable.

The application is a single Node.js server that handles everything:

Here is the architecture:

  Customer Email
       |
       v
  +----------------+    POST /v2/ai/chat/completions    +------------------+
  |  Express API   | ---------------------------------> |  Telnyx AI       |
  |  + SQLite      | <---------- tool_calls ----------- |  Inference       |
  +-------+--------+                                    +------------------+
          |                POST /v2/emails
          | ----------------------------------------->  Telnyx Email API
          |
          +---> SSE stream ---> 3-panel dashboard
                                (tickets + emails + AI reasoning)

The Telnyx Email API and AI Inference are part of the Telnyx AI Communications Infrastructure platform, which provides email, SMS, voice, AI, and networking APIs through a single account and API key.

Five demo scenarios run the full pipeline with no credentials:

| Scenario | Customer | Issue | AI Action | |---|---|---|---| | Damaged Item | Maria Santos | Cracked headphones ($249.99) | Immediate replacement, no return needed | | Wrong Size | James Chen | Jacket ordered wrong size ($129.00) | Exchange with prepaid return label | | Late Delivery | Priya Patel | Smartwatch delayed ($329.00) | Tracking update + 15% discount code | | Return Request | Lukas Weber | Shoes don't fit ($159.00) | Full refund, prepaid label sent | | Promo Code | Noah Kim | Discount code not applied ($89.00) | Partial refund for missed discount |

node:sqlite module)

git clone https://github.com/team-telnyx/telnyx-code-examples.git
cd telnyx-code-examples/ecommerce-email-support-nodejs
cp .env.example .env

The default .env enables demo mode, which works without any credentials:

TELNYX_API_KEY=
FROM_EMAIL=support@yourdomain.com
PORT=3000
DEMO_MODE=true
AI_MODEL=meta-llama/Llama-3.3-70B-Instruct
npm install
npm start

One dependency: express. SQLite and fetch are built into Node 22. The server starts on http://localhost:3000:

TelnyxStore Email Support running on http://localhost:3000
Mode: DEMO (no credentials needed)

Open the dashboard and click a scenario button to start.

Open http://localhost:3000 in your browser. You will see the three-panel dashboard with scenario buttons along the top. Click Damaged Item and watch the AI agent work:

Each scenario runs in about 8-12 seconds with animated delays that simulate real inference latency. Click Reset between scenarios to start fresh.

The entire server is a single server.js file (1,318 lines). Let me walk through the four key patterns.

Six tools give the AI agent full access to the support system. Each is defined in OpenAI-compatible function-calling schema:

const AI_TOOLS = [
  {
    type: "function",
    function: {
      name: "lookup_customer",
      description: "Find a customer by their email address",
      parameters: {
        type: "object",
        properties: {
          email: { type: "string", description: "Customer email address" },
        },
        required: ["email"],
      },
    },
  },
  // lookup_order — find by order ID or list all for a customer
  // check_return_eligibility — verify 30-day return window
  // initiate_return — start replacement, exchange, or refund
  // send_email_response — compose and send the reply email
  // resolve_ticket — close the ticket with a summary
];

Each tool maps to an executeTool function that reads/writes SQLite and publishes SSE events. For example, initiate_return updates the order status, generates a tracking number, and broadcasts an order.updated event:

case "initiate_return": {
  const newTracking = "TRK-RPL-" + crypto.randomUUID().slice(0, 8).toUpperCase();
  let newStatus, details;

  switch (toolInput.action) {
    case "replacement":
      newStatus = "replacement_shipped";
      details = `Replacement shipped with tracking ${newTracking}. No return of damaged item needed.`;
      break;
    case "exchange":
      newStatus = "exchange_initiated";
      details = `Exchange initiated. Prepaid return label sent. New item ships when return received.`;
      break;
    case "refund":
      newStatus = "refund_processing";
      details = `Refund of $${order.price.toFixed(2)} initiated. Funds in 5-7 business days.`;
      break;
  }

  db.prepare("UPDATE orders SET status = ?, tracking_number = ? WHERE id = ?")
    .run(newStatus, newTracking, toolInput.order_id);

  ssePublish("order.updated", { order: updatedOrder });
  return JSON.stringify({ success: true, action: toolInput.action, tracking: newTracking, details });
}

This is the core pattern. Build a message array with the system prompt and customer context, call AI inference, execute any tool calls the model returns, append results, and loop until the model stops requesting tools:

async function runAgentLoop(ticketId, customerEmail, subject, body) {
  const messages = [
    { role: "system", content: SYSTEM_PROMPT },
    { role: "user", content: `Customer email: ${customerEmail}\n\nInbound support email:\nSubject: ${subject}\n\n${body}\n\nPlease handle this customer's support request.` },
  ];

  const MAX_ITERATIONS = 10;

  for (let i = 0; i < MAX_ITERATIONS; i++) {
    const data = useMock
      ? mockInference(messages, ticketId)
      : await callInference(messages);

    const msg = data.choices[0].message;

    // Publish thinking step to dashboard
    if (msg.content) {
      ssePublish("agent.thinking", { ticket_id: ticketId, content: msg.content });
    }

    // No more tool calls — AI is done
    if (!msg.tool_calls || msg.tool_calls.length === 0) break;

    // Append assistant message, execute each tool, append results
    messages.push(msg);
    for (const tc of msg.tool_calls) {
      const result = executeTool(tc.function.name, JSON.parse(tc.function.arguments), ticketId);
      ssePublish("agent.tool_result", { ticket_id: ticketId, tool: tc.function.name, result: JSON.parse(result) });
      messages.push({ role: "tool", tool_call_id: tc.id, content: result });
    }
  }
}

The AI inference call itself goes to Telnyx's OpenAI-compatible endpoint:

async function callInference(messages) {
  const resp = await fetch("https://api.telnyx.com/v2/ai/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${TELNYX_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "meta-llama/Llama-3.3-70B-Instruct",
      messages,
      tools: AI_TOOLS,
      tool_choice: "auto",
      max_tokens: 1024,
    }),
  });
  return resp.json();
}

Telnyx AI Inference uses the same tools and tool_choice parameters as the OpenAI Chat Completions API. The model returns tool_calls in choices[0].message when it wants to invoke a function. You execute the function locally, append the result as a tool role message, and call inference again. This loop continues until the model responds without tool calls.

SSE pushes every agent action to the browser in real time. It is unidirectional (server to client), works through proxies, and the browser reconnects automatically:

const subscribers = [];

function ssePublish(eventType, data) {
  const payload = JSON.stringify({ type: eventType, ts: new Date().toISOString(), ...data });
  for (const res of subscribers) {
    try { res.write(`data: ${payload}\n\n`); } catch { /* dead connection */ }
  }
}

app.get("/stream", (req, res) => {
  res.set({
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "X-Accel-Buffering": "no",
  });
  res.flushHeaders();
  subscribers.push(res);

  const keepalive = setInterval(() => {
    try { res.write(": keepalive\n\n"); } catch { /* ignore */ }
  }, 30_000);

  req.on("close", () => {
    clearInterval(keepalive);
    const idx = subscribers.indexOf(res);
    if (idx !== -1) subscribers.splice(idx, 1);
  });
});

The 30-second keepalive comment frame prevents reverse proxies from closing idle connections. Eleven event types cover the full lifecycle: ticket.created, ticket.updated, ticket.resolved, email.inbound, email.outbound, agent.thinking, agent.tool_call, agent.tool_result, agent.done, order.updated, and demo.reset.

In live mode, the /webhooks/email endpoint receives Telnyx email.received events and feeds them into the agent loop:

app.post("/webhooks/email", async (req, res) => {
  const data = req.body?.data || {};
  if (data.event_type !== "email.received") {
    return res.json({ status: "ignored" });
  }

  const p = data.payload || {};
  const fromEmail = p.from?.email || "";
  const subject = p.subject || "(no subject)";
  const body = stripQuotedReply(p.text_body || "");

  // Find or create customer
  let customer = db.prepare("SELECT * FROM customers WHERE email = ?").get(fromEmail);
  if (!customer) {
    // Auto-create from email address
    db.prepare("INSERT INTO customers (name, email, tier, ...) VALUES (?, ?, ?, ...)")
      .run(name, fromEmail, "Gold", ...);
    customer = db.prepare("SELECT * FROM customers WHERE email = ?").get(fromEmail);
  }

  // Create ticket + store inbound email
  db.prepare("INSERT INTO tickets (customer_id, subject, status) VALUES (?, ?, ?)")
    .run(customer.id, subject, "new");
  const ticket = db.prepare("SELECT * FROM tickets ORDER BY id DESC LIMIT 1").get();

  // Publish SSE events
  ssePublish("ticket.created", { ticket, customer });
  ssePublish("email.inbound", { email: inboundEmail, ticket_id: ticket.id });

  res.json({ status: "ok", ticket_id: ticket.id });

  // Run the AI agent loop asynchronously
  runAgentLoop(ticket.id, fromEmail, subject, body);
});

The handler also detects reply threads by matching the Re: subject line prefix against existing tickets, reopening resolved tickets when a customer follows up.

Demo mode and live mode coexist. Even with DEMO_MODE=true, adding a TELNYX_API_KEY enables the Live Mode button in the dashboard header. Click it to compose a customer email from the browser -- the agent processes it with real Telnyx AI Inference and sends a real email reply.

For full production use with inbound webhooks:

DEMO_MODE=false in .env TELNYX_API_KEY ngrok http 3000 The outbound email goes through the Telnyx Email API (POST /v2/emails) with both plain text and HTML bodies:

await fetch("https://api.telnyx.com/v2/emails", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${TELNYX_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    from: { email: FROM_EMAIL, name: "TelnyxStore Support" },
    to: [{ email: toEmail }],
    subject,
    text_body: body,
    html_body: `<div style="font-family:sans-serif;max-width:600px">...</div>`,
  }),
});

Do I need a Telnyx account to try this?

No. Demo mode is the default and runs entirely locally with mock AI inference and five pre-built scenarios. You only need a Telnyx API key for live AI inference and real email sending.

What AI model does this use?

Telnyx AI Inference with meta-llama/Llama-3.3-70B-Instruct by default. It supports OpenAI-compatible function calling, so the agentic loop pattern works the same as it would with GPT-4 or Claude -- just swap the base URL and model name. You can change the model via the AI_MODEL environment variable.

Can I use this pattern for other support channels?

Yes. The agentic loop is channel-agnostic. The same tool definitions and runAgentLoop function work with any input source. Replace the email webhook with an SMS webhook or a chat widget, and the AI processes it identically. The email-whatsapp-support-python example shows this pattern applied to unified email + WhatsApp support.

Why SQLite instead of Postgres?

Node 22 ships node:sqlite as a built-in module. Zero install, zero config, single-file database. WAL mode enables concurrent reads while the agent loop writes. For a local demo or low-traffic production use, it is the right choice. Swap to Postgres when you need horizontal scaling.

原文来源:dev.to