Build an AI Email Support Agent with Node.js and Telnyx (Full Tutorial) A developer published a tutorial showing how to build an AI email support agent in Node.js that uses function calling to handle customer tickets end to end — looking up customers and orders, deciding on replacements, exchanges or refunds, sending replies, and resolving tickets — while streaming each step to a three-panel dashboard over SSE. The single-file server runs locally in a credential-free demo mode with five seeded scenarios and switches to live email and AI inference via environment variables, using Telnyx's Email API and OpenAI-compatible AI Inference with a Llama-3.3-70B-Instruct model. 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: js 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: js 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: js 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: js 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: js 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: js 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: