亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Table of contents
Why Use Langchain?
Prerequisites
How to Build Your Fitness Coach?
Core Dependencies
SerperSearchTool Class
UserDataTracker Class
Langchain Agent Configuration
Gradio Chatbot Logic
User Interface
Use Cases for Langchain
Conclusion
Home Technology peripherals AI Build a LangChain Fitness Coach: Your AI Personal Trainer

Build a LangChain Fitness Coach: Your AI Personal Trainer

Jul 05, 2025 am 09:06 AM

Many individuals hit the gym with passion and believe they are on the right path to achieving their fitness goals. But the results aren’t there due to poor diet planning and a lack of direction. Hiring a personal trainer along with an expensive gym stack isn’t always an option. That is why I have created this blog post to show you how to build your fitness coach using the power of LangChain. With this, you can now get workout and diet advice customized to your goals with minimal cost. Let’s get started with taking some amazing tech and turning it into your fitness co-pilot!

Table of contents

  • Why Use Langchain?
    • Prerequisites
  • How to Build Your Fitness Coach?
    • Core Dependencies?
    • SerperSearchTool Class
    • UserDataTracker Class
    • Langchain Agent Configuration
    • Gradio Chatbot Logic
    • User Interface
    • Use Cases for Langchain
  • Conclusion

Why Use Langchain?

Langchain enables you to do much more when building advanced AI applications by combining large language models (LLMs) with tools, data sources, and memory. Instead of invoking the LLM with a plain text prompt, you can create agents that invoke functions, query information, and manage conversations with state. For a fitness coach, Langchain allows you to combine LLM intelligence with custom logic – for example, create workout suggestions, track progress, and get health data – so you can be a smarter interactive coach without having to figure that all out yourself.

Prerequisites

To create your fitness coach using LangChain, you’ll need:

  • An OpenAI API key to access language models
  • A key for the SerpAPI service to use the web search
  • Basic knowledge of Python

That’s all, you are now ready to get started.

How to Build Your Fitness Coach?

In this section, I will demonstrate how to make your fitness coach using a Langchain agent. Ensure you have everything prepared according to the prerequisites. I will walk you through the step-by-step process of building the solution and explain the role each step plays in achieving the outcome.

FitCoach AI is a conversational fitness coach that collects user data consistently and generates personalized workout and diet plans using LangChain agents with OpenAI.

Core Dependencies

To install all the libraries required for building the fitness agent, run the following command in your command line:

pip install gradio langchain openai serper-dev python-doten

Once all the dependencies are in place, we’d start by importing all the relevant modules for the task:

import os
import gradio as gr
import traceback
import datetime
from typing import List, Tuple, Optional

from langchain_openai import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.agents import initialize_agent, AgentType
from langchain.tools import BaseTool
import json
import requests
import dotenv

# Load environment variables
dotenv.load_dotenv()

SerperSearchTool Class

Functionality: Provides the ability to have real-time web search capabilities for up-to-date fitness/nutrition information.

Main features:

  • Integrates with the Serper API to get Google search results
  • Returns the top 5 formatted search results that include the title, snippet, and URL
  • Has acceptable failure modes with timeout protection
  • Supports both sync and async
# ----------- SERPER SEARCH TOOL ------------

class SerperSearchTool(BaseTool):
    name: str = "search_web"
    description: str = "Searches the web for real-time information and returns structured results"

    def _run(self, query: str) -> str:
        """Search the web using Serper API"""
        try:
            api_key = os.getenv("SERPER_API_KEY")
            if not api_key:
                return "Error: SERPER_API_KEY not found in environment variables"

            url = "https://google.serper.dev/search"
            payload = json.dumps({"q": query})
            headers = {
                'X-API-KEY': api_key,
                'Content-Type': 'application/json'
            }

            response = requests.post(url, headers=headers, data=payload, timeout=10)
            response.raise_for_status()
            search_results = response.json()

            # Extract and format organic results
            results = []
            if 'organic' in search_results:
                for item in search_results['organic'][:5]:  # Limit to top 5 results
                    results.append({
                        "title": item.get('title', ''),
                        "link": item.get('link', ''),
                        "snippet": item.get('snippet', '')
                    })

            # Format results in a readable way
            if results:
                formatted_results = "Search Results:\n\n"
                for i, result in enumerate(results, 1):
                    formatted_results  = f"{i}. {result['title']}\n"
                    formatted_results  = f"   {result['snippet']}\n"
                    formatted_results  = f"   URL: {result['link']}\n\n"
                return formatted_results
            else:
                return "No search results found."

        except requests.exceptions.RequestException as e:
            return f"Error performing search - Network issue: {str(e)}"
        except Exception as e:
            return f"Error performing search: {str(e)}"

    async def _arun(self, query: str) -> str:
        """Async version of search"""
        return self._run(query)

UserDataTracker Class

Functionality: Get all necessary information before creating any fitness plans

Required Data Fields (in order):<br><br>Fitness goal (weight loss, muscle gain, etc.)<br>Age (in range 10-100 validation)<br>Gender (male/female/other)<br>Weight (in units, - kg/lbs)<br>Height (in cm or feet/inches)<br>Activity Level (5 predefined levels)<br>Diet Preferences (vegetarian, vegan, etc.)<br>Diet Restrictions/allergy<br>Workout-Preferencing & limitations

Main Features:

  • Field Validation: Each input will be validated with custom validation functions.
  • Sequential Flow: No one can skip ahead.
  • Error Handling: Provide specific error messages for invalid inputs.
# ----------- USER DATA TRACKER CLASS ------------

class UserDataTracker:
    def __init__(self):
        self.data = {}
        # Define required fields with their validation functions and question prompts
        self.required_fields = {
            'fitness_goal': {
                'question': "What is your primary fitness goal? (e.g., weight loss, muscle gain, general fitness)",
                'validate': self._validate_fitness_goal
            },
            'age': {
                'question': "How old are you? (Must be between 10-100)",
                'validate': self._validate_age
            },
            'gender': {
                'question': "What is your gender? (male/female/other)",
                'validate': self._validate_gender
            },
            'weight': {
                'question': "What is your current weight? (e.g., 150 lbs or 68 kg)",
                'validate': self._validate_weight
            },
            'height': {
                'question': "What is your height? (e.g., 5'10\" or 178 cm)",
                'validate': self._validate_height
            },
            'activity_level': {
                'question': "What is your activity level? (sedentary, lightly active, moderately active, very active, extremely active)",
                'validate': self._validate_activity_level
            },
            'dietary_preferences': {
                'question': "Do you follow any specific diet? (e.g., vegetarian, vegan, keto, none)",
                'validate': self._validate_dietary_preferences
            },
            'dietary_restrictions': {
                'question': "Any food allergies or dietary restrictions? (e.g., nuts, dairy, gluten, none)",
                'validate': self._validate_dietary_restrictions
            },
            'workout_preferences': {
                'question': "What are your workout preferences? (e.g., gym, home workouts, equipment available, any injuries?)",
                'validate': self._validate_workout_preferences
            },

        }
        self.current_step = 0

Langchain Agent Configuration

Agent Initialization:

  • Model: GPT-4o-mini with temperature 0.3 for consistency.
  • Memory: ConversationBufferMemory for context consistency.
  • Tools: Web search to let the agent look up real-time information.

The initialize_fitcoach_agent function configures FitCoach, a Langchain conversational agent that serves as a virtual fitness and nutrition coach. It connects to the language model GPT-4o-mini, is potentially augmented by web search tools, and keeps track of conversation memory for context. The agent follows a stringent, rule-based dialogue continuity: it asks users specific questions one at a time to extract all important information regarding fitness goals, age, body metrics, food habits, and medical history, among others. Only after all you needed to know has been gathered and confirmed, the agent will commit to not generating any fitness or diet plans. This way, the agent allows for the safe, accurate, and personalized instructions that users want in an agent. Once all the necessary information has been gathered, FitCoach generates comprehensive workout routines and meal plans based on the user, while offering an interactive and engaging coaching plan.

# ----------- LANGCHAIN AGENT SETUP ------------

def initialize_fitcoach_agent():
    """Initialize the FitCoach agent with error handling"""
    try:
        # Check for OpenAI API key
        openai_key = os.getenv("OPENAI_API_KEY")
        if not openai_key:
            raise ValueError("OPENAI_API_KEY not found in environment variables")

        # Initialize the language model with correct model name
        llm = ChatOpenAI(
            model="gpt-4o-mini",
            temperature=0.3,
            openai_api_key=openai_key
        )

        # Initialize tools
        tools = []
        try:
            if os.getenv("SERPER_API_KEY"):
                search_tool = SerperSearchTool()
                tools.append(search_tool)
                print("? Search tool initialized successfully")
            else:
                print("?? SERPER_API_KEY not found - search functionality will be limited")
        except Exception as e:
            print(f"?? Could not initialize search tool: {e}")

        # Initialize memory
        memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)

Gradio Chatbot Logic

  • is_plan_content: Determines if a given text has a detailed fitness or nutrition plan by checking for multiple keywords, such as days of the week, meal names, and workout comparisons. Helps to separate plans from informal conversations around fitness.
  • format_plan_for_text: Formats raw fitness plan texts into cleaner sections while retaining headings, lists, and paragraphs, to improve readability and suitability for sharing in chat or email.
  • chat_function: Manages the FitCoach chat flow. Collects information from the user in steps (user fitness goal, meal preferences), calls the AI agent to produce a custom workout & meal plan, and safely handles errors to keep chat flow uninterrupted.
 ----------- GRADIO CHATBOT LOGIC ------------

def is_plan_content(text: str) -> bool:
    """Check if the text contains a fitness plan with detailed content"""
    if not text or len(text.strip()) = 3

Note: I have shown only parts of the code in the article. My full code is available here.

User Interface

When it comes to the user interface, you could use solutions like Streamlit or Gradio to keep it simple. I used Gradio since it allows me to create a polished web app with a custom design, automatic updates, and a quick, responsive interface that suits health and fitness applications. Click here to view the source code.

Build a LangChain Fitness Coach: Your AI Personal Trainer

Use Cases for Langchain

  • Customer Support Bots: Create an assistant that can search customer support knowledge bases to find answers to customer questions.
  • Search-Aided Chatbots: Curse maps to sources of real-time knowledge such as Google and Wikipedia.
  • Document Q&A: Allow the user to upload a PDF and automatically retrieve accurate answers with citations.
  • Data Manipulation Assistants: Allow users to upload and explore data in a spreadsheet while asking questions related to the data.
  • Content Generation Tools: Generate content, including blogs, emails, or social media posts.
  • Multi-agent Systems: Create systems in which AI Agents can collaborate or specialize in the task.

Conclusion

When it’s all said and done, AI isn’t all about tech; it’s about the inner workings of how to leverage technology as a power to improve our everyday lives! Whether it be to get in shape, eat well, or stay motivated, designing your own unique personal fitness coach is a perfect example of how AI can support and motivate, yet still keep us accountable for our actions to meet our goals. And the best part is you don’t have to be a tech wizard to start building your application! There are a number of tools like LangChain for development, OpenAI for AI capabilities, and Gradio for deploying your smart application, just to mention a few, that can help anyone build smart and unique applications for themselves. The future of fitness, as well as many other areas of life, is available to us!

The above is the detailed content of Build a LangChain Fitness Coach: Your AI Personal Trainer. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Kimi K2: The Most Powerful Open-Source Agentic Model Kimi K2: The Most Powerful Open-Source Agentic Model Jul 12, 2025 am 09:16 AM

Remember the flood of open-source Chinese models that disrupted the GenAI industry earlier this year? While DeepSeek took most of the headlines, Kimi K1.5 was one of the prominent names in the list. And the model was quite cool.

AGI And AI Superintelligence Are Going To Sharply Hit The Human Ceiling Assumption Barrier AGI And AI Superintelligence Are Going To Sharply Hit The Human Ceiling Assumption Barrier Jul 04, 2025 am 11:10 AM

Let’s talk about it. This analysis of an innovative AI breakthrough is part of my ongoing Forbes column coverage on the latest in AI, including identifying and explaining various impactful AI complexities (see the link here). Heading Toward AGI And

Grok 4 vs Claude 4: Which is Better? Grok 4 vs Claude 4: Which is Better? Jul 12, 2025 am 09:37 AM

By mid-2025, the AI “arms race” is heating up, and xAI and Anthropic have both released their flagship models, Grok 4 and Claude 4. These two models are at opposite ends of the design philosophy and deployment platform, yet they

In-depth discussion on how artificial intelligence can help and harm all walks of life In-depth discussion on how artificial intelligence can help and harm all walks of life Jul 04, 2025 am 11:11 AM

We will discuss: companies begin delegating job functions for AI, and how AI reshapes industries and jobs, and how businesses and workers work.

10 Amazing Humanoid Robots Already Walking Among Us Today 10 Amazing Humanoid Robots Already Walking Among Us Today Jul 16, 2025 am 11:12 AM

But we probably won’t have to wait even 10 years to see one. In fact, what could be considered the first wave of truly useful, human-like machines is already here. Recent years have seen a number of prototypes and production models stepping out of t

Context Engineering is the 'New' Prompt Engineering Context Engineering is the 'New' Prompt Engineering Jul 12, 2025 am 09:33 AM

Until the previous year, prompt engineering was regarded a crucial skill for interacting with large language models (LLMs). Recently, however, LLMs have significantly advanced in their reasoning and comprehension abilities. Naturally, our expectation

6 Tasks Manus AI Can Do in Minutes 6 Tasks Manus AI Can Do in Minutes Jul 06, 2025 am 09:29 AM

I am sure you must know about the general AI agent, Manus. It was launched a few months ago, and over the months, they have added several new features to their system. Now, you can generate videos, create websites, and do much mo

Build a LangChain Fitness Coach: Your AI Personal Trainer Build a LangChain Fitness Coach: Your AI Personal Trainer Jul 05, 2025 am 09:06 AM

Many individuals hit the gym with passion and believe they are on the right path to achieving their fitness goals. But the results aren’t there due to poor diet planning and a lack of direction. Hiring a personal trainer al

See all articles