Spaces:
Sleeping
Sleeping
| from smolagents import CodeAgent, HfApiModel,load_tool,tool | |
| import requests | |
| import yaml | |
| import json | |
| from tools.final_answer import FinalAnswerTool | |
| from tools.web_search import DuckDuckGoSearchTool | |
| from bs4 import BeautifulSoup | |
| from duckduckgo_search import DDGS | |
| import re | |
| from typing import List, Dict, Any | |
| from Gradio_UI import GradioUI | |
| def get_healthy_cheat_meal(diet_type: str) -> List[Dict[str, Any]]: | |
| """Search for healthy sweet dish alternatives based on specific diet types. | |
| Args: | |
| diet_type: The specific diet type (e.g., Keto, Paleo, Vegan). | |
| Returns: | |
| A list of dictionaries containing 'recipe_name', 'url', 'ingredients', and 'instructions'. | |
| """ | |
| query = f"healthy {diet_type} sweet dish recipe" | |
| recipes = [] | |
| try: | |
| ddgs = DDGS() | |
| search_results = ddgs.text(query, region="us-en", safesearch="moderate", max_results=10) | |
| if not search_results: | |
| return [{"error": "No recipes found"}] | |
| for result in search_results: | |
| title = result.get('title', '').split(' - ')[0].strip() | |
| url = result.get('href', '') | |
| if not url: | |
| continue # Skip if no URL | |
| # Fetch recipe details | |
| details = visit_webpage(url) | |
| # Skip recipes with errors | |
| if "error" in details: | |
| continue | |
| recipes.append({ | |
| "recipe_name": title, | |
| "url": url, | |
| "ingredients": details.get("ingredients", []), | |
| "instructions": details.get("instructions", []) | |
| }) | |
| return recipes if recipes else [{"error": "No valid recipes found"}] | |
| except Exception as e: | |
| return [{"error": f"An error occurred: {str(e)}"}] | |
| def visit_webpage(url: str) -> Dict[str, Any]: | |
| """Visits a webpage and extracts ingredients and instructions. | |
| Args: | |
| url: The recipe URL. | |
| Returns: | |
| A dictionary containing 'ingredients' and 'instructions', or an error message if the URL is invalid. | |
| """ | |
| try: | |
| # Validate URL format before making a request | |
| if not url.startswith("http"): | |
| return {"error": f"Invalid URL format: {url}"} | |
| response = requests.get(url, timeout=10, headers={ | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' | |
| }) | |
| response.raise_for_status() # Raise an error for 404, 403, etc. | |
| soup = BeautifulSoup(response.content, 'html.parser') | |
| # Extract ingredients | |
| ingredients = [tag.get_text(strip=True) for tag in soup.select('ul li, .ingredient')] | |
| if not ingredients: | |
| ingredients = [tag.get_text(strip=True) for tag in soup.find_all('li') if "ingredient" in tag.get_text(strip=True).lower()] | |
| # Extract instructions | |
| instructions = [tag.get_text(strip=True) for tag in soup.select('ol li, .instruction, .step')] | |
| if not instructions: | |
| instructions = [tag.get_text(strip=True) for tag in soup.find_all('p') if "step" in tag.get_text(strip=True).lower()] | |
| return { | |
| "ingredients": ingredients if ingredients else [], | |
| "instructions": instructions if instructions else [] | |
| } | |
| except requests.exceptions.HTTPError as http_err: | |
| return {"error": f"HTTP error {response.status_code}: {http_err}"} | |
| except requests.exceptions.RequestException as req_err: | |
| return {"error": f"Request failed: {req_err}"} | |
| except Exception as e: | |
| return {"error": f"Failed to scrape {url}: {str(e)}"} | |
| # Initialize tools | |
| final_answer = FinalAnswerTool() | |
| # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder: | |
| # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| #model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded | |
| model_id = 'https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud', | |
| custom_role_conversions=None, | |
| ) | |
| # Import tool from Hub | |
| #image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
| with open("prompts.yaml", 'r') as stream: | |
| prompt_templates = yaml.safe_load(stream) | |
| agent = CodeAgent( | |
| model=model, | |
| tools=[get_healthy_cheat_meal, visit_webpage, final_answer], ## add your tools here (don't remove final answer) | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() |