Construct a LangChain Health Coach: Your AI Private Coach

Many people hit the health club with ardour and imagine they’re on the precise path to reaching their health objectives. However the outcomes aren’t there resulting from poor weight loss program planning and a scarcity of route. Hiring a private coach together with an costly health club stack isn’t all the time an choice. That’s the reason I’ve created this weblog put up to indicate you the right way to construct your health coach utilizing the ability of LangChain. With this, now you can get exercise and weight loss program recommendation personalized to your objectives with minimal value. Let’s get began with taking some superb tech and turning it into your health co-pilot!

Why Use Langchain?

Langchain lets you do rather more when constructing superior AI functions by combining giant language fashions (LLMs) with instruments, information sources, and reminiscence. As an alternative of invoking the LLM with a plain textual content immediate, you possibly can create brokers that invoke capabilities, question info, and handle conversations with state. For a health coach, Langchain lets you mix LLM intelligence with customized logic – for instance, create exercise options, observe progress, and get well being information – so that you could be a smarter interactive coach with out having to determine that every one out your self.

Conditions

To create your health coach utilizing LangChain, you’ll want:

  • An OpenAI API key to entry language fashions
  • A key for the SerpAPI service to make use of the net search
  • Primary data of Python

That’s all, you at the moment are able to get began.

Tips on how to Construct Your Health Coach?

On this part, I’ll exhibit the right way to make your health coach utilizing a Langchain agent. Guarantee you may have all the pieces ready in line with the conditions. I’ll stroll you thru the step-by-step means of constructing the answer and clarify the position every step performs in reaching the result.

FitCoach AI is a conversational health coach that collects person information persistently and generates personalised exercise and weight loss program plans utilizing LangChain brokers with OpenAI.

Core Dependencies 

To put in all of the libraries required for constructing the health agent, run the next command in your command line:

pip set up gradio langchain openai serper-dev python-doten

As soon as all of the dependencies are in place, we’d begin by importing all of the related modules for the duty:

import os
import gradio as gr
import traceback
import datetime
from typing import Checklist, Tuple, Non-obligatory

from langchain_openai import ChatOpenAI
from langchain.reminiscence import ConversationBufferMemory
from langchain.brokers import initialize_agent, AgentType
from langchain.instruments import BaseTool
import json
import requests
import dotenv

# Load surroundings variables
dotenv.load_dotenv()

SerperSearchTool Class

Performance: Offers the power to have real-time net search capabilities for up-to-date health/diet info.

Primary options:

  • Integrates with the Serper API to get Google search outcomes 
  • Returns the highest 5 formatted search outcomes that embody the title, snippet, and URL
  • Has acceptable failure modes with timeout safety
  • Helps each sync and async
# ----------- SERPER SEARCH TOOL ------------

class SerperSearchTool(BaseTool):
    identify: str = "search_web"
    description: str = "Searches the net for real-time info and returns structured outcomes"

    def _run(self, question: str) -> str:
        """Search the net utilizing Serper API"""
        strive:
            api_key = os.getenv("SERPER_API_KEY")
            if not api_key:
                return "Error: SERPER_API_KEY not present in surroundings variables"

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

            response = requests.put up(url, headers=headers, information=payload, timeout=10)
            response.raise_for_status()
            search_results = response.json()

            # Extract and format natural outcomes
            outcomes = []
            if 'natural' in search_results:
                for merchandise in search_results['organic'][:5]:  # Restrict to high 5 outcomes
                    outcomes.append({
                        "title": merchandise.get('title', ''),
                        "hyperlink": merchandise.get('hyperlink', ''),
                        "snippet": merchandise.get('snippet', '')
                    })

            # Format ends in a readable manner
            if outcomes:
                formatted_results = "Search Outcomes:nn"
                for i, lead to enumerate(outcomes, 1):
                    formatted_results += f"{i}. {end result['title']}n"
                    formatted_results += f"   {end result['snippet']}n"
                    formatted_results += f"   URL: {end result['link']}nn"
                return formatted_results
            else:
                return "No search outcomes discovered."

        besides requests.exceptions.RequestException as e:
            return f"Error performing search - Community problem: {str(e)}"
        besides Exception as e:
            return f"Error performing search: {str(e)}"

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

UserDataTracker Class

Performance: Get all mandatory info earlier than creating any health plans

Required Knowledge Fields (so as):

Health objective (weight reduction, muscle achieve, and so forth.)
Age (in vary 10-100 validation)
Gender (male/feminine/different)
Weight (in models, - kg/lbs)
Peak (in cm or toes/inches)
Exercise Stage (5 predefined ranges)
Food regimen Preferences (vegetarian, vegan, and so forth.)
Food regimen Restrictions/allergy
Exercise-Preferencing & limitations

Primary Options:

  • Subject Validation: Every enter might be validated with customized validation capabilities.
  • Sequential Circulation: Nobody can skip forward.
  • Error Dealing with: Present particular error messages for invalid inputs.
# ----------- USER DATA TRACKER CLASS ------------

class UserDataTracker:
    def __init__(self):
        self.information = {}
        # Outline required fields with their validation capabilities and query prompts
        self.required_fields = {
            'fitness_goal': {
                'query': "What's your major health objective? (e.g., weight reduction, muscle achieve, basic health)",
                'validate': self._validate_fitness_goal
            },
            'age': {
                'query': "How previous are you? (Should be between 10-100)",
                'validate': self._validate_age
            },
            'gender': {
                'query': "What's your gender? (male/feminine/different)",
                'validate': self._validate_gender
            },
            'weight': {
                'query': "What's your present weight? (e.g., 150 lbs or 68 kg)",
                'validate': self._validate_weight
            },
            'top': {
                'query': "What's your top? (e.g., 5'10" or 178 cm)",
                'validate': self._validate_height
            },
            'activity_level': {
                'query': "What's your exercise stage? (sedentary, evenly lively, reasonably lively, very lively, extraordinarily lively)",
                'validate': self._validate_activity_level
            },
            'dietary_preferences': {
                'query': "Do you comply with any particular weight loss program? (e.g., vegetarian, vegan, keto, none)",
                'validate': self._validate_dietary_preferences
            },
            'dietary_restrictions': {
                'query': "Any meals allergic reactions or dietary restrictions? (e.g., nuts, dairy, gluten, none)",
                'validate': self._validate_dietary_restrictions
            },
            'workout_preferences': {
                'query': "What are your exercise preferences? (e.g., health club, house exercises, gear accessible, any accidents?)",
                'validate': self._validate_workout_preferences
            },

        }
        self.current_step = 0

Langchain Agent Configuration

Agent Initialization:

  • Mannequin: GPT-4o-mini with temperature 0.3 for consistency.
  • Reminiscence: ConversationBufferMemory for context consistency.
  • Instruments: Internet search to let the agent search for real-time info.

The initialize_fitcoach_agent perform configures FitCoach, a Langchain conversational agent that serves as a digital health and diet coach. It connects to the language mannequin GPT-4o-mini, is probably augmented by net search instruments, and retains observe of dialog reminiscence for context. The agent follows a stringent, rule-based dialogue continuity: it asks customers particular questions one after the other to extract all necessary info concerning health objectives, age, physique metrics, meals habits, and medical historical past, amongst others. Solely in any case you wanted to know has been gathered and confirmed, the agent will decide to not producing any health or weight loss program plans. This fashion, the agent permits for the protected, correct, and personalised directions that customers need in an agent. As soon as all the required info has been gathered, FitCoach generates complete exercise routines and meal plans based mostly on the person, whereas providing an interactive and fascinating teaching plan.

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

def initialize_fitcoach_agent():
    """Initialize the FitCoach agent with error dealing with"""
    strive:
        # Examine for OpenAI API key
        openai_key = os.getenv("OPENAI_API_KEY")
        if not openai_key:
            increase ValueError("OPENAI_API_KEY not present in surroundings variables")

        # Initialize the language mannequin with appropriate mannequin identify
        llm = ChatOpenAI(
            mannequin="gpt-4o-mini",
            temperature=0.3,
            openai_api_key=openai_key
        )

        # Initialize instruments
        instruments = []
        strive:
            if os.getenv("SERPER_API_KEY"):
                search_tool = SerperSearchTool()
                instruments.append(search_tool)
                print("✅ Search device initialized efficiently")
            else:
                print("⚠️ SERPER_API_KEY not discovered - search performance might be restricted")
        besides Exception as e:
            print(f"⚠️ Couldn't initialize search device: {e}")

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

Gradio Chatbot Logic

  • is_plan_content: Determines if a given textual content has an in depth health or diet plan by checking for a number of key phrases, comparable to days of the week, meal names, and exercise comparisons. Helps to separate plans from casual conversations round health. 
  • format_plan_for_text: Codecs uncooked health plan texts into cleaner sections whereas retaining headings, lists, and paragraphs, to enhance readability and suitability for sharing in chat or e mail. 
  • chat_function: Manages the FitCoach chat circulation. Collects info from the person in steps (person health objective, meal preferences), calls the AI agent to supply a customized exercise & meal plan, and safely handles errors to maintain chat circulation uninterrupted. 
 ----------- GRADIO CHATBOT LOGIC ------------

def is_plan_content(textual content: str) -> bool:
    """Examine if the textual content incorporates a health plan with detailed content material"""
    if not textual content or len(textual content.strip()) < 100:  # Too brief to be a whole plan
        return False

    # Examine for frequent plan indicators
    plan_indicators = [
        'workout plan', 'exercise routine', 'training program',
        'meal plan', 'nutrition plan', 'diet plan', 'weekly schedule',
        'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday',
        'sets x reps', 'rest between sets', 'warm up', 'cool down',
        'day 1', 'day 2', 'day 3', 'day 4', 'day 5', 'day 6', 'day 7',
        'breakfast', 'lunch', 'dinner', 'snacks', 'meals', 'nutrition',
        'exercise', 'workout', 'training', 'routine', 'program', 'plan'
    ]

    # Examine for a number of indicators to cut back false positives
    text_lower = textual content.decrease()
    matching_indicators = [ind for ind in plan_indicators if ind in text_lower]

    # Require at the very least 3 matching indicators to contemplate it a plan
    return len(matching_indicators) >= 3

Be aware: I’ve proven solely components of the code within the article. My full code is offered right here.

Person Interface

In terms of the person interface, you may use options like Streamlit or Gradio to maintain it easy. I used Gradio because it permits me to create a sophisticated net app with a customized design, automated updates, and a fast, responsive interface that fits well being and health functions. Click on right here to view the supply code.

Use Instances for Langchain

  • Buyer Help Bots: Create an assistant that may search buyer help data bases to search out solutions to buyer questions.  
  • Search-Aided Chatbots: Curse maps to sources of real-time data comparable to Google and Wikipedia.  
  • Doc Q&A: Enable the person to add a PDF and routinely retrieve correct solutions with citations.  
  • Knowledge Manipulation Assistants: Enable customers to add and discover information in a spreadsheet whereas asking questions associated to the info.  
  • Content material Technology Instruments: Generate content material, together with blogs, emails, or social media posts.
  • Multi-agent Programs: Create techniques wherein AI Brokers can collaborate or specialize within the process.

Conclusion

When it’s all mentioned and carried out, AI isn’t all about tech; it’s in regards to the interior workings of the right way to leverage expertise as an influence to enhance our on a regular basis lives! Whether or not or not it’s to get in form, eat nicely, or keep motivated, designing your individual distinctive private health coach is an ideal instance of how AI can help and inspire, but nonetheless preserve us accountable for our actions to satisfy our objectives. And the very best half is you don’t must be a tech wizard to start out constructing your software! There are a variety of instruments like LangChain for improvement, OpenAI for AI capabilities, and Gradio for deploying your good software, simply to say a number of, that may assist anybody construct good and distinctive functions for themselves. The way forward for health, in addition to many different areas of life, is offered to us!

Knowledge Scientist | AWS Licensed Options Architect | AI & ML Innovator

As a Knowledge Scientist at Analytics Vidhya, I specialise in Machine Studying, Deep Studying, and AI-driven options, leveraging NLP, pc imaginative and prescient, and cloud applied sciences to construct scalable functions.

With a B.Tech in Pc Science (Knowledge Science) from VIT and certifications like AWS Licensed Options Architect and TensorFlow, my work spans Generative AI, Anomaly Detection, Pretend Information Detection, and Emotion Recognition. Captivated with innovation, I try to develop clever techniques that form the way forward for AI.

Login to proceed studying and luxuriate in expert-curated content material.