Download app.py from Jpreval/MrsJuJu: direct link, hf CLI and curl.
- Browser
- Download file 5.02 kB
-
https://huggingface.co/spaces/Jpreval/MrsJuJu/resolve/main/app.py
- Command line
-
hf download hf://spaces/Jpreval/MrsJuJu/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Jpreval/MrsJuJu/resolve/main/app.py
5.02 kB
| """ | |
| Build Your Own Agent β Created by Mrs. JuJu | |
| This prototype was developed by Julie Preval-Toussaint for educational and ethical agentic deployment. | |
| """ | |
| __author__ = "Julie Preval-Toussaint (Mrs. JuJu)" | |
| __version__ = "1.0.0" | |
| __copyright__ = "Β© 2025 Julie Preval-Toussaint. All rights reserved." | |
| # Step 2: User Data Setup (No Tavily key here) | |
| import gradio as gr | |
| from sentence_transformers import SentenceTransformer | |
| from sklearn.neighbors import NearestNeighbors | |
| from langgraph.graph import StateGraph | |
| import numpy as np | |
| import requests | |
| model = SentenceTransformer("all-MiniLM-L6-v2") | |
| # Default fallback data if user doesn't upload or type anything | |
| default_data = [ | |
| "Haiti is known for its vibrant art and music.", | |
| "MSIS Cohort 55 meets every Tuesday.", | |
| "Julie is a Program Analyst at MIA.", | |
| "Julie Preval Toussaint is the owner of this Agentic App" | |
| ] | |
| # This will be dynamically passed from Gradio later | |
| #4. Agent Logic: Decision Function + LangGraph Routing | |
| def tavily_search(query, key): | |
| url = "https://api.tavily.com/search" | |
| headers = {"Authorization": f"Bearer {key}"} | |
| payload = {"query": query, "max_results": 1} | |
| response = requests.post(url, json=payload, headers=headers) | |
| return response.json()["results"][0]["content"] | |
| def decide_tool(query, user_data, knn, tavily_key, threshold=0.65): | |
| query_vec = model.encode([query]) | |
| query_vec = query_vec / np.linalg.norm(query_vec) | |
| distances, indices = knn.kneighbors(query_vec) | |
| score = 1 - distances[0][0] | |
| if score >= threshold: | |
| return {"response": user_data[indices[0][0]], "use_web": False, "score": score} | |
| else: | |
| return {"response": tavily_search(query, tavily_key), "use_web": True, "score": score} | |
| # LangGraph routing | |
| def local_response_node(state): return {"response": state["response"]} | |
| def web_search_node(state): return {"response": state["response"]} | |
| # Define the state schema | |
| class AgentState: | |
| response: str | |
| use_web: bool | |
| score: float | |
| graph = StateGraph(AgentState) | |
| graph.add_node("local_response", local_response_node) | |
| graph.add_node("web_search", web_search_node) | |
| graph.set_entry_point("local_response") | |
| graph.add_conditional_edges("local_response", lambda s: "web_search" if s["use_web"] else None) | |
| agent = graph.compile() | |
| #5. Gradio UI: Query Box + Response Display + Disclaimer | |
| def chatbot_interface(tavily_key, user_file, typed_data, agent_name, query): | |
| # Step 1: Load user data | |
| if user_file is not None: | |
| user_data = user_file.read().decode("utf-8").split("\n") | |
| elif typed_data.strip(): | |
| user_data = typed_data.split("\n") | |
| else: | |
| user_data = [ | |
| "Haiti is known for its vibrant art and music.", | |
| "MSIS Cohort 55 meets every Tuesday.", | |
| "Julie is a Program Analyst at MIA.", | |
| "Julie Preval Toussaint is the owner of this Agentic App" | |
| ] | |
| # Step 2: Rebuild embeddings and KNN | |
| embeddings = model.encode(user_data) | |
| normalized_embeddings = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True) | |
| knn = NearestNeighbors(n_neighbors=1, metric="cosine") | |
| knn.fit(normalized_embeddings) | |
| # Step 3: Run decision logic | |
| query_vec = model.encode([query]) | |
| query_vec = query_vec / np.linalg.norm(query_vec) | |
| distances, indices = knn.kneighbors(query_vec) | |
| score = 1 - distances[0][0] | |
| if score >= 0.65: | |
| response = user_data[indices[0][0]] | |
| source = "Local" | |
| else: | |
| response = tavily_search(query, tavily_key) | |
| source = "Web" | |
| disclaimer = ( | |
| "\n\nThis response is generated by an AI assistant. " | |
| "Please verify important details independently. " | |
| "Use of this tool implies acceptance of all terms. " | |
| "Do not input illegal, offensive, or harmful content." | |
| ) | |
| return f"[{source} Answer from {agent_name}] {response}{disclaimer}" | |
| import gradio as gr | |
| gr.Interface( | |
| fn=chatbot_interface, | |
| inputs=[ | |
| gr.Textbox( | |
| label="π Step 1: Enter your free Tavily API key (get one at https://www.tavily.com)", | |
| type="password", | |
| placeholder="tvly-dev-xxxxxxxxxxxxxxxxxxxx" | |
| ), | |
| gr.File( | |
| label="π Step 2: Upload your data (optional)", | |
| file_types=[".txt", ".csv", ".pdf"] | |
| ), | |
| gr.Textbox( | |
| label="βοΈ Step 2a: Or type your custom facts", | |
| lines=4, | |
| placeholder="e.g., Our group is called Cohort 55. Julie likes blue. We meet on Tuesdays." | |
| ), | |
| gr.Textbox( | |
| label="π€ Step 3: Name your agent", | |
| placeholder="e.g., Haiti Explorer by Mrs. JuJu" | |
| ), | |
| gr.Textbox( | |
| label="π Step 4: Ask your question" | |
| ) | |
| ], | |
| outputs="text", | |
| title="πΊ Build Your Own Agent with Mrs. JuJu", | |
| description="Empower your own AI agent with custom data and queries. Created by Julie Preval Toussaint.", | |
| theme=gr.themes.Soft() | |
| ).launch(share=True, debug=True) | |