Introduction to OpenAI

Text Generation

Project 4 Personal Trainer

In this tutorial, you’ll create a command-line personal trainer application leveraging the OpenAI API and Python. You will:

  • Load real-world fitness data
  • Collect user health goals
  • Generate custom, actionable recommendations

Prerequisites

PackagePurposeInstallation Command
Python 3.xCore programming languageDownload
openaiOpenAI Python SDKpip3 install openai
pandasData manipulation and I/Opip3 install pandas
pip3 install openai pandas

Warning

Storing your API key in plaintext is insecure. Use environment variables or a secrets manager instead of hardcoding it in your script.

1. Setup and Imports

Create a file named personal_trainer.py and add:

import os
import pandas as pd
from openai import OpenAI

# Initialize the OpenAI client using an environment variable
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

2. Load Fitness Data

Load your CSV dataset containing sleep, health, and lifestyle metrics. Update the file path as needed:

# Load the fitness dataset
df = pd.read_csv("/path/to/Sleep_health_and_lifestyle_dataset.csv")

Note

Ensure the CSV file has columns like sleep_duration, diet_quality, and stress_level for best results.

3. Collect User Health Goals

Prompt the user to enter one or more goals. Type done to finish:

def get_user_goals():
    goals = []
    while True:
        goal = input("Enter a health goal (type 'done' when finished): ").strip()
        if goal.lower() == "done":
            break
        goals.append(goal)
    return goals

goals = get_user_goals()

4. Define the Trainer Function

This function builds a chat prompt from user goals and context, then calls the OpenAI chat completion API:

def trainer(goals, df):
    messages = []

    # Add user goals
    for goal in goals:
        messages.append({"role": "user", "content": goal})

    # System instructions
    messages.extend([
        {"role": "system", "content": "Provide concise, bullet-point recommendations."},
        {
            "role": "assistant",
            "content": (
                "You are a health expert advising an accountant. "
                "Be technical, specific, and offer actionable steps."
            )
        }
    ])

    # Call the GPT-4 model
    response = client.chat.completions.create(
        model="gpt-4",
        messages=messages,
        temperature=0.8
    )

    return response.choices[0].message.content

Warning

API calls may incur costs. Monitor your usage on the OpenAI dashboard.

5. Main Execution

Invoke the trainer function and display recommendations:

if __name__ == "__main__":
    recommendations = trainer(goals, df)
    print("\nPersonal Trainer Recommendations:\n")
    print(recommendations)

6. Example Run

$ python3 personal_trainer.py
Enter a health goal (type 'done' when finished): weight loss
Enter a health goal (type 'done' when finished): healthier diet
Enter a health goal (type 'done' when finished): stress reduction
Enter a health goal (type 'done' when finished): done

Personal Trainer Recommendations:

• Sleep Duration: Aim for 7–8 hours/night (current average: 6.2h)  
• Dietary Adjustments:
  – Reduce simple carbs by 20%  
  – Increase protein at breakfast  
• Exercise Plan:
  – 3× weekly circuit training sessions (30 min)  
  – 2× yoga or meditation sessions for stress control  
• Stress Management:
  – Implement 5-minute mindfulness breaks every 2 hours  
  – Track HRV trends; maintain ≥50 ms daily  

Watch Video

Watch video content

Previous
Project 3 AI Research Assistant