Skip to main content

Workout Planner with OpenAI ChatGPT API

· 7 min read
Deniz Colak

In today's world, where people are becoming more health-conscious, workout planners are becoming increasingly popular. It also can be difficult to find the time and motivation to work out. That's where an AI-powered workout planner comes in. By leveraging the power of artificial intelligence, we can create a workout planner that can tailor workout routines to individual needs, preferences, and goals. In this blog post, we will learn how to build an AI-powered workout planner using Flutter for the frontend, Altogic for the backend, and OpenAI's ChatGPT API for the AI.

New app
AI workout planner - Workout Planner Flutter App

Building the Frontend with Flutter

Flutter is a popular open-source framework for building mobile applications. It uses a single codebase to create apps for both Android and iOS platforms. Let's look at the steps involved in building the frontend for our AI-powered workout planner.

Step 1: Set up the development environment

The first step is to set up the development environment. Follow the instructions in the Flutter documentation to install and set up the Flutter SDK on your system.

After setting up your flutter development environment, you can get the AI-Powered Workout Planner repo from Github

Github Repository: https://github.com/zinedkaloc/ai-workout-planner

You can clone the repo by running the following command in your terminal:

$ git clone [email protected]:zinedkaloc/ai-workout-planner.git

Switch to the app directory by running the following command:

$ cd ai-workout-planner

Once you have the repo, open it in your code editor of choice. Install the necessary dependencies by running the following command in your terminal:

$ flutter pub get
info

To get started, you will need a endpoint URL that will be used to send requests to the OpenAI ChatGPT API. You can get the endpoint URL by following the steps in the next section.

Building the Backend

Altogic is a backend as a service platform that allows you to build and deploy serverless applications with the speed of no-code or flexibility of code. It provides both of the worlds in a single platform. In this tutorial, we will be using the no-code service builder to build our backend.

If you don't have an Altogic account, you can create one for free at https://altogic.com. Once you have an account, you can create a new project by clicking on the "New Project" button on the workspace.

New app
Creating a backend application for the AI workout planner

Open Models view of Altogic Designer to create a new model. Click on the + New button and select Model from JSON. Copy and paste the following JSON to the editor and click on the Next button.

workout.json
{  "workoutDuration": 7,  "workoutFrequency": "text",  "fitnessLevel": "text",  "fitnessGoal": "text",  "workoutType": "text"}

Watch the video below to learn how to create a new project, create a model from JSON in Altogic Designer and learn how to create a new service to send request to the OpenAI ChatGPT API.

You will also need following JSON to set Messages as a prompt with parameters in Altogic Designer.

[
{
"role": "user",
"content": {{CONCAT("Create a personalized workout plan to help the user achieve their fitness goals. The user's fitness goal is ", input.body.fitnessGoal, " and they prefer ", input.body.workoutType, " workouts. They have ", input.body.fitnessLevel , " fitness level and prefer to workout ", input.body.workoutFrequency, " . Please provide a detailed workout plan for ", input.body.workoutDuration, " days, including suggested exercises, reps, and sets", "Format your response using HTML. Use headings, subheadings, bullet points, and bold to organize the information.")}}
}
]

In the above JSON, we are concatenating the user's input with the CONCAT function. The CONCAT function takes two or more strings as arguments and returns a single string. You can learn more about the Altogic documentation.

Now that we have created the service, we can copy the endpoint URL and use it in our Flutter app. Visit the Endpoints page and click on the Copy button next to the endpoint URL to copy the endpoint URL.

Overview of the service
Endpoint URL

Connecting the Frontend and Backend

Now that we have created the frontend and backend, we can connect them. To do this, we will be using the endpoint URL that we copied in the previous step. Open the work_out_plan.dart file in the lib directory and paste the URL that you copied in the previous step.

try {      final response = await http.post(        Uri.parse(            'https://c1-europe.altogic.com/e:6413153a59f30b2fd0badbd5/workout'),            body: {              ...            })}

Now that we have the endpoint URL, we can run the frontend app by running the following command in your terminal:

$ flutter run

Once the app is running, you can visit it in your browser at http://localhost:63721/ if you are running it on the browser.

AI Workout planner app
AI Workout Planner App

The app is now ready to use. You can start by selecting your fitness level, fitness goal, workout type, workout frequency, and workout duration. Once you have selected all the options, you can click on the Submit button to generate the workout plan.

AI Workout planner app -  Workout Plan
AI Workout Planner App - Workout Plan

Here is the parameters and handleSubmit function that we used to generate the workout plan:

Future<void> submitForm() async {    // Show a loading indicator    setState(() {      isLoading = true;      isSubmitted = false;    });    try {      // Send the user's preferences to a backend server or API      // You can use a package like http or dio to make API calls      // Replace the URL with your backend endpoint      final response = await http.post(        Uri.parse(            'https://c1-europe.altogic.com/e:6413153a59f30b2fd0badbd5/fitness'),        body: {          'fitnessGoal': fitnessGoal,          'workoutType': workoutType,          'fitnessLevel': fitnessLevel,          'workoutFrequency': workoutFrequency,          'workoutDuration': workoutDuration.toString(),        },      );      // Parse the response and create a WorkoutPlan object      final workoutPlan = WorkoutPlan.fromJson(jsonDecode(response.body));      // Show the workout plan on the screen      setState(() {        isLoading = false;        isSubmitted = true;        this.workoutPlan = workoutPlan;      });    } catch (e) {      // Handle errors      print('Error: $e');      setState(() {        isLoading = false;        isSubmitted = false;        workoutPlan = null;      });    }  }

In the handleSubmit function, we are using the http package to make a POST request to the endpoint URL that we have created before in the Altogic with the workout as the request body. In that endpoint, we are using the Create Chat Completion node to generate the workout plan so the response from the endpoint is a JSON object that contains the workout plan.

With these steps, we have created an AI workout planner app that can generate a workout plan based on user input. With further development, this app could be expanded to include additional features such as creating a workout plan for a group of people, creating a workout plan for a specific body part, and more.

Overall, integrating OpenAI's Chat Completion(ChatGPT) API into a Flutter app is a strong way to build an AI-powered workout planner mobile app that can help people achieve their fitness goals and generate a workout plan based on their preferences.

Resources

Source Code: The source code for the AI workout planner app can be found Github

Demo: Demo of the AI workout planner app can be found Netlify.

Conclusion

In this blog post, we learned how to build a workout planner using Flutter and Altogic, and integrating the two parts using API. We looked at the steps involved in building the frontend and backend separately and then integrating them to create a fully functional app. We hope this blog post was helpful to you and that you were able to successfully build your own workout planner app.

If you have any questions, please feel free to reach out to us at community forum or discord channel.