偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

如何使用LangChain打造你的個人健身教練?

譯文 精選
人工智能
這篇博文介紹如何利用LangChain的強大功能打造你的健身教練。有了它,你現(xiàn)在可以以最低的成本獲得根據(jù)你的目標(biāo)定制的鍛煉和飲食建議。不妨開始運用這項令人驚嘆的技術(shù),將其變成你的健身助手!

譯者 | 布加迪

審校 | 重樓

許多人滿懷熱情地走進(jìn)健身房,相信自己正走在實現(xiàn)健身目標(biāo)的正確道路上。但由于飲食計劃不合理和缺乏方向,健身效果往往不盡如人意。聘請私人教練、添置昂貴的健身器材并非總是切實可行。因此我撰寫了這篇博文,介紹如何利用LangChain的強大功能打造你的健身教練。有了它,你現(xiàn)在可以以最低的成本獲得根據(jù)你的目標(biāo)定制的鍛煉和飲食建議。不妨開始運用這項令人驚嘆的技術(shù),將其變成你的健身助手!

為什么使用 Langchain?

Langchain通過將大語言模型(LLM)與工具、數(shù)據(jù)源和內(nèi)存相結(jié)合,使你在構(gòu)建高級 AI 應(yīng)用程序時能夠發(fā)揮更大的作用。你無需使用純文本提示調(diào)用LLM,而是可以創(chuàng)建智能體來調(diào)用函數(shù)、查詢信息和管理狀態(tài)對話。就健身教練而言,Langchain 允許你將LLM智能與定制邏輯相結(jié)合——比如創(chuàng)建鍛煉建議、跟蹤進(jìn)度和獲取健康數(shù)據(jù),這樣你就可以成為一名更智能的互動教練,無需自己費心思考所有事情。

前提條件

要使用LangChain創(chuàng)建你的健身教練,你需要:

  • 用于訪問語言模型的OpenAI API密鑰
  • 用于使用互聯(lián)網(wǎng)搜索的SerpAPI服務(wù)密鑰
  • 對Python 有基本的了解

好了,你現(xiàn)在可以開始了。

如何構(gòu)建你的健身教練?

在本節(jié)中,我將演示如何使用Langchain智能體創(chuàng)建健身教練。確保你已根據(jù)前提條件做好了一切準(zhǔn)備。我將逐步指導(dǎo)你構(gòu)建解決方案,并解釋每個步驟在實現(xiàn)結(jié)果中所起的作用。

FitCoach AI是一種對話式健身教練,它持續(xù)收集用戶數(shù)據(jù),并使用LangChain智能體和OpenAI生成個性化的鍛煉和飲食計劃。

核心依賴項

要安裝構(gòu)建健身智能體所需的所有庫,請在命令行中運行以下命令:

pip install gradio langchain openai serper-dev python-doten

所有依賴項安裝到位后,我們將開始導(dǎo)入任務(wù)所需的所有相關(guān)模塊:

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類

功能:提供實時網(wǎng)頁搜索功能,獲取最新的健身/營養(yǎng)信息。

主要特性:

  • 集成Serper API以獲取谷歌搜索結(jié)果。
  • 返回包含標(biāo)題、摘要和URL的前5個格式化搜索結(jié)果。
  • 具有可接受的故障模式和超時保護(hù)。
  • 支持同步和異步。
# ----------- 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 類

功能:在創(chuàng)建任何健身計劃之前獲取所有必要的信息。

Required Data Fields (in order):

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

主要特性:

  • 字段驗證:每個輸入都將使用自定義驗證函數(shù)進(jìn)行驗證。
  • 順序流:所有輸入均不可跳過。
  • 錯誤處理:為無效輸入提供具體的錯誤消息。
# ----------- 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智能體配置

智能體初始化:

  • 模型:GPT-4o-mini,溫度設(shè)置為 0.3,以確保一致性。
  • 內(nèi)存:ConversationBufferMemory,用于上下文一致性。
  • 工具:互聯(lián)網(wǎng)搜索,讓智能體可以查找實時信息。

initialize_fitcoach_agent函數(shù)用于配置FitCoach,這個Langchain對話智能體充當(dāng)虛擬健身和營養(yǎng)教練。它連接到語言模型GPT-4o-mini,可以輔以互聯(lián)網(wǎng)搜索工具,并跟蹤對話記憶以獲取上下文。該智能體遵循嚴(yán)格的基于規(guī)則的對話連續(xù)性:它會向用戶逐個詢問特定問題,以提取有關(guān)健身目標(biāo)、年齡、身體指標(biāo)、飲食習(xí)慣和病史等方面的所有重要信息。只有在收集并確認(rèn)所有必要信息后,智能體才會根據(jù)用戶情況生成全面的鍛煉計劃和膳食計劃,提供用戶所需的安全、準(zhǔn)確和個性化的指導(dǎo)。

# ----------- 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 聊天機器人邏輯

  • is_plan_content:通過檢查多個關(guān)鍵詞(比如星期幾、膳食名稱和鍛煉對比),確定特定的文本是否包含詳細(xì)的健身或營養(yǎng)計劃。這有助于將計劃與非正式的健身對話區(qū)分開來。
  • format_plan_for_text:將原始健身計劃文本格式化為更簡潔的部分,同時保留標(biāo)題、列表和段落,以提高可讀性,并使其更適合在聊天或電子郵件中分享。
  • chat_function:管理FitCoach聊天流程。分步收集用戶信息(用戶健身目標(biāo)、膳食偏好),調(diào)用 AI智能體來制定個性化鍛煉和膳食計劃,并安全處理錯誤以確保聊天流程暢通無阻。
----------- 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()) < 100: # Too short to be a complete plan
 return False

 # Check for common 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'
 ]

 # Check for multiple indicators to reduce false positives
 text_lower = text.lower()
 matching_indicators = [ind for ind in plan_indicators if ind in text_lower]

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

注意:本文僅展示了部分代碼。完整代碼可在此處獲取:

https://colab.research.google.com/drive/1rr2LrPH-XoXxSKO9GLfkhUUoJ33ZVWjx?usp=sharing。

用戶界面

說到用戶界面,你可以使用Streamlit或Gradio等解決方案來簡化操作。我使用了Gradio,因為它允許我創(chuàng)建一個精致的Web應(yīng)用程序,附有自定義設(shè)計、自動更新以及快速響應(yīng)的界面,非常適合健康和健身應(yīng)用。點擊此處即可查看源代碼:https://colab.research.google.com/drive/1rr2LrPH-XoXxSKO9GLfkhUUoJ33ZVWjx?usp=sharing。

Langchain 的用例

  • 客戶支持機器人:創(chuàng)建一個可以搜索客戶支持知識庫以查找客戶問題答案的助手。
  • 搜索輔助聊天機器人:Curse 可以映射到谷歌和維基百科等實時知識來源。
  • 文檔問答:允許用戶上傳 PDF文件,并自動檢索帶有引用的準(zhǔn)確答案。
  • 數(shù)據(jù)操作助手:允許用戶在電子表格中上傳和探索數(shù)據(jù),并提出與數(shù)據(jù)相關(guān)的問題。
  • 內(nèi)容生成工具:生成內(nèi)容,包括博客、電子郵件或社交媒體帖子。
  • 多智能體系統(tǒng):創(chuàng)建AI智能體進(jìn)行協(xié)作或?qū)iT處理特定任務(wù)的系統(tǒng)。

結(jié)論

總而言之,AI 并非僅僅關(guān)乎技術(shù),而是關(guān)乎如何利用技術(shù)的力量來改善我們?nèi)粘I畹膬?nèi)部運作!無論是為了塑形、健康飲食還是保持干勁,設(shè)計專屬于你的私人健身教練就是一個典例,表明了AI如何支持和激勵我們,同時讓我們對自己的行為負(fù)責(zé),最終實現(xiàn)目標(biāo)。最棒的是,你無需成為技術(shù)專家即可開始構(gòu)建應(yīng)用程序!市面上有許多工具,比如用于開發(fā)的LangChain、用于AI功能的OpenAI以及用于部署智能應(yīng)用程序的Gradio等等,它們可以幫助任何人構(gòu)建屬于自己的智能且獨特的應(yīng)用程序。健身以及生活其他諸多領(lǐng)域的未來都呈現(xiàn)在我們面前!

原文標(biāo)題:How to Build your Personal Fitness Coach using LangChain?,作者:Soumil Jain

責(zé)任編輯:姜華 來源: 51CTO內(nèi)容精選
相關(guān)推薦

2020-11-24 09:42:30

人工智能健身數(shù)字

2015-06-26 16:59:57

WOO火辣健身徐威特

2021-12-10 06:43:07

CS年薪計算機

2015-06-19 15:11:04

敏捷物聯(lián)華為

2022-06-16 19:57:03

AR火山引擎

2025-03-17 08:30:00

谷歌模型AI

2017-04-28 22:07:38

威海智慧健身大數(shù)據(jù)平臺

2021-01-06 17:55:00

HarmonyOS應(yīng)用開發(fā)Fit

2020-01-18 18:44:39

網(wǎng)絡(luò)硬盤百度固態(tài)硬盤

2023-11-23 08:00:00

OpenAILangChain

2025-05-08 07:54:24

2016-12-09 13:42:14

2024-08-12 15:23:43

LangChain

2017-02-27 11:06:28

Github開源項目

2021-07-27 10:34:15

高管教練高管輔導(dǎo)IT領(lǐng)導(dǎo)者

2014-12-03 10:54:55

2015-09-08 15:37:08

2011-09-16 10:59:11

IOS應(yīng)用Android應(yīng)用iPhone應(yīng)用

2023-11-21 08:00:00

LangChain大型語言模型人工智能

2018-02-26 06:53:21

軟件程序員數(shù)字化
點贊
收藏

51CTO技術(shù)棧公眾號