> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Project 4 Personal Trainer

> Create a command-line personal trainer application using Python and the OpenAI API to provide custom fitness recommendations based on user goals and data.

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

| Package    | Purpose                   | Installation Command                          |
| ---------- | ------------------------- | --------------------------------------------- |
| Python 3.x | Core programming language | [Download](https://www.python.org/downloads/) |
| openai     | OpenAI Python SDK         | `pip3 install openai`                         |
| pandas     | Data manipulation and I/O | `pip3 install pandas`                         |

```bash theme={null}
pip3 install openai pandas
```

<Callout icon="triangle-alert" color="#FF6B6B">
  Storing your API key in plaintext is insecure. Use environment variables or a secrets manager instead of hardcoding it in your script.
</Callout>

## 1. Setup and Imports

Create a file named `personal_trainer.py` and add:

```python theme={null}
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:

```python theme={null}
# Load the fitness dataset
df = pd.read_csv("/path/to/Sleep_health_and_lifestyle_dataset.csv")
```

<Callout icon="lightbulb" color="#1CB2FE">
  Ensure the CSV file has columns like `sleep_duration`, `diet_quality`, and `stress_level` for best results.
</Callout>

## 3. Collect User Health Goals

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

```python theme={null}
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:

```python theme={null}
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
```

<Callout icon="triangle-alert" color="#FF6B6B">
  API calls may incur costs. Monitor your usage on the [OpenAI dashboard][openai-dashboard].
</Callout>

## 5. Main Execution

Invoke the trainer function and display recommendations:

```python theme={null}
if __name__ == "__main__":
    recommendations = trainer(goals, df)
    print("\nPersonal Trainer Recommendations:\n")
    print(recommendations)
```

## 6. Example Run

```bash theme={null}
$ 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  
```

## Links and References

* [OpenAI Python SDK][openai-sdk]
* [pandas Documentation][pandas-docs]
* [OpenAI Dashboard][openai-dashboard]

[openai-sdk]: https://pypi.org/project/openai/

[pandas-docs]: https://pandas.pydata.org/

[openai-dashboard]: https://platform.openai.com/account/usage

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/introduction-to-openai/module/b6b7bec7-ed21-47d5-afbb-663df59f5e97/lesson/63b8c65f-2957-476f-bc52-f8e932bc166d" />
</CardGroup>
