Fine tuning tools 2 and 3
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420512338 unmodified lines42434425045462524748254495051522 unmodified lines555657263264265266267268269270271272585960616263646566676869707172737475765 unmodified lines82838428485862868788288899091922 unmodified lines9596972972982993003013023033049899100101102103104105106107108109110111112113114115116# import os# import requests# import json# import gradio as gr# from textblob import TextBlob# from groq import Groq
# # 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 prompt_optimizaiton(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=prompt_optimizaiton,# inputs=gr.Textbox(lines=5, placeholder="Enter prompt to optimize..."),# outputs=gr.Textbox(),# api_name="prompt_optimizaiton",# 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)
import osimport requestsimport json38 unmodified lines# Tool 2: Five Questions Analysis and Follow-Up Generationdef five_questions_analysis_and_followup_generation(user_input: str) -> str: """ Receives 5 questions and answers, analyzes what it is about and come up with 3 follow up questions to better understand the context Analyzes 5 question-answer pairs about a user's prompt requirements and generates 3 strategic follow-up questions to gather additional context for future better prompt creation. Args: user_input (str): A string containing 5 questions and answers. Must not be empty. user_input (str): A string containing exactly 5 questions and their corresponding answers related to the user's prompt requirements. Format should be clear Questioin and Answer pairs. Must not be empty. Returns: A single string containing 3 enumerated follow up questions. Three numbered follow-up questions (e.g.: 1. Foo...?, 2. Foo...?, 3. Foo...?) designed to elicit additional context that will improve future prompt creation. No additional commentary included. """ client = Groq(api_key=os.getenv("GROQ_API_KEY")) resp = client.chat.completions.create(2 unmodified lines { "role": "system", "content": ( "You are a prompt‑engineering expert. The user will give you " "5 questions and answers about the subject he wants to write a prompt." "You task is to analyses the questions and answers and produce 3 follow up" "questions to better understand the user context so in the future you will have" "More information to write a better prompt for the user." "Your final answer must be ONLY the 3 enumerated follow up questions, DO NOT ADD ANY EXTRA COMMENT." "Exemple of your final answer:" "1. Can you clarify your timeline?\n" "2. Who else is involved in this project?\n" "3. What would success look like in one sentence?" "You are a prompt-engineering expert specializing in context analysis. " "The user will provide you with 5 questions and answers about a subject " "they want to create a prompt for. " "Your task is to analyze these question-answer pairs to understand the user's needs, " "then generate exactly 3 strategic follow-up questions that will gather " "the most valuable additional context for creating an optimal prompt. " "Focus on identifying gaps in information about scope, constraints, audience, " "desired outcomes, or specific requirements that weren't covered in the original 5 questions. " "Format your response as a numbered list (e.g.: 1. Foo...?, 2. Foo...?, 3. Foo...?). " "Make questions specific, actionable, and directly relevant a future to prompt creation. " "IMPORTANT: Your response must contain ONLY the 3 numbered follow-up questions " "with no additional commentary, analysis, or explanation. " "Example format: " "1. What specific ...? " "2. Are there any ...? " "3. What does ...?" ) }, {"role": "user", "content": user_input},5 unmodified lines# Tool 3: Eight Questions Analysis and Prompt Generationdef eight_questions_analysis_and_prompt_generation(user_input: str) -> str: """ Receives 8 questions and answers from the user, analyzes what it is about, understands what the user wants and writes a prompt that summarizes the user demand in a text that later will be used by the user to ask for help from a commercial web‑based LLM. Analyzes 8 question-answer pairs to understand user requirements and generates a comprehensive, ready-to-use prompt for commercial LLM platforms. Args: user_input (str): A string containing 8 questions and answers. Must not be empty. user_input (str): A string containing exactly 8 questions and their corresponding answers that define the user's requirements, context, and desired outcomes. Format should be clear Questioin and Answer pairs. Must not be empty. Returns: A single string containing the optimized prompt based on the 8 questions and answers. A complete, optimized prompt that synthesizes all provided information into a clear, actionable request ready for copy-paste use with commercial LLMs (ChatGPT, Claude, etc.). No additional commentary included. """ client = Groq(api_key=os.getenv("GROQ_API_KEY")) resp = client.chat.completions.create(2 unmodified lines { "role": "system", "content": ( "You are a prompt‑engineering expert. The user will give you " "8 questions and answers about the subject he wants to write a prompt." "You task is to analyses the questions and answers and produce a detailed prompt" "so the user can later copy and paste it into a commercial web‑based LLM" "Your task is to basically understand the user demand from the 8 questions and answers" "And elaborate a good prompt about it to so the user can later" "Copy and paste the prompt to get help from a LLM" "Your final answer must be ONLY the final optimised prompt DO NOT ADD ANY EXTRA COMMENT." "You are a prompt-engineering expert specialized in comprehensive prompt creation. " "The user will provide you with 8 questions and answers that define their specific " "requirements, context, constraints, and desired outcomes. " "Your task is to analyze these Questioin and Answer pairs thoroughly to understand the user's " "complete request, then craft a detailed, well-structured prompt that captures " "all essential information. " "The final prompt should be optimized for commercial web-based LLMs (like ChatGPT, " "Claude, Gemini, etc.) and include: clear instructions, relevant context, " "specific requirements, and any constraints mentioned. " "Make the prompt self-contained so the user can copy and paste it directly " "without needing to provide additional context. " "Structure the prompt logically with clear sections if needed, and ensure " "it's specific enough to generate high-quality, targeted responses. " "IMPORTANT: Your response must contain ONLY the final optimized prompt " "with no introduction, explanation, or additional commentary. The prompt " "should be ready for immediate use." ) }, {"role": "user", "content": user_input},app.py+38-229