Spaces:
Runtime error
Runtime error
File size: 13,343 Bytes
888a013 de825cf 1dd5be6 888a013 24dfcbe 888a013 f3997bc 888a013 f3997bc 221b3be 888a013 6783989 888a013 6783989 888a013 1dd5be6 6783989 888a013 6783989 221b3be 6783989 888a013 1dd5be6 66f97a0 1dd5be6 221b3be 4740451 6783989 6017d5f 888a013 1dd5be6 888a013 f3997bc 9db0453 f3997bc 9db0453 de825cf f3997bc 3d29a11 f3997bc 221b3be f3997bc 221b3be 6783989 1dd5be6 fbb1d8b aad2281 f3997bc 6783989 f3997bc 6783989 f3997bc aad2281 7113c10 b5d2905 1dd5be6 6783989 1dd5be6 f3997bc 221b3be afa3e60 0065147 de825cf d9b54f7 f3997bc 221b3be f3997bc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | 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: <your key>
# # 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)
|