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 retrieves and displays AI assistants using the Telnyx Python SDK. This tutorial demonstrates the new client-based initialization pattern, proper pagination handling, and secure credential management for AI assistant management systems.

Prerequisites

  • Python 3.8 or higher.
  • A Telnyx account with an active API key from the Telnyx Portal.
  • 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-ai-assistant-list
cd telnyx-ai-assistant-list

Step 2: Configuration

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

TELNYX_API_KEY=YOUR_API_KEY_HERE

Replace YOUR_API_KEY_HERE with your actual API key from the Telnyx Portal.

Step 3: Implementation

Create app.py and initialize the Telnyx client using the new pattern. Define a helper function to handle assistant listing with proper pagination:

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 list_assistants(page_size: int = 20, page_number: int = 1) -> dict:
    """List AI assistants with pagination and return JSON-serializable response data."""
    # Use client.ai_assistants.list() — NOT client.ai_assistants.list()
    response = client.ai_assistants.list(
        page_size=page_size,
        page_number=page_number
    )

    # Extract serializable data — SDK objects are NOT JSON-serializable
    assistants = [
        {
            "id": assistant.id,
            "name": assistant.name,
            "model": assistant.model,
            "instructions": assistant.instructions,
            "enabled_features": assistant.enabled_features,
            "created_at": assistant.created_at,
        }
        for assistant in response.data
    ]

    return {
        "assistants": assistants,
        "total_count": len(response.data),
        "page_number": page_number,
        "page_size": page_size,
    }

Step 4: Testing

Add the Flask route with comprehensive error handling for production resilience:

from flask import Flask, jsonify, request

app = Flask(__name__)


@app.route("/assistants", methods=["GET"])
def list_assistants_endpoint():
    """HTTP endpoint to list AI assistants with pagination."""
    # Parse query parameters for pagination
    page_size = request.args.get("page_size", 20, type=int)
    page_number = request.args.get("page_number", 1, type=int)

    # Validate pagination parameters
    if page_size < 1 or page_size > 100:
        return jsonify({"error": "page_size must be between 1 and 100"}), 400

    if page_number < 1:
        return jsonify({"error": "page_number must be greater than 0"}), 400

    try:
        result = list_assistants(page_size, page_number)
        return jsonify(result), 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

Test with pagination parameters:

curl "http://localhost:5000/assistants?page_size=10&page_number=1"

Expected response:

{
  "assistants": [
    {
      "id": "01234567-89ab-cdef-0123-456789abcdef",
      "name": "Customer Support Assistant",
      "model": "meta-llama/Meta-Llama-3.1-70B-Instruct",
      "instructions": "You are a helpful customer support agent...",
      "enabled_features": ["telephony", "messaging"],
      "created_at": "2024-01-15T10:30:00Z"
    }
  ],
  "total_count": 1,
  "page_number": 1,
  "page_size": 20
}

Complete Code

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

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

load_dotenv()

app = Flask(__name__)

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


def list_assistants(page_size: int = 20, page_number: int = 1) -> dict:
    """List AI assistants with pagination and return JSON-serializable response data."""
    # Use client.ai_assistants.list() — NOT client.ai_assistants.list()
    response = client.ai_assistants.list(
        page_size=page_size,
        page_number=page_number
    )

    # Extract serializable data — SDK objects are NOT JSON-serializable
    assistants = [
        {
            "id": assistant.id,
            "name": assistant.name,
            "model": assistant.model,
            "instructions": assistant.instructions,
            "enabled_features": assistant.enabled_features,
            "created_at": assistant.created_at,
        }
        for assistant in response.data
    ]

    return {
        "assistants": assistants,
        "total_count": len(response.data),
        "page_number": page_number,
        "page_size": page_size,
    }


@app.route("/assistants", methods=["GET"])
def list_assistants_endpoint():
    """HTTP endpoint to list AI assistants with pagination."""
    # Parse query parameters for pagination
    page_size = request.args.get("page_size", 20, type=int)
    page_number = request.args.get("page_number", 1, type=int)

    # Validate pagination parameters
    if page_size < 1 or page_size > 100:
        return jsonify({"error": "page_size must be between 1 and 100"}), 400

    if page_number < 1:
        return jsonify({"error": "page_number must be greater than 0"}), 400

    try:
        result = list_assistants(page_size, page_number)
        return jsonify(result), 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. If the key was regenerated recently, update your environment file and restart the Flask server.
Empty Assistant List The endpoint returns an empty assistants array even though you have created assistants in the portal. Confirm you're using the correct API key that has access to your assistants. Check that your assistants were created successfully by logging into the Telnyx Portal. Verify the pagination parameters aren't skipping your data by testing with page_number=1.
Pagination Parameter Validation Error You receive a 400 error about invalid page_size or page_number values. Ensure page_size is between 1 and 100, and page_number is greater than 0. Check your query string format: ?page_size=10&page_number=1. Remove any extra characters or spaces in the URL parameters.

Next Steps