Introduction
In this tutorial, you'll learn how to build a simple AI-powered personalization system using OpenAI's API and Codex technology, similar to what Circles uses in the telecommunications industry. You'll create a basic recommendation engine that can suggest personalized services to users based on their behavior patterns. This hands-on project will teach you fundamental concepts of working with AI APIs and how to integrate them into real applications.
Prerequisites
Before starting this tutorial, you'll need:
- A basic understanding of Python programming
- An OpenAI API key (you can get one from OpenAI's website)
- Python 3.7 or higher installed on your computer
- Basic knowledge of how APIs work
Step-by-Step Instructions
Step 1: Set Up Your Development Environment
Install Required Packages
First, create a new Python project folder and install the necessary packages. Open your terminal or command prompt and run:
pip install openai python-dotenv
This installs the OpenAI Python library and python-dotenv, which helps manage your API keys securely.
Step 2: Create Your API Key Configuration
Set Up Environment Variables
Create a file named .env in your project directory and add your OpenAI API key:
OPENAI_API_KEY=your_actual_api_key_here
Never commit this file to version control. Add it to your .gitignore file to keep your API key secure.
Step 3: Initialize Your Python Project
Create the Main Script
Create a file called personalization_engine.py and start with the basic imports:
import openai
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure OpenAI API key
openai.api_key = os.getenv('OPENAI_API_KEY')
print('Personalization engine initialized successfully!')
This code loads your API key from the environment variable and sets up the OpenAI client. The environment variable approach keeps your API key secure.
Step 4: Create Sample User Data
Define User Profiles
Add sample user data to your script to simulate different user behaviors:
# Sample user data
users = [
{
'id': 1,
'name': 'Alice Johnson',
'usage_pattern': 'high_data',
'plan_type': 'basic',
'churn_risk': 'low'
},
{
'id': 2,
'name': 'Bob Smith',
'usage_pattern': 'high_voice',
'plan_type': 'premium',
'churn_risk': 'medium'
}
]
This sample data represents different user types that your AI system will analyze to make recommendations.
Step 5: Build the AI Recommendation Function
Create the Core Recommendation Logic
Add a function that uses OpenAI's API to generate personalized recommendations:
def generate_recommendations(user):
prompt = f"""
You are a telecommunications expert analyzing customer behavior.
Customer Profile:
Name: {user['name']}
Usage Pattern: {user['usage_pattern']}
Current Plan: {user['plan_type']}
Churn Risk: {user['churn_risk']}
Based on this information, recommend 2 specific services or plan upgrades that would benefit this customer.
Format your response as a simple list with bullet points.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful telecommunications consultant."},
{"role": "user", "content": prompt}
],
max_tokens=150,
temperature=0.7
)
return response.choices[0].message.content.strip()
except Exception as e:
return f"Error generating recommendations: {str(e)}"
This function sends a structured prompt to the OpenAI API with specific user information. The model analyzes the data and returns personalized recommendations, which is exactly what Circles does at scale.
Step 6: Implement the Main Execution Loop
Process All Users
Add the main execution logic to process all users and display their recommendations:
def main():
print("Starting personalization engine...")
for user in users:
print(f"\n--- Recommendations for {user['name']} ---")
recommendations = generate_recommendations(user)
print(recommendations)
print("\nPersonalization engine completed!")
# Run the main function
if __name__ == "__main__":
main()
This loop processes each user and displays personalized recommendations, simulating how Circles might handle thousands of users at once.
Step 7: Test Your Personalization Engine
Run Your Application
Execute your script by running:
python personalization_engine.py
You should see output showing personalized recommendations for each user based on their profile. The AI will suggest specific services or plan upgrades tailored to each customer's behavior.
Step 8: Enhance Your System with Codex
Integrate Code Generation
For a more advanced approach, you can use Codex to generate code based on natural language prompts. Add this function to your script:
def generate_code_snippet(description):
prompt = f"""
Generate Python code that would implement the following feature:
{description}
Return only the Python code without any explanations or markdown formatting.
"""
try:
response = openai.Completion.create(
engine="code-davinci-002",
prompt=prompt,
max_tokens=200,
temperature=0.5,
stop="\n\n"
)
return response.choices[0].text.strip()
except Exception as e:
return f"Error generating code: {str(e)}"
# Example usage
print("\n--- Code Generation Example ---")
code = generate_code_snippet("a function that calculates customer lifetime value based on usage data")
print(code)
This demonstrates how Codex can be used to automatically generate code from natural language descriptions, which is part of what makes Circles' system AI-native.
Summary
In this tutorial, you've built a basic AI-powered personalization system that simulates how telecommunications companies like Circles use OpenAI technology. You learned how to:
- Set up an OpenAI API environment with secure key management
- Use the ChatCompletion API to generate personalized recommendations
- Structure prompts that provide context for AI models
- Implement a simple user recommendation engine
- Use Codex to generate code from natural language descriptions
This foundation demonstrates the core concepts behind Circles' success in increasing ARPU and reducing churn through AI-native experiences. As you continue learning, you can expand this system to handle more complex user data, integrate with real databases, and scale to support thousands of users.



