import requests import json import gradio as gr from textblob import TextBlob # Tool 1: Joke Generation def joke_generation( categories: str = "Any", lang: str = "en", blacklistFlags: str | None = None, safe_mode: bool = True, type: str | None = None, contains: str | None = None, idRange: str | None = None, amount: int = 1 ): """ Fetches jokes from JokeAPI. Use this tool when the user asks for a joke. **IMPORTANT:** For simple requests like "tell me a joke", you do not need to specify any parameters. The function will automatically fetch a safe, general joke by default. Args: categories (str): The category of the joke. ONLY use this if the user explicitly asks for a specific category. It MUST be one of: 'Any', 'Programming', 'Misc', 'Pun', 'Dark', 'Spooky', 'Christmas'. lang (str): Language code for the joke (e.g., 'pt' for Portuguese). Only use if the user requests another language. blacklistFlags (str | None): Comma-separated flags to exclude: 'nsfw', 'religious', 'political', 'racist', 'sexist', 'explicit'. Only use if requested. safe_mode (bool): Defaults to True. Set to False only if the user explicitly wants potentially unsafe jokes. type (str | None): 'single' or 'twopart'. Only set if user specifies. contains (str | None): A substring the joke must include. Only set if requested. idRange (str | None): Specific ID or range (e.g., '10-50'). Only use if requested. amount (int): Number of jokes to fetch (1–10). Only change if the user asks for multiple jokes. Returns: A string containing the joke. **Example:** joke_generation() "Why don't scientists trust atoms? Because they make up everything!" """ url = f"https://v2.jokeapi.dev/joke/{categories}" params: dict[str, str | int | bool] = { "format": "json", "lang": lang, "amount": amount } if blacklistFlags: params["blacklistFlags"] = blacklistFlags if safe_mode: params["safe-mode"] = "" if type: params["type"] = type if contains: params["contains"] = contains if idRange: params["idRange"] = idRange try: resp = requests.get(url, params=params) resp.raise_for_status() data = resp.json() if data.get("error"): return [f"JokeAPI error: {data.get('message', 'Unknown error')}"] def extract(item: dict): if item.get("type") == "single": return item["joke"] else: # two-part joke return f"{item['setup']} {item['delivery']}" if amount > 1: jokes = [extract(j) for j in data.get("jokes", [])] else: # single joke — flatten dict to string if needed single = extract(data) jokes = [single] # jokes = ["Why do cemeteries have fences around them? Because everyone’s dying to get in."] return jokes except requests.exceptions.RequestException as e: return [f"Network error: {e}"] # Tool 2: Sentiment Analysis def sentiment_analysis(text: str) -> str: """ Analyzes the sentiment of a given text using TextBlob. Args: text (str): The text to analyze. Must not be empty. Returns: A JSON string with: - polarity: -1 (negative) to 1 (positive) - subjectivity: 0 (objective) to 1 (subjective) - assessment: 'positive', 'negative', or 'neutral' """ if not text: return json.dumps({"error": "Input text cannot be empty."}) blob = TextBlob(text) polarity = round(blob.sentiment.polarity, 2) subjectivity = round(blob.sentiment.subjectivity, 2) if polarity > 0.1: assessment = "positive" elif polarity < -0.1: assessment = "negative" else: assessment = "neutral" return json.dumps({ "polarity": polarity, "subjectivity": subjectivity, "assessment": assessment }, indent=2) # --- Gradio Interface Setup --- # Sentiment Analysis interface sentiment_interface = gr.Interface( fn=sentiment_analysis, inputs=gr.Textbox(lines=5, placeholder="Enter text here..."), outputs=gr.JSON(), api_name="sentiment_analysis", title="Sentiment Analysis Tool", description="Analyzes the sentiment of a piece of text." ) # Joke Generation interface joke_interface = gr.Interface( fn=joke_generation, inputs=[ gr.Textbox( label="Categories", value="Any", info="Any, Programming, Misc, Pun, Dark, Spooky, Christmas" ), gr.Dropdown( label="Language", choices=["en", "cs", "de", "es", "fr", "pt"], value="en" ), gr.CheckboxGroup( label="Blacklist Flags", choices=["nsfw", "religious", "political", "racist", "sexist", "explicit"] ), gr.Checkbox(label="Safe Mode", value=True), gr.Radio( label="Joke Type", choices=["single", "twopart"] ), gr.Textbox(label="Contains"), gr.Textbox(label="ID Range"), gr.Slider( label="Amount", minimum=1, maximum=10, step=1, value=1 ), ], outputs=gr.JSON(), api_name="joke_generation", title="Joke Generation Tool", description=( "Fetches jokes from JokeAPI using various filters. " "For a simple joke, just click Submit without changing any fields." ) ) # Combine into a tabbed demo demo = gr.TabbedInterface( [joke_interface, sentiment_interface], ["Joke Generation", "Sentiment Analysis"] ) if __name__ == "__main__": demo.launch(mcp_server=True) # import os # # from dotenv import load_dotenv # import requests # import json # import gradio as gr # from textblob import TextBlob # from groq import Groq # # Load environment (e.g. GROQ_API_KEY) from .env or Secrets in Hugging Face Spaces # # load_dotenv() # # In Hugging Face, go to Settings → Secrets & Variables → Add new variable: # # Name: GROQ_API_KEY # # Value: # # Tool 1: Joke Generation # def joke_generation( # categories: str = "Any", # lang: str = "en", # blacklistFlags: str | None = None, # safe_mode: bool = True, # type: str | None = None, # contains: str | None = None, # idRange: str | None = None, # amount: int = 1 # ): # """ # Fetches jokes from JokeAPI. Use this tool when the user asks for a joke. # **IMPORTANT:** For simple requests like "tell me a joke", you do not need to specify any parameters. The function will automatically fetch a safe, general joke by default. # Args: # categories (str): The category of the joke. ONLY use this if the user explicitly asks for a specific category. It MUST be one of: 'Any', 'Programming', 'Misc', 'Pun', 'Dark', 'Spooky', 'Christmas'. # lang (str): Language code for the joke (e.g., 'pt' for Portuguese). Only use if the user requests another language. # blacklistFlags (str | None): Comma-separated flags to exclude: 'nsfw', 'religious', 'political', 'racist', 'sexist', 'explicit'. Only use if requested. # safe_mode (bool): Defaults to True. Set to False only if the user explicitly wants potentially unsafe jokes. # type (str | None): 'single' or 'twopart'. Only set if user specifies. # contains (str | None): A substring the joke must include. Only set if requested. # idRange (str | None): Specific ID or range (e.g., '10-50'). Only use if requested. # amount (int): Number of jokes to fetch (1–10). Only change if the user asks for multiple jokes. # Returns: # A list of jokes (as strings). # """ # url = f"https://v2.jokeapi.dev/joke/{categories}" # params: dict[str, str | int | bool] = { # "format": "json", # "lang": lang, # "amount": amount # } # if blacklistFlags: # params["blacklistFlags"] = blacklistFlags # if safe_mode: # params["safe-mode"] = "" # if type: # params["type"] = type # if contains: # params["contains"] = contains # if idRange: # params["idRange"] = idRange # try: # resp = requests.get(url, params=params) # resp.raise_for_status() # data = resp.json() # if data.get("error"): # return [f"JokeAPI error: {data.get('message', 'Unknown error')}"] # def extract(item: dict): # if item.get("type") == "single": # return item["joke"] # else: # return f"{item['setup']} {item['delivery']}" # if amount > 1: # jokes = [extract(j) for j in data.get("jokes", [])] # else: # jokes = [extract(data)] # return jokes # except requests.exceptions.RequestException as e: # return [f"Network error: {e}"] # # Tool 2: Sentiment Analysis # def sentiment_analysis(text: str) -> str: # """ # Analyzes the sentiment of a given text using TextBlob. # Args: # text (str): The text to analyze. Must not be empty. # Returns: # A JSON string with: # - polarity: -1 (negative) to 1 (positive) # - subjectivity: 0 (objective) to 1 (subjective) # - assessment: 'positive', 'negative', or 'neutral' # """ # if not text: # return json.dumps({"error": "Input text cannot be empty."}) # blob = TextBlob(text) # polarity = round(blob.sentiment.polarity, 2) # subjectivity = round(blob.sentiment.subjectivity, 2) # if polarity > 0.1: # assessment = "positive" # elif polarity < -0.1: # assessment = "negative" # else: # assessment = "neutral" # return json.dumps({ # "polarity": polarity, # "subjectivity": subjectivity, # "assessment": assessment # }, indent=2) # # Tool 3: Prompt Optimization # def ask_llm(user_input: str) -> str: # """ # Optimizes a user‑provided prompt for better results in commercial LLMs by rewriting it using the Groq chat endpoint. # Args: # user_input (str): The original prompt to optimize. # Returns: # A single string containing the optimized prompt. # """ # client = Groq(api_key=os.getenv("GROQ_API_KEY")) # resp = client.chat.completions.create( # model="llama-3.3-70b-versatile", # messages=[ # { # "role": "system", # "content": ( # "You are a prompt‑engineering expert. The user will give you " # "simple prompts, and you should rewrite them so they get better " # "results from commercial web‑based LLMs. Only return the optimized prompt." # ) # }, # {"role": "user", "content": user_input}, # ], # ) # return resp.choices[0].message.content # # --- Gradio Interface Setup --- # # Sentiment Analysis interface # sentiment_interface = gr.Interface( # fn=sentiment_analysis, # inputs=gr.Textbox(lines=5, placeholder="Enter text here..."), # outputs=gr.JSON(), # api_name="sentiment_analysis", # title="Sentiment Analysis Tool", # description="Analyzes the sentiment of a piece of text." # ) # # Joke Generation interface # joke_interface = gr.Interface( # fn=joke_generation, # inputs=[ # gr.Textbox( # label="Categories", # value="Any", # info="Any, Programming, Misc, Pun, Dark, Spooky, Christmas" # ), # gr.Dropdown( # label="Language", # choices=["en", "cs", "de", "es", "fr", "pt"], # value="en" # ), # gr.CheckboxGroup( # label="Blacklist Flags", # choices=["nsfw", "religious", "political", "racist", "sexist", "explicit"] # ), # gr.Checkbox(label="Safe Mode", value=True), # gr.Radio( # label="Joke Type", # choices=["single", "twopart"] # ), # gr.Textbox(label="Contains"), # gr.Textbox(label="ID Range"), # gr.Slider( # label="Amount", # minimum=1, maximum=10, step=1, value=1 # ), # ], # outputs=gr.JSON(), # api_name="joke_generation", # title="Joke Generation Tool", # description=( # "Fetches jokes from JokeAPI using various filters. " # "For a simple joke, just click Submit without changing any fields." # ) # ) # # Prompt Optimization interface # prompt_interface = gr.Interface( # fn=ask_llm, # inputs=gr.Textbox(lines=5, placeholder="Enter prompt to optimize..."), # outputs=gr.Textbox(label="Optimized Prompt"), # api_name="ask_llm", # title="Prompt Optimization Tool", # description="Rewrites user prompts to improve results from commercial LLMs." # ) # # Combine into a tabbed demo # demo = gr.TabbedInterface( # [joke_interface, sentiment_interface, prompt_interface], # ["Joke Generation", "Sentiment Analysis", "Prompt Optimization"] # ) # if __name__ == "__main__": # demo.launch(mcp_server=True)