MuhammadSaad16's picture
Upload 112 files
971b4ea verified

Quickstart: Content Personalization API

Feature Branch: 005-content-personalize Created: 2025-12-14

Prerequisites

  • Backend server running (uvicorn app.main:app --reload)
  • At least one user registered in the database
  • OpenAI API key configured in .env

API Endpoint

POST /api/personalize
Content-Type: application/json

Request Format

{
  "content": "The educational content to personalize",
  "user_id": 1
}

Response Format

{
  "personalized_content": "Adapted content based on user profile",
  "adjustments_made": "Description of changes made"
}

Quick Test Examples

1. Personalize for a Beginner User

First, ensure user with ID 1 has software_level="beginner":

curl -X POST http://localhost:8000/api/personalize \
  -H "Content-Type: application/json" \
  -d '{
    "content": "A recursive function calls itself to solve smaller instances of the same problem. The base case terminates recursion.",
    "user_id": 1
  }'

Expected response: Content with added explanations, simpler terms, and examples.

2. Personalize for an Advanced User

Assuming user ID 2 has software_level="advanced":

curl -X POST http://localhost:8000/api/personalize \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Functions store data. Use = to assign values.",
    "user_id": 2
  }'

Expected response: Content with technical depth, no basic explanations.

3. Personalize Hardware Content for a Novice

User with hardware_level="none":

curl -X POST http://localhost:8000/api/personalize \
  -H "Content-Type: application/json" \
  -d '{
    "content": "GPIO pins allow the microcontroller to interface with external circuits. PWM signals control motor speed.",
    "user_id": 1
  }'

Expected response: Hardware concepts explained from scratch with analogies.


Error Handling

User Not Found (404)

curl -X POST http://localhost:8000/api/personalize \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Some content",
    "user_id": 99999
  }'

Response:

{
  "detail": "User not found"
}

Empty Content (400)

curl -X POST http://localhost:8000/api/personalize \
  -H "Content-Type: application/json" \
  -d '{
    "content": "",
    "user_id": 1
  }'

Response:

{
  "detail": [
    {
      "loc": ["body", "content"],
      "msg": "Content cannot be empty",
      "type": "value_error"
    }
  ]
}

Content Too Long (400)

# Content exceeding 50,000 characters
curl -X POST http://localhost:8000/api/personalize \
  -H "Content-Type: application/json" \
  -d '{
    "content": "'"$(python -c "print('x' * 60000)")"'",
    "user_id": 1
  }'

Response:

{
  "detail": [
    {
      "loc": ["body", "content"],
      "msg": "Content exceeds maximum length of 50000 characters",
      "type": "value_error"
    }
  ]
}

User Profile Fields Used

The personalization uses these fields from the user's profile:

Field Values Effect on Personalization
software_level beginner, intermediate, advanced Controls code/programming explanation depth
hardware_level none, basic, experienced Controls hardware concept explanation depth
learning_goals Free text Content emphasis and topic connections

Python Client Example

import requests

def personalize_content(content: str, user_id: int) -> dict:
    """Personalize content for a specific user."""
    response = requests.post(
        "http://localhost:8000/api/personalize",
        json={"content": content, "user_id": user_id}
    )
    response.raise_for_status()
    return response.json()

# Example usage
result = personalize_content(
    content="Variables store data in memory. The = operator assigns values.",
    user_id=1
)

print("Personalized Content:")
print(result["personalized_content"])
print("\nAdjustments Made:")
print(result["adjustments_made"])

Integration with Frontend

async function personalizeContent(content, userId) {
  const response = await fetch('/api/personalize', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ content, user_id: userId })
  });

  if (!response.ok) {
    throw new Error(`Personalization failed: ${response.statusText}`);
  }

  return response.json();
}

// Usage
const result = await personalizeContent(
  "A loop repeats code multiple times.",
  currentUserId
);
displayContent(result.personalized_content);

Troubleshooting

Issue Possible Cause Solution
503 Service Unavailable OpenAI API down or rate limited Check OpenAI status, verify API key
404 User Not Found Invalid user_id Verify user exists in database
Slow response (>15s) Long content or OpenAI latency Check content length, retry
Generic 500 error Server exception Check server logs for details