Voice AI

Predict Churn Before Customers Leave

Customer churn rarely comes out of nowhere.

Before a customer cancels, there are usually signals: usage drops, support tickets increase, logins slow down, payment problems show up, or a renewal date gets close with no sign of engagement. The hard part is not noticing one signal. The hard part is turning a messy set of signals into a useful next action.

The ai-customer-churn-predictor-python example shows one way to build that workflow with Telnyx AI Inference.

It is a small Flask app that accepts customer activity data, sends it to a Telnyx-hosted model through the chat-completions endpoint, and returns structured churn risk with recommended retention actions.

What the Example Builds

The app exposes four routes:

  • POST /predict - predict churn risk for one customer
  • POST /predict/batch - process up to 20 customers at once
  • GET /predictions - list recent in-memory predictions
  • GET /health - check app health

The current example uses Telnyx AI Inference through:

POST https://api.telnyx.com/v2/ai/chat/completions

The default model in .env.example is:

AI_MODEL=moonshotai/Kimi-K2.6

You can change that model later, but the sample keeps the flow simple: send a customer profile, ask for a constrained JSON response, parse the result, and return it to the caller.

Why Churn Prediction Is a Good AI App Pattern

A lot of AI examples stop at chat.

Churn prediction is more interesting because the model is not just producing prose. It is helping the app make a decision:

  • Is this customer high, medium, or low risk?
  • What signals contributed to that assessment?
  • How urgent is the issue?
  • What should the customer success team do next?
  • How much revenue may be at risk?

That shape matters because it is close to how real products work. A product does not need a paragraph about churn. It needs structured output that can be routed into a dashboard, CRM, workflow queue, alert, or customer success playbook.

Running the Example

Clone the examples repo and enter the churn predictor folder:

git clone https://github.com/team-telnyx/telnyx-code-examples.git
cd telnyx-code-examples/ai-customer-churn-predictor-python

Create your environment file:

cp .env.example .env

Set your Telnyx API key:

TELNYX_API_KEY=your_telnyx_api_key
AI_MODEL=moonshotai/Kimi-K2.6
HOST=127.0.0.1

Install dependencies and run the app:

pip install -r requirements.txt
python app.py

The app starts locally on http://localhost:5000.

Predict Churn for One Customer

Send customer activity signals to /predict:

curl -X POST http://localhost:5000/predict \
  -H "Content-Type: application/json" \
  -d '{
    "customer_id": "CUST-123",
    "call_volumes": [120, 105, 80, 55],
    "message_volumes": [450, 420, 300, 190],
    "support_tickets": 6,
    "account_age_months": 18,
    "renewal_days": 21,
    "last_login_days": 14,
    "payment_issues": 1
  }'

The prompt asks the model to return JSON with this shape:

{
  "churn_risk": "high",
  "probability": 0.82,
  "risk_factors": [
    "Call volume declined over the last four months",
    "Support ticket volume is elevated",
    "Renewal date is approaching"
  ],
  "recommended_actions": [
    "Schedule an account review this week",
    "Investigate support ticket themes",
    "Offer a renewal success plan"
  ],
  "urgency": "this_week",
  "estimated_revenue_at_risk": "unknown",
  "customer_id": "CUST-123",
  "predicted_at": "2026-06-29T19:00:00Z"
}

The exact output depends on the model response and the data you send, but the point is the same: the app turns scattered activity signals into a structured retention workflow.

The Telnyx AI Inference Call

The example uses a small helper around Telnyx AI Inference:

def call_inference(messages, max_tokens=1500):
    resp = requests.post(
        INFERENCE_URL,
        headers={
            "Authorization": f"Bearer {TELNYX_API_KEY}",
            "Content-Type": "application/json",
        },
        json={
            "model": AI_MODEL,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": 0.2,
        },
        timeout=15,
    )
    resp.raise_for_status()
    return resp.json()["choices"][0]["message"]["content"]

The system prompt tells the model to act like a customer success analyst and return only JSON. The app also includes a JSON extraction helper because real model output can still vary. If the response comes back wrapped in markdown fences, the helper strips them before parsing.

That is a small implementation detail, but it matters. AI apps should assume model output needs validation before it becomes application state.

Batch Prediction

The batch endpoint accepts up to 20 customers:

curl -X POST http://localhost:5000/predict/batch \
  -H "Content-Type: application/json" \
  -d '{
    "customers": [
      {
        "customer_id": "CUST-123",
        "call_volumes": [120, 105, 80, 55],
        "support_tickets": 6,
        "last_login_days": 14
      },
      {
        "customer_id": "CUST-456",
        "call_volumes": [80, 82, 85, 87],
        "support_tickets": 1,
        "last_login_days": 2
      }
    ]
  }'

The response includes the prediction results and a high_risk_count, which makes it easy to build a triage screen or scheduled workflow.

Making It Production-Ready

This sample keeps state in memory so the app is easy to understand. For production, you would likely add:

  • Persistent storage for predictions
  • Auth on the API routes
  • Real customer activity data from your product, CRM, or warehouse
  • Strict schema validation on model output
  • A queue for batch jobs
  • Alerting when high-value accounts become high risk
  • Human review before sending customer-facing actions

The repo is intentionally agent-readable. The README, API reference, guide, environment template, and app code are structured so coding agents can inspect the project and help extend it. You can ask an agent to add persistence, write tests, connect a CRM, or turn the batch endpoint into a scheduled job.

Frequently Asked Questions

No FAQs yet.

Resources

  • Code: https://github.com/team-telnyx/telnyx-code-examples/tree/main/ai-customer-churn-predictor-python
  • Telnyx AI skills and toolkits: https://github.com/team-telnyx/ai
  • Telnyx AI Inference docs: https://developers.telnyx.com/docs/inference
  • Chat Completions API: https://developers.telnyx.com/api/inference/chat-completions
  • Telnyx Portal: https://portal.telnyx.com/

Ready to build with low-latency voice AI?

Join developers building the future of real-time conversations