Tutorial Factory

Powered by Telnyx

Dev Docs Low Latency Club GitHub Log in
AI Assistants Python Flask

List AI Assistants with Python and Flask

Overview

Build a production-ready Flask endpoint that lists all AI Assistants on your Telnyx account using the Telnyx Python SDK. This tutorial covers the client-based initialization pattern, proper serialization of SDK response objects, and comprehensive error handling for a reliable API layer over Telnyx AI Assistants.

Prerequisites

  • Python 3.8 or higher.
  • A Telnyx account with an active API key from the Telnyx Portal.
  • At least one AI Assistant created in your Telnyx account (optional, but useful for verifying results).
  • pip (Python package manager).

Step 1: Setup

Install the required dependencies:

pip install telnyx flask python-dotenv

Create a project directory and navigate into it:

mkdir telnyx-list-assistants
cd telnyx-list-assistants

Step 2: Configuration

Create a .env file in your project root to store your API key securely:

TELNYX_API_KEY=YOUR_API_KEY_HERE

Replace YOUR_API_KEY_HERE with your actual API key from the Telnyx Portal. Never commit this file to version control — add .env to your .gitignore.

Step 3: Implementation

Create app.py and initialize the Telnyx client. Define a helper function that fetches assistants and returns a plain list of dictionaries — SDK response objects are not JSON-serializable, so you must extract fields explicitly:

import os
import telnyx
from dotenv import load_dotenv

load_dotenv()

# Initialize client with the new SDK pattern
client = telnyx.Telnyx(api_key=os.getenv("TELNYX_API_KEY"))


def fetch_assistants() -> list[dict]:
    """Retrieve all AI Assistants and return JSON-serializable data."""
    response = client.ai_assistants.list()

    # SDK objects are NOT JSON-serializable — always unpack to plain dicts
    return [
        {
            "id": a.id,
            "name": a.name,
            "model": a.model,
            "enabled_features": a.enabled_features,
            "created_at": a.created_at,
        }
        for a in response.data
    ]

The helper function stays free of exception handling — errors propagate up to the route handler where they belong.

Step 4: Testing

Add the Flask route with error handling that maps each Telnyx exception to the correct HTTP status code:

from flask import Flask, jsonify

app = Flask(__name__)


@app.route("/assistants", methods=["GET"])
def list_assistants():
    """HTTP endpoint to list all AI Assistants."""
    try:
        assistants = fetch_assistants()
        return jsonify({"assistants": assistants, "count": len(assistants)}), 200

    except telnyx.AuthenticationError:
        return jsonify({"error": "Invalid API key"}), 401
    except telnyx.RateLimitError:
        return jsonify({"error": "Rate limit exceeded. Please slow down."}), 429
    except telnyx.APIStatusError as e:
        return jsonify({"error": str(e), "status_code": e.status_code}), e.status_code
    except telnyx.APIConnectionError:
        return jsonify({"error": "Network error connecting to Telnyx"}), 503


if __name__ == "__main__":
    app.run(debug=True, port=5000)

Start the server:

python app.py

Test the endpoint using curl:

curl http://localhost:5000/assistants

Expected response:

{
  "assistants": [
    {
      "id": "a1b2c3d4-5678-90ab-cdef-1234567890ab",
      "name": "Customer Support Bot",
      "model": "meta-llama/Meta-Llama-3.1-70B-Instruct",
      "enabled_features": ["telephony", "messaging"],
      "created_at": "2026-04-20T14:30:00Z"
    },
    {
      "id": "e5f6a7b8-9012-34cd-ef56-7890abcdef12",
      "name": "Sales Qualifier",
      "model": "meta-llama/Meta-Llama-3.1-70B-Instruct",
      "enabled_features": ["telephony"],
      "created_at": "2026-04-22T09:15:00Z"
    }
  ],
  "count": 2
}

If you have no assistants yet, the response will return an empty list with "count": 0.

Complete Code

#!/usr/bin/env python3
"""Production-ready Flask endpoint for listing Telnyx AI Assistants."""

import os
import telnyx
from dotenv import load_dotenv
from flask import Flask, jsonify

load_dotenv()

app = Flask(__name__)

# Initialize client with the new SDK pattern
client = telnyx.Telnyx(api_key=os.getenv("TELNYX_API_KEY"))


def fetch_assistants() -> list[dict]:
    """Retrieve all AI Assistants and return JSON-serializable data."""
    response = client.ai_assistants.list()

    # SDK objects are NOT JSON-serializable — always unpack to plain dicts
    return [
        {
            "id": a.id,
            "name": a.name,
            "model": a.model,
            "enabled_features": a.enabled_features,
            "created_at": a.created_at,
        }
        for a in response.data
    ]


@app.route("/assistants", methods=["GET"])
def list_assistants():
    """HTTP endpoint to list all AI Assistants."""
    try:
        assistants = fetch_assistants()
        return jsonify({"assistants": assistants, "count": len(assistants)}), 200

    except telnyx.AuthenticationError:
        return jsonify({"error": "Invalid API key"}), 401
    except telnyx.RateLimitError:
        return jsonify({"error": "Rate limit exceeded. Please slow down."}), 429
    except telnyx.APIStatusError as e:
        return jsonify({"error": str(e), "status_code": e.status_code}), e.status_code
    except telnyx.APIConnectionError:
        return jsonify({"error": "Network error connecting to Telnyx"}), 503


if __name__ == "__main__":
    app.run(debug=True, port=5000)

Troubleshooting

Issue Problem Solution
Authentication Error (401) The endpoint returns {"error": "Invalid API key"} with HTTP 401. Verify your TELNYX_API_KEY in the .env file matches the key shown in the Telnyx Portal. Ensure there are no trailing spaces or quotes around the value. If the key was recently regenerated, update your .env file and restart the Flask server.
Empty List Returned The response shows {"assistants": [], "count": 0} even though you expect assistants. Confirm you have created at least one AI Assistant in the Telnyx Portal under the same account tied to your API key. API keys are scoped to a single organization — assistants created under a different organization will not appear.
Connection Error (503) The endpoint returns {"error": "Network error connecting to Telnyx"} with HTTP 503. Check your network connectivity and ensure outbound HTTPS traffic to api.telnyx.com is not blocked by a firewall or proxy. If you are behind a corporate network, configure your proxy settings or try from a different network. Retry after a few seconds — transient DNS or TLS issues can cause this.

Next Steps