CultriX commited on
Commit
038f212
·
verified ·
1 Parent(s): 21f5be1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -107
app.py CHANGED
@@ -1,112 +1,108 @@
1
- import gradio as gr
2
  import os
3
- from dotenv import load_dotenv
4
-
5
- # Import necessary functions/variables from run.py
6
- from run import create_agent
7
-
8
- load_dotenv()
9
-
10
- CONFIG_FILE = ".user_config.env"
11
-
12
-
13
- def save_env_vars_to_file(env_vars):
14
- """Saves environment variables to a file."""
15
- print("[DEBUG] Saving user config to file")
16
- with open(CONFIG_FILE, "w") as f:
17
- for key, value in env_vars.items():
18
- f.write(f"{key}={value}\n")
19
-
20
-
21
- def launch_interface():
22
- """Launches the Gradio interface for configuring and running the agent."""
23
-
24
- def setup_agent(question, model_id, hf_token, serpapi_key, use_custom_endpoint,
25
- custom_api_endpoint, custom_api_key, search_provider, search_api_key, custom_search_url):
26
- """Sets up the agent with the given configuration and runs it with the provided question."""
27
- print("[DEBUG] Setting up agent with input question:", question)
28
-
29
- if question.strip() == "":
30
- return "Please enter a question."
31
-
32
- endpoint = custom_api_endpoint if use_custom_endpoint else None
33
- api_key = custom_api_key if use_custom_endpoint else None
34
-
35
- save_env_vars_to_file({
36
- "HF_TOKEN": hf_token,
37
- "SERPAPI_API_KEY": serpapi_key,
38
- })
39
-
40
- print("[DEBUG] Instantiating agent with UI configuration")
41
- agent = create_agent(
42
- model_id=model_id,
43
- hf_token=hf_token,
44
- serpapi_key=serpapi_key,
45
- custom_api_endpoint=endpoint,
46
- custom_api_key=api_key,
47
- search_provider=search_provider,
48
- search_api_key=search_api_key,
49
- custom_search_url=custom_search_url
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  )
51
 
52
- return agent.run(question)
53
-
54
- with gr.Blocks(theme=gr.themes.Base(), css=".gr-box { border-radius: 15px; padding: 20px; }") as demo:
55
- gr.Markdown("# 🤖 SmolAgent Configurable Interface")
56
-
57
- with gr.Row():
58
- with gr.Column(scale=2):
59
- question = gr.Textbox(label="🧠 Question", placeholder="Ask me anything...")
60
- model_id = gr.Textbox(value="gpt-4o-mini", label="🧬 Model ID")
61
- hf_token = gr.Textbox(value=os.getenv("HF_TOKEN", ""), label="🔑 HuggingFace Token", type="password")
62
- serpapi_key = gr.Textbox(value=os.getenv("SERPAPI_API_KEY", ""), label="🔍 Serper API Key",
63
- type="password", visible=True)
64
- use_custom_endpoint = gr.Checkbox(label="🌐 Use Custom API Endpoint")
65
- custom_api_endpoint = gr.Textbox(label="🔌 Custom API Endpoint URL",
66
- placeholder="https://your-api-endpoint.com", visible=False)
67
- custom_api_key = gr.Textbox(label="🔐 Custom API Endpoint Key", type="password", visible=False)
68
- search_provider = gr.Dropdown(label="🔎 Search Provider", choices=["serper", "searxng"], value="serper")
69
- search_api_key = gr.Textbox(label="🔑 Search Provider API Key (optional)", type="password",
70
- visible=False)
71
- custom_search_url = gr.Textbox(label="🌐 Custom SearxNG Instance URL",
72
- placeholder="https://your-searxng-instance/search", visible=False)
73
- submit_btn = gr.Button("🚀 Run Agent")
74
-
75
- with gr.Column(scale=1):
76
- output = gr.Textbox(label="📤 Answer", lines=15)
77
-
78
-
79
- def update_search_visibility(provider):
80
- """Updates the visibility of search-related textboxes based on the selected search provider."""
81
- return {
82
- serpapi_key: gr.update(visible=(provider == "serper")),
83
- custom_search_url: gr.update(visible=(provider == "searxng")),
84
- search_api_key: gr.update(visible=(provider == "searxng")),
85
- }
86
-
87
-
88
- def update_custom_endpoint_visibility(checked):
89
- """Updates the visibility of custom API endpoint textboxes based on the checkbox state."""
90
- return {
91
- custom_api_endpoint: gr.update(visible=checked),
92
- custom_api_key: gr.update(visible=checked),
93
- }
94
-
95
-
96
- search_provider.change(fn=update_search_visibility, inputs=search_provider,
97
- outputs=[serpapi_key, custom_search_url, search_api_key])
98
- use_custom_endpoint.change(fn=update_custom_endpoint_visibility, inputs=use_custom_endpoint,
99
- outputs=[custom_api_endpoint, custom_api_key])
100
-
101
- submit_btn.click(fn=setup_agent,
102
- inputs=[question, model_id, hf_token, serpapi_key,
103
- use_custom_endpoint, custom_api_endpoint, custom_api_key,
104
- search_provider, search_api_key, custom_search_url],
105
- outputs=output)
106
-
107
- print("[DEBUG] Launching Gradio interface")
108
- demo.launch()
109
-
110
 
111
  if __name__ == "__main__":
112
- launch_interface()
 
 
 
1
  import os
2
+ import gradio as gr
3
+ from run import create_agent, log_formatter, MODEL_CONFIGS
4
+ import io
5
+ import logging
6
+ import contextlib
7
+
8
+ # Simple dark theme styling.
9
+ CSS = """
10
+ body {
11
+ background-color: #2c2c2c;
12
+ color: #ffffff;
13
+ }
14
+ .gradio-container {
15
+ background-color: #3a3a3a;
16
+ border-radius: 10px;
17
+ padding: 20px;
18
+ }
19
+ h1, h2, h3 {
20
+ color: #79c0ff;
21
+ }
22
+ """
23
+
24
+ def set_keys(openai_api_key, serper_api_key, hf_token, gemini_api_key, groq_api_key):
25
+ os.environ["OPENAI_API_KEY"] = openai_api_key
26
+ os.environ["SERPER_API_KEY"] = serper_api_key
27
+ os.environ["HF_TOKEN"] = hf_token
28
+ os.environ["GEMINI_API_KEY"] = gemini_api_key
29
+ os.environ["GROQ_API_KEY"] = groq_api_key
30
+ return "API keys have been updated successfully! Please restart the agent for changes to take effect."
31
+
32
+ def get_answer(question, model_name):
33
+ log_buffer = io.StringIO()
34
+ stdout_buffer = io.StringIO()
35
+ stream_handler = logging.StreamHandler(log_buffer)
36
+ stream_handler.setFormatter(log_formatter)
37
+ root_logger = logging.getLogger()
38
+ root_logger.setLevel(logging.DEBUG)
39
+ root_logger.addHandler(stream_handler)
40
+
41
+ conversation = []
42
+ try:
43
+ agent = create_agent(model_name=model_name)
44
+ answer = agent.run(question)
45
+ if isinstance(answer, str):
46
+ conversation = [
47
+ {"role": "user", "content": question},
48
+ {"role": "assistant", "content": answer}
49
+ ]
50
+ else:
51
+ result = ""
52
+ for chunk in answer:
53
+ result += chunk
54
+ conversation = [
55
+ {"role": "user", "content": question},
56
+ {"role": "assistant", "content": result}
57
+ ]
58
+ except Exception as e:
59
+ conversation = [
60
+ {"role": "user", "content": question},
61
+ {"role": "assistant", "content": f"An error occurred: {e}"}
62
+ ]
63
+ finally:
64
+ root_logger.removeHandler(stream_handler)
65
+ stream_handler.close()
66
+ logs = log_buffer.getvalue()
67
+ return conversation, f"```\n{stdout_buffer.getvalue()}\n{logs}\n```"
68
+
69
+ def build_app():
70
+ with gr.Blocks(css=CSS) as demo:
71
+ # Title and header.
72
+ gr.HTML("<h1>SmolAgents Open Deep Search 🥳</h1>")
73
+ gr.Markdown("## Enhanced Agent UI")
74
+
75
+ # Configuration Accordion.
76
+ with gr.Accordion("Configuration (Click to Expand)", open=False):
77
+ openai_field = gr.Textbox(label="OPENAI_API_KEY", type="password", placeholder="Enter your OpenAI API key")
78
+ serper_field = gr.Textbox(label="SERPER_API_KEY", type="password", placeholder="Enter your Serper API key")
79
+ hf_field = gr.Textbox(label="HF_TOKEN", type="password", placeholder="Enter your Hugging Face Token")
80
+ gemini_field = gr.Textbox(label="GEMINI_API_KEY", type="password", placeholder="Enter your Gemini API key")
81
+ groq_field = gr.Textbox(label="GROQ_API_KEY", type="password", placeholder="Enter your Groq API key")
82
+ update_btn = gr.Button("Update Keys")
83
+ status_box = gr.Markdown("*(No keys set yet)*")
84
+ update_btn.click(fn=set_keys, inputs=[openai_field, serper_field, hf_field, gemini_field, groq_field], outputs=status_box)
85
+
86
+ # Placeholder for agent logs.
87
+ log_markdown = gr.Markdown(label="Agent Logs")
88
+
89
+ gr.Markdown("### Select a model and ask your question below:")
90
+ model_names = list(MODEL_CONFIGS.keys())
91
+ model_dropdown = gr.Dropdown(choices=model_names, label="Select Model", value="o1", allow_custom_value=True)
92
+ question_input = gr.Textbox(label="Your Question", placeholder="Enter your question here...")
93
+ submit_btn = gr.Button("Get Answer")
94
+ # Use Chatbot component with type "messages" for OpenAI-style dict format.
95
+ chatbot = gr.Chatbot(label="Answer", type="messages")
96
+
97
+ # Connect the answer function.
98
+ submit_btn.click(
99
+ fn=get_answer,
100
+ inputs=[question_input, model_dropdown],
101
+ outputs=[chatbot, log_markdown]
102
  )
103
 
104
+ return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  if __name__ == "__main__":
107
+ demo = build_app()
108
+ demo.launch(server_name="0.0.0.0")