国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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)

Top 7 NotebookLM Alternatives Top 7 NotebookLM Alternatives Jun 17, 2025 pm 04:32 PM

Google’s NotebookLM is a smart AI note-taking tool powered by Gemini 2.5, which excels at summarizing documents. However, it still has limitations in tool use, like source caps, cloud dependence, and the recent “Discover” feature

Sam Altman Says AI Has Already Gone Past The Event Horizon But No Worries Since AGI And ASI Will Be A Gentle Singularity Sam Altman Says AI Has Already Gone Past The Event Horizon But No Worries Since AGI And ASI Will Be A Gentle Singularity Jun 12, 2025 am 11:26 AM

Let’s dive into this.This piece analyzing a groundbreaking development in AI is part of my continuing coverage for Forbes on the evolving landscape of artificial intelligence, including unpacking and clarifying major AI advancements and complexities

Hollywood Sues AI Firm For Copying Characters With No License Hollywood Sues AI Firm For Copying Characters With No License Jun 14, 2025 am 11:16 AM

But what’s at stake here isn’t just retroactive damages or royalty reimbursements. According to Yelena Ambartsumian, an AI governance and IP lawyer and founder of Ambart Law PLLC, the real concern is forward-looking.“I think Disney and Universal’s ma

Alphafold 3 Extends Modeling Capacity To More Biological Targets Alphafold 3 Extends Modeling Capacity To More Biological Targets Jun 11, 2025 am 11:31 AM

Looking at the updates in the latest version, you’ll notice that Alphafold 3 expands its modeling capabilities to a wider range of molecular structures, such as ligands (ions or molecules with specific binding properties), other ions, and what’s refe

What Does AI Fluency Look Like In Your Company? What Does AI Fluency Look Like In Your Company? Jun 14, 2025 am 11:24 AM

Using AI is not the same as using it well. Many founders have discovered this through experience. What begins as a time-saving experiment often ends up creating more work. Teams end up spending hours revising AI-generated content or verifying outputs

Dia Browser Released — With AI That Knows You Like A Friend Dia Browser Released — With AI That Knows You Like A Friend Jun 12, 2025 am 11:23 AM

Dia is the successor to the previous short-lived browser Arc. The Browser has suspended Arc development and focused on Dia. The browser was released in beta on Wednesday and is open to all Arc members, while other users are required to be on the waiting list. Although Arc has used artificial intelligence heavily—such as integrating features such as web snippets and link previews—Dia is known as the “AI browser” that focuses almost entirely on generative AI. Dia browser feature Dia's most eye-catching feature has similarities to the controversial Recall feature in Windows 11. The browser will remember your previous activities so that you can ask for AI

The Prototype: Space Company Voyager's Stock Soars On IPO The Prototype: Space Company Voyager's Stock Soars On IPO Jun 14, 2025 am 11:14 AM

Space company Voyager Technologies raised close to $383 million during its IPO on Wednesday, with shares offered at $31. The firm provides a range of space-related services to both government and commercial clients, including activities aboard the In

From Adoption To Advantage: 10 Trends Shaping Enterprise LLMs In 2025 From Adoption To Advantage: 10 Trends Shaping Enterprise LLMs In 2025 Jun 20, 2025 am 11:13 AM

Here are ten compelling trends reshaping the enterprise AI landscape.Rising Financial Commitment to LLMsOrganizations are significantly increasing their investments in LLMs, with 72% expecting their spending to rise this year. Currently, nearly 40% a

See all articles