CoolFace
Apppublic

deeptig92/Dish_Recommender

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py165 linesDownload Raw Back to root
1from smolagents import CodeAgent,DuckDuckGoSearchTool, VisitWebpageTool, HfApiModel,load_tool,tool2import requests3import pytz4import yaml5from tools.final_answer import FinalAnswerTool6from typing import List, Dict, Any7import json, os, datetime as _dt8 9from Gradio_UI import GradioUI10 11# Below is an example of a tool that does nothing. Amaze us with your creativity !12_TODO_PATH = "/mnt/data/todo_data.json"13 14def _load(persist: bool) -> Dict[str, Any]:15    if persist and os.path.exists(_TODO_PATH):16        try:17            with open(_TODO_PATH, "r", encoding="utf-8") as f:18                return json.load(f)19        except Exception:20            # corrupted or unreadable -> start clean21            return {"next_id": 1, "tasks": []}22    return {"next_id": 1, "tasks": []}23 24def _save(state: Dict[str, Any], persist: bool) -> None:25    if not persist:26        return27    os.makedirs(os.path.dirname(_TODO_PATH), exist_ok=True)28    with open(_TODO_PATH, "w", encoding="utf-8") as f:29        json.dump(state, f, ensure_ascii=False, indent=2)30 31def _validate_priority(p: str) -> str:32    p = (p or "normal").strip().lower()33    return p if p in {"low", "normal", "high"} else "normal"34 35def _validate_due(d: str) -> str:36    d = (d or "").strip()37    if not d:38        return ""39    try:40        _dt.date.fromisoformat(d)  # YYYY-MM-DD41        return d42    except Exception:43        return ""44 45@tool46def todo_manager(action: str,47                 title: str = "",48                 task_id: int = 0,49                 priority: str = "normal",50                 due: str = "",51                 persist: bool = False) -> Dict[str, Any]:52    """Create and manage a simple todo list.53 54    Args:55      action: 'add' | 'list' | 'complete' | 'uncomplete' | 'delete' | 'clear'.56      title: Task title (needed for 'add'; optional substring filter for 'list').57      task_id: Required for 'complete'/'uncomplete'/'delete'.58      priority: 'low' | 'normal' | 'high' (used by 'add').59      due: Optional 'YYYY-MM-DD' (used by 'add').60      persist: If true, saves/loads to /mnt/data/todo_data.json so state survives steps.61 62    Returns:63      { ok, message, tasks: [{id,title,done,priority,due,created_at}] }64    """65    state = _load(persist)66    tasks: List[Dict[str, Any]] = state["tasks"]67 68    action = (action or "").strip().lower()69    if action == "add":70        if not title.strip():71            return {"ok": False, "message": "Title is required for add.", "tasks": tasks}72        task = {73            "id": state["next_id"],74            "title": title.strip(),75            "done": False,76            "priority": _validate_priority(priority),77            "due": _validate_due(due),78            "created_at": _dt.datetime.utcnow().isoformat(timespec="seconds")79        }80        state["next_id"] += 181        tasks.append(task)82        _save(state, persist)83        return {"ok": True, "message": f"Added task #{task['id']}.", "tasks": tasks}84 85    elif action in {"complete", "uncomplete", "delete"}:86        if not task_id:87            return {"ok": False, "message": "task_id is required.", "tasks": tasks}88        idx = next((i for i, t in enumerate(tasks) if t["id"] == int(task_id)), -1)89        if idx < 0:90            return {"ok": False, "message": f"Task #{task_id} not found.", "tasks": tasks}91        if action == "complete":92            tasks[idx]["done"] = True93            msg = f"Completed task #{task_id}."94        elif action == "uncomplete":95            tasks[idx]["done"] = False96            msg = f"Marked task #{task_id} as not done."97        else:98            tasks.pop(idx)99            msg = f"Deleted task #{task_id}."100        _save(state, persist)101        return {"ok": True, "message": msg, "tasks": tasks}102 103    elif action == "clear":104        state["tasks"] = []105        _save(state, persist)106        return {"ok": True, "message": "Cleared all tasks.", "tasks": []}107 108    elif action == "list":109        q = title.strip().lower()110        view = [t for t in tasks if (not q or q in t["title"].lower())]111        return {"ok": True, "message": f"{len(view)} task(s).", "tasks": view}112 113    else:114        return {"ok": False, "message": "Unknown action. Use add/list/complete/uncomplete/delete/clear.", "tasks": tasks}115 116@tool117def get_current_time_in_timezone(timezone: str) -> str:118    """A tool that fetches the current local time in a specified timezone.119    Args:120        timezone: A string representing a valid timezone (e.g., 'America/New_York').121    """122    try:123        # Create timezone object124        tz = pytz.timezone(timezone)125        # Get current time in that timezone126        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")127        return f"The current local time in {timezone} is: {local_time}"128    except Exception as e:129        return f"Error fetching time for timezone '{timezone}': {str(e)}"130 131web_search = DuckDuckGoSearchTool(max_results=5)  # returns top N results132visit_page = VisitWebpageTool(max_output_length=40_000)           # fetches & returns page text133final_answer = FinalAnswerTool()134 135# 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:136# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 137 138model = HfApiModel(139max_tokens=2096,140temperature=0.5,141model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded142custom_role_conversions=None,143)144 145 146# Import tool from Hub147image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)148 149with open("prompts.yaml", 'r') as stream:150    prompt_templates = yaml.safe_load(stream)151    152agent = CodeAgent(153    model=model,154    tools=[todo_manager, final_answer ], ## add your tools here (don't remove final answer)155    max_steps=4,156    verbosity_level=1,157    grammar=None,158    planning_interval=None,159    name=None,160    description=None,161    prompt_templates=prompt_templates162)163 164 165GradioUI(agent).launch()