Ready to elevate your fitness journey? AI has got you covered! In this blog, we’ll dive into building a FitnessAI app using CrewAI, Langchain, and Streamlit. This will deliver personalized exercise recommendations tailored to your goals, enhanced by real-time data scraping to keep you on track. Plus, you’ll learn how to leverage CrewAI to effortlessly create amazing agents. Excited to get started? Let’s get started.
What is Langchain?
LangChain is a framework designed for developing applications powered by language models. It helps integrate language models with external tools, manage memory, handle chains of logic, and build complex workflows, making it easier to create sophisticated, multi-step AI-driven processes.
Langchain provides many AI functionalities to develop complex AI pipelines. Lanchain is also very flexible in terms of LLMs, so you can also run your favorite LLM other than ChatGPT in the Langchain.
What is CrewAI?
CrewAI is a framework designed for orchestrating AI agents to work together much like a well-coordinated crew. It enables agents to assume specific roles, share goals, and collaborate on tasks to achieve complex objectives.
CrewAI also enables integration with Langchain. Thus you can also use tools, and functions from the Langchain to leverage your crew.
FitnessAI: Let’s get started
First of all, let’s import all the required libraries that will be used in this project. For real-time scraping, We will use SerpAPI to scrape websites. It will require an API key. So if you don’t have it already go to https://serpapi.com/ and create one.
After getting APIs of ChatGPT and SerpAPI, store then into .env file.
OPENAI_MODEL_NAME = 'gpt-3.5-turbo' OPENAI_API_KEY = "YOUR_OPENAI_KEY" SERPER_API_KEY= "YOUR_SERPER_API_KEY"
from crewai_tools import ( ScrapeWebsiteTool, SerperDevTool, ) from crewai import Agent, Task, Crew from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field from langchain_openai import ChatOpenAI
So first we are going to make a crew. To make a Crew we have to define Agents and Tasks.
Let’s start with Agents. Agents are assigned specific tasks, make decisions, and collaborate with other agents. They require three key arguments—Role, Goal, and Backstory. These provide direction for the agent to perform a specific task, making our job much easier.
In our project, we are going to develop two agents:
- Fitness Coach Agent As the name suggests, this agent will scrape the internet based on the user’s input and suggest exercises that align with the user’s goals.
- Content Writer Agent This agent will take the text fetched by the fitness coach agent and format it into a proper and consistent format.
fitness_coach_agent=Agent( role='Fitness coach', goal="Make sure to give clear and effective" "list of exercises guide and repetitions that align with client's goals" "If the client's requirements are unrealistic, then" "don't give false answers.", verbose=True, backstory=( "As an experienced Fitness coach, you have all the knowledge" "about all types of exercises. You help " "clients by suggesting the list of exercises that " "aligns with their fitness goals." ) ) content_writer_agent=Agent( role="Professional content writer", goal="Restructure the given text that aligns with proper format.", backstory="You are professional content writes, who writes " "articles about fitness." )
Now, we will define tasks for these agents. Similar to agents, tasks also have three main arguments: description, expected output, and agents. We will create two tasks, one for each agent.
fitness_task = Task( description=( "Suggest fitness exercises " " for {main_goal} in {expected_time} time at {location}." " If required, use the tools to give brief answers to exercises." ), expected_output=( "A structured list of names of exercises, with steps to do it." " Also include the repetitions of a particular exercise." ), agent=fitness_coach_agent, tools=[scrape_tool,search_tool] ) # Task for Researcher Agent: Extract Job Requirements content_writer_task = Task( description=( "Give well-written fitness exercises with description and repetitions" "related article with focused on {main_goal} at {location} for {expected_time} with {equipment} " ), expected_output=( "A well-written blog post in markdown format"), agent=content_writer_agent )
Now let’s create a crew and test it out.
fitness_coach_crew = Crew( agents=[fitness_coach_agent,content_writer_agent], tasks=[fitness_task,content_writer_task], verbose=True ) ##Input variables that are defined in Agents and Tasks. crew_variables={'main_goal': 'lose fat', 'expected_time': '3 months', 'location': 'at home', 'equipment': 'with dumbbells'} result = fitness_coach_crew.kickoff(inputs=output)
Here is your 3-month plan to lose fat with the Dumbbell at home.
Not bad! You can see that the output aligns with our input goal. We’re halfway there.
Now, no one wants to manually input parameters from the front end every time to trigger the crew! That’s why we’re going to leverage the tagging functionality of Langchain. This will allow us to extract the parameters directly from the input prompt.
#defining Pydantic class for the Langchain tagging class Fitness(BaseModel): main_goal: str = Field(description="The fitness goal or to achive or focused body part to improve(i.e. Chest,Abs,etc.). If not provided set it to `overall body` ") expected_time: str = Field( description="The provided exptected time. If not provided set it to `no duration`" ) location: str = Field(description="The location to do fitness excercises. If the location is not provided then set it to `any location`") equipment: str = Field(description="The equipement to use for excercise.If the equipment is not provided then set it to `any gym_equipments`") def extract_tags(user_input:str) -> dict: tagging_prompt = ChatPromptTemplate.from_template( """ Extract the desired information from the following passage. Only extract the properties mentioned in the 'Classification' function. Passage: {input} """ ) # LLM llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo").with_structured_output(Fitness) # You can pass different model tagging_chain = tagging_prompt | llm output=tagging_chain.invoke({"input": user_input}) return output.dict() #testing of extract_tags user_tags=extract_tags("I want to lose fat at home with dumbbells. Give me some exercises with the plan of 3 months.") print(user_tags) ### OUTPUT {'main_goal': 'lose fat', 'expected_time': '3 months', 'location': 'at home', 'equipment': 'with dumbbells'}
And voilà! You’ve now built the pipeline to extract tags from plain text and created the agents to process those tags into a fitness plan. Let’s now combine these two pipelines into one and connect them with Streamlit so that the functionalities can be accessed through the UI.
I have wrapped all the Agents, Tasks, and crew in one function called execute_crew to compact the code.
import streamlit as st from utils import utils st.title("Fitness AI") def main(): #Get the question from the user user_input=st.text_input("Type your fitness goal",placeholder="Ex. I want to lose belly fat. Suggest me some exercises with the plan of 3 months.") submit=st.button("Submit") if submit: #get the tags from the user_input user_tags=utils.extract_tags(user_input) #run the Crew output=utils.execute_crew(user_tags) st.markdown(output) # Run the app if __name__ == "__main__": main()
Now in the terminal, start the app using:
streamlit run main.py
Open the App on the browser and type any query related to fitness and will give the plan according to that.
it will give all the information about exercises. Now it’s your turn to ask any question related to fitness!
I’ve added the source code here try it on your own.
Also Read: How to make an appointment bot using Langchain and Google Sheets in Python easily