awacke1 commited on
Commit
3b51c72
Β·
verified Β·
1 Parent(s): 3b0df6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -100
app.py CHANGED
@@ -1,112 +1,69 @@
1
- import streamlit as st
2
- import os
3
- import glob
4
- import re
5
- import base64
6
- import pytz
7
- from datetime import datetime
8
  from transformers.agents import CodeAgent, ReactCodeAgent, ReactJsonAgent, load_tool
 
9
 
10
- # Page config
11
- st.set_page_config(page_title="🌳✨ AI Knowledge Tree Builder πŸ› οΈπŸ€“", page_icon="🌳", layout="wide")
12
- st.sidebar.markdown("""
13
- πŸŒ³πŸ€– **AI Knowledge Tree Builder**
14
- 1. πŸ“± Universal access
15
- 2. ⚑ Rapid builds (<2min)
16
- 3. πŸ”— Linked AI sources
17
- 4. 🎯 Lean core
18
- 5. 🧠 Shareable memory
19
- 6. πŸ‘€ Personalized
20
- 7. 🐦 Cloneable brevity
21
- """)
22
 
23
- # Initialize Agents
24
- tools = [load_tool("text-to-speech"), load_tool("image_question_answering")]
25
- agents = {
26
- "CodeCrafter": CodeAgent(tools=tools, system_prompt="Craft code like a pro! πŸ–₯️"),
27
- "StepSage": ReactCodeAgent(tools=tools, system_prompt="Step-by-step wisdom! 🧠"),
28
- "JsonJugger": ReactJsonAgent(tools=tools, system_prompt="JSON-powered antics! 🀑"),
29
- "OutlineOracle": ReactCodeAgent(tools=tools, system_prompt="Outline everything! πŸ“‹"),
30
- "ToolTitan": CodeAgent(tools=tools, system_prompt="List tools with swagger! πŸ”§"),
31
- "SpecSpinner": ReactJsonAgent(tools=tools, system_prompt="Spin specs with style! πŸ“œ"),
32
- "ImageImp": CodeAgent(tools=tools, system_prompt="Dream up image prompts! 🎨"),
33
- "VisualVortex": ReactCodeAgent(tools=tools, system_prompt="Generate visuals! πŸ–ΌοΈ"),
34
- "GlossGuru": ReactJsonAgent(tools=tools, system_prompt="Define terms with pizzazz! πŸ“–"),
35
- }
36
-
37
- # MoE Prompts mapped to agents
38
- moe_prompts = {
39
- "Create a python streamlit app.py...": "CodeCrafter",
40
- "Create a python gradio app.py...": "CodeCrafter",
41
- "Create a mermaid model...": "OutlineOracle",
42
- "Create a top three list of tools...": "ToolTitan",
43
- "Create a specification in markdown...": "SpecSpinner",
44
- "Create an image generation prompt...": "ImageImp",
45
- "Generate an image which describes...": "VisualVortex",
46
- "List top ten glossary terms...": "GlossGuru",
47
- "": "StepSage" # Default agent for blank selection
48
- }
49
 
50
- # Session state
51
- if 'selected_file' not in st.session_state:
52
- st.session_state.selected_file = None
53
- if 'view_mode' not in st.session_state:
54
- st.session_state.view_mode = 'view'
55
- if 'files' not in st.session_state:
56
- st.session_state.files = []
57
 
58
- # MoE Selection
59
- moe_options = list(moe_prompts.keys())
60
- selected_moe = st.selectbox("Pick an MoE Adventure! 🎲", moe_options, index=0, key="selected_moe")
61
 
62
- # Utility Functions (simplified for brevity, reusing yours where unchanged)
63
- def sanitize_filename(text):
64
- return re.sub(r'[^\w\s-]', ' ', text.strip())[:50]
 
 
 
65
 
66
- def generate_timestamp_filename(query):
67
- central = pytz.timezone('US/Central')
68
- now = datetime.now(central)
69
- return f"{now.strftime('%I%M%p %m%d%Y')} ({sanitize_filename(query)}).md"
70
-
71
- def save_ai_interaction(query, result, is_rerun=False):
72
- filename = generate_timestamp_filename(query)
73
- content = f"# {'Rerun' if is_rerun else 'Query'}: {query}\n\n## AI Response\n{result}"
74
- with open(filename, 'w', encoding='utf-8') as f:
75
- f.write(content)
76
- return filename
77
-
78
- def run_agent(task, agent_name):
79
- agent = agents[agent_name]
80
- if isinstance(agent, CodeAgent):
81
- return agent.run(task, return_generated_code=True)
82
- return agent.run(task)
83
 
84
- # Main App
85
- def main():
86
- st.markdown("### 🌳 AI Knowledge Tree Builder 🧠🌱 Let’s Grow Some Smarts!")
87
- query = st.text_input("Ask Away! πŸ€”", placeholder="E.g., 'Explain transformers!'")
88
-
89
- if query:
90
- agent_name = moe_prompts[selected_moe]
91
  try:
92
- result = run_agent(f"{selected_moe} {query}" if selected_moe else query, agent_name)
93
- st.markdown(f"πŸŽ‰ {agent_name} says: {result}")
94
- saved_file = save_ai_interaction(query, result)
95
- st.success(f"Saved to {saved_file}")
96
- st.session_state.selected_file = saved_file
 
97
  except Exception as e:
98
- st.error(f"😱 Oops! {e}")
 
99
 
100
- # File Management (simplified)
101
- st.sidebar.title("πŸ“ Files")
102
- md_files = sorted([f for f in glob.glob("*.md") if f.lower() != 'readme.md'])
103
- for file in md_files:
104
- st.sidebar.write(file)
105
- if st.sidebar.button(f"View {file}", key=f"v_{file}"):
106
- st.session_state.selected_file = file
107
- if st.session_state.selected_file:
108
- with open(st.session_state.selected_file, 'r') as f:
109
- st.markdown(f.read())
110
 
111
- if __name__ == "__main__":
112
- main()
 
1
+ import gradio as gr
 
 
 
 
 
 
2
  from transformers.agents import CodeAgent, ReactCodeAgent, ReactJsonAgent, load_tool
3
+ import random
4
 
5
+ # Custom tools since some built-ins are flaky
6
+ class WittyQuoteTool:
7
+ def __init__(self):
8
+ self.name = "witty_quote"
9
+ self.description = "Spouts a random witty ML quote! πŸ˜‚"
10
+ self.inputs = {}
11
+ self.output_type = str
 
 
 
 
 
12
 
13
+ def __call__(self):
14
+ quotes = ["'AI is just spicy statistics' - Unknown πŸ€“", "'The only limit is your GPU budget' - Me πŸ’Έ"]
15
+ return random.choice(quotes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ class MLDevTool:
18
+ def __init__(self):
19
+ self.name = "ml_dev_helper"
20
+ self.description = "Helps with ML dev tasks like coding or debugging! πŸ› οΈ"
21
+ self.inputs = {"task": {"type": "str", "description": "What ML task to assist with"}}
22
+ self.output_type = str
 
23
 
24
+ def __call__(self, task):
25
+ return f"🧠 Beep boop! Helping with: {task}. Tip: Always check your data first! πŸ“Š"
 
26
 
27
+ # Initialize 9 agents with stable tools
28
+ tools = [WittyQuoteTool(), MLDevTool()] # Dropped problematic built-ins
29
+ try:
30
+ tools.append(load_tool("speech_to_text")) # Safer built-in option
31
+ except Exception as e:
32
+ print(f"Skipping speech_to_text due to: {e}")
33
 
34
+ agents = {
35
+ "CodeWizard": CodeAgent(tools=tools, system_prompt="You're a coding genius! πŸ§™β€β™‚οΈ Write concise code."),
36
+ "StepByStep": ReactCodeAgent(tools=tools, system_prompt="Think step-by-step, oh wise one! πŸ€–"),
37
+ "JsonJester": ReactJsonAgent(tools=tools, system_prompt="JSON all the things! πŸ˜‚"),
38
+ "DataDiva": ReactCodeAgent(tools=tools, system_prompt="Clean that data, superstar! 🌟"),
39
+ "ModelMaestro": CodeAgent(tools=tools, system_prompt="Tune models like a pro! 🎻"),
40
+ "DebugDemon": ReactJsonAgent(tools=tools, system_prompt="Squash bugs with flair! πŸ‘Ύ"),
41
+ "DocDynamo": ReactCodeAgent(tools=tools, system_prompt="Write docs that dazzle! πŸ“œ"),
42
+ "VizVirtuoso": CodeAgent(tools=tools, system_prompt="Visualize like a boss! πŸ“ˆ"),
43
+ "DeployDaredevil": ReactJsonAgent(tools=tools, system_prompt="Deploy with guts! πŸš€"),
44
+ }
 
 
 
 
 
 
45
 
46
+ def run_ml_team(task):
47
+ outputs = []
48
+ for name, agent in agents.items():
 
 
 
 
49
  try:
50
+ if isinstance(agent, CodeAgent):
51
+ result = agent.run(task, return_generated_code=True)
52
+ outputs.append(f"πŸŽ‰ {name} says: Here's my code magic! ```python\n{result}\n```")
53
+ else:
54
+ result = agent.run(task)
55
+ outputs.append(f"πŸ”₯ {name} reacts: {result}")
56
  except Exception as e:
57
+ outputs.append(f"😱 {name} tripped over a wire: {str(e)}")
58
+ return "\n\n".join(outputs)
59
 
60
+ # Gradio UI
61
+ with gr.Blocks(title="ML Agent Party πŸŽ‰") as demo:
62
+ gr.Markdown("# ML Agent Party! πŸ€–πŸŽˆ\n9 Agents to Boost Your ML Game with Sass & Smarts!")
63
+ task_input = gr.Textbox(label="What's Your ML Quest? πŸ—‘οΈ", placeholder="E.g., 'Clean my data!'")
64
+ output = gr.Markdown(label="Agent Squad Response 🎀")
65
+ submit_btn = gr.Button("Unleash the Crew! πŸš€")
66
+ submit_btn.click(run_ml_team, inputs=task_input, outputs=output)
67
+ gr.Markdown("---\nBuilt with ❀️ & πŸ˜‚ by xAI's Grok & Transformers Agents")
 
 
68
 
69
+ demo.launch()