stackConsult commited on
Commit
824cdbc
Β·
verified Β·
1 Parent(s): 9cec6dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +287 -4
app.py CHANGED
@@ -1,7 +1,290 @@
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
1
+ """Vendor-Neutral Smolagents Fork - Main Application
2
+
3
+ This is the main Gradio UI application that integrates CSV-driven agent tools.
4
+ Designed to be vendor-neutral and work with various LLM backends.
5
+ """
6
+
7
  import gradio as gr
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+ from dotenv import load_dotenv
12
+
13
+ # Add smolagents to path
14
+ sys.path.insert(0, str(Path(__file__).parent / 'smolagents'))
15
+
16
+ try:
17
+ from tools import CSVToolHandler, CSVDataHandler, register_csv_tools
18
+ except ImportError as e:
19
+ print(f"Warning: Could not import tools module: {e}")
20
+ print("Some features may not be available.")
21
+ CSVToolHandler = None
22
+ CSVDataHandler = None
23
+ register_csv_tools = None
24
+
25
+ # Load environment variables
26
+ load_dotenv()
27
+
28
+ # Configuration
29
+ CSV_TOOLS_PATH = os.getenv('CSV_TOOLS_PATH', './tools.csv')
30
+ CSV_DATA_DIR = os.getenv('CSV_DATA_DIR', './data')
31
+ AGENT_BACKEND = os.getenv('AGENT_BACKEND', 'huggingface')
32
+ AGENT_MODEL_NAME = os.getenv('AGENT_MODEL_NAME', 'HuggingFaceH4/zephyr-7b-beta')
33
+
34
+ # Initialize CSV tool handler
35
+ tool_handler = None
36
+ available_tools = []
37
+
38
+ if CSVToolHandler:
39
+ try:
40
+ tool_handler = CSVToolHandler(CSV_TOOLS_PATH)
41
+ available_tools = tool_handler.get_tools()
42
+ print(f"Initialized with {len(available_tools)} CSV tools")
43
+ except Exception as e:
44
+ print(f"Error initializing CSV tool handler: {e}")
45
+
46
+
47
+ def process_query(query: str, tool_selection: str = None) -> str:
48
+ """Process user query with optional tool selection.
49
+
50
+ Args:
51
+ query: User input query
52
+ tool_selection: Optional tool to use
53
+
54
+ Returns:
55
+ Response string
56
+ """
57
+ if not query or not query.strip():
58
+ return "Please enter a query."
59
+
60
+ response_parts = []
61
+ response_parts.append(f"Query: {query}")
62
+ response_parts.append(f"Backend: {AGENT_BACKEND}")
63
+ response_parts.append(f"Model: {AGENT_MODEL_NAME}")
64
+
65
+ if tool_selection and tool_selection != "None":
66
+ response_parts.append(f"Selected Tool: {tool_selection}")
67
+
68
+ if tool_handler:
69
+ tool = tool_handler.get_tool_by_name(tool_selection)
70
+ if tool:
71
+ response_parts.append(f"Tool Description: {tool.get('description', 'N/A')}")
72
+
73
+ # List available tools
74
+ if available_tools:
75
+ response_parts.append(f"\nAvailable Tools ({len(available_tools)}):")
76
+ for tool in available_tools[:5]: # Show first 5
77
+ response_parts.append(f" - {tool.get('name', 'N/A')}: {tool.get('description', 'N/A')}")
78
+ if len(available_tools) > 5:
79
+ response_parts.append(f" ... and {len(available_tools) - 5} more")
80
+ else:
81
+ response_parts.append("\nNote: No CSV tools loaded. Add tools to tools.csv to enable tool support.")
82
+
83
+ response_parts.append("\n---")
84
+ response_parts.append("This is a vendor-neutral fork of Salesforce-Smolagents-AI.")
85
+ response_parts.append("CSV tool integration is active. Full agent capabilities coming soon!")
86
+
87
+ return "\n".join(response_parts)
88
+
89
+
90
+ def list_tools() -> str:
91
+ """List all available CSV tools."""
92
+ if not available_tools:
93
+ return "No tools available. Please add tool definitions to tools.csv."
94
+
95
+ tool_list = ["Available CSV Tools:"]
96
+ tool_list.append("=" * 50)
97
+
98
+ for i, tool in enumerate(available_tools, 1):
99
+ tool_list.append(f"\n{i}. {tool.get('name', 'Unknown')}")
100
+ tool_list.append(f" Description: {tool.get('description', 'N/A')}")
101
+ tool_list.append(f" Function: {tool.get('function', 'N/A')}")
102
+ tool_list.append(f" Parameters: {tool.get('parameters', 'N/A')}")
103
+
104
+ return "\n".join(tool_list)
105
+
106
+
107
+ def upload_csv_tools(file) -> str:
108
+ """Upload and process a CSV tools file."""
109
+ if file is None:
110
+ return "No file uploaded."
111
+
112
+ try:
113
+ # Read the uploaded file
114
+ if CSVDataHandler:
115
+ data = CSVDataHandler.read_csv(file.name)
116
+ return f"Successfully uploaded CSV with {len(data)} rows.\n" + str(data[:5])
117
+ else:
118
+ return "CSV tools module not available."
119
+ except Exception as e:
120
+ return f"Error processing CSV file: {str(e)}"
121
+
122
 
123
+ # Create Gradio interface
124
+ with gr.Blocks(title="Vendor-Neutral Smolagents Fork", theme=gr.themes.Soft()) as demo:
125
+ gr.Markdown("""
126
+ # πŸ€– Vendor-Neutral Smolagents Fork
127
+
128
+ A vendor-neutral implementation of agent tools with CSV-driven configuration.
129
+ Based on Salesforce-Smolagents-AI, designed for maximum flexibility and portability.
130
+
131
+ ### Features:
132
+ - πŸ“Š CSV-based tool definitions
133
+ - πŸ”§ Vendor-neutral LLM backend support
134
+ - πŸš€ Gradio UI for easy interaction
135
+ - πŸ”Œ Extensible architecture
136
+ """)
137
+
138
+ with gr.Tab("Agent Chat"):
139
+ gr.Markdown("### Interact with the Agent")
140
+
141
+ tool_names = ["None"] + [t.get('name', 'Unknown') for t in available_tools]
142
+
143
+ with gr.Row():
144
+ query_input = gr.Textbox(
145
+ label="Your Query",
146
+ placeholder="Ask me anything or request a tool action...",
147
+ lines=3
148
+ )
149
+
150
+ with gr.Row():
151
+ tool_dropdown = gr.Dropdown(
152
+ choices=tool_names,
153
+ label="Select Tool (Optional)",
154
+ value="None"
155
+ )
156
+
157
+ with gr.Row():
158
+ submit_btn = gr.Button("Submit", variant="primary")
159
+ clear_btn = gr.Button("Clear")
160
+
161
+ output = gr.Textbox(
162
+ label="Response",
163
+ lines=10,
164
+ interactive=False
165
+ )
166
+
167
+ submit_btn.click(
168
+ fn=process_query,
169
+ inputs=[query_input, tool_dropdown],
170
+ outputs=output
171
+ )
172
+
173
+ clear_btn.click(
174
+ fn=lambda: ("", "None", ""),
175
+ inputs=[],
176
+ outputs=[query_input, tool_dropdown, output]
177
+ )
178
+
179
+ with gr.Tab("Tool Management"):
180
+ gr.Markdown("### CSV Tool Configuration")
181
+
182
+ list_tools_btn = gr.Button("List Available Tools")
183
+ tools_output = gr.Textbox(
184
+ label="Tools",
185
+ lines=15,
186
+ interactive=False
187
+ )
188
+
189
+ list_tools_btn.click(
190
+ fn=list_tools,
191
+ inputs=[],
192
+ outputs=tools_output
193
+ )
194
+
195
+ gr.Markdown("### Upload CSV Tools")
196
+ gr.Markdown("Upload a CSV file with columns: name, description, function, parameters")
197
+
198
+ csv_upload = gr.File(
199
+ label="Upload CSV File",
200
+ file_types=[".csv"]
201
+ )
202
+
203
+ upload_output = gr.Textbox(
204
+ label="Upload Status",
205
+ lines=5,
206
+ interactive=False
207
+ )
208
+
209
+ csv_upload.change(
210
+ fn=upload_csv_tools,
211
+ inputs=csv_upload,
212
+ outputs=upload_output
213
+ )
214
+
215
+ with gr.Tab("Configuration"):
216
+ gr.Markdown("### System Configuration")
217
+
218
+ with gr.Row():
219
+ with gr.Column():
220
+ gr.Markdown(f"**Backend:** {AGENT_BACKEND}")
221
+ gr.Markdown(f"**Model:** {AGENT_MODEL_NAME}")
222
+ gr.Markdown(f"**CSV Tools Path:** {CSV_TOOLS_PATH}")
223
+ gr.Markdown(f"**CSV Data Dir:** {CSV_DATA_DIR}")
224
+
225
+ gr.Markdown("""
226
+ ### Setup Instructions
227
+
228
+ 1. Copy `smolagents/.env.sample` to `smolagents/.env`
229
+ 2. Configure your preferred LLM backend and API keys
230
+ 3. Create a `tools.csv` file with your tool definitions
231
+ 4. Use the Tool Management tab to verify your tools are loaded
232
+
233
+ ### CSV Tools Format
234
+
235
+ Your `tools.csv` should have these columns:
236
+ - `name`: Unique tool name
237
+ - `description`: What the tool does
238
+ - `function`: Function identifier or code
239
+ - `parameters`: Parameter specification (e.g., "query:str,limit:int")
240
+ """)
241
+
242
+ with gr.Tab("About"):
243
+ gr.Markdown("""
244
+ ### About This Project
245
+
246
+ This is a **vendor-neutral fork** of Salesforce's Smolagents-AI, designed to provide:
247
+
248
+ - 🌐 **Vendor Neutrality**: Works with any LLM provider (OpenAI, Anthropic, HuggingFace, local models, etc.)
249
+ - πŸ“Š **CSV-Driven Configuration**: Easy tool management through CSV files
250
+ - πŸ”§ **Extensibility**: Simple architecture for adding new capabilities
251
+ - πŸš€ **Production Ready**: Built with best practices and clean code
252
+
253
+ ### Key Components
254
+
255
+ - `smolagents/tools.py`: CSV tool handlers and registration
256
+ - `smolagents/.env.sample`: Configuration template
257
+ - `app.py`: Gradio UI (this file)
258
+ - `requirements.txt`: Minimal dependencies
259
+
260
+ ### Repository Structure
261
+
262
+ ```
263
+ β”œβ”€β”€ smolagents/
264
+ β”‚ β”œβ”€β”€ tools.py # CSV tool support
265
+ β”‚ └── .env.sample # Configuration template
266
+ β”œβ”€β”€ app.py # Main Gradio application
267
+ β”œβ”€β”€ requirements.txt # Dependencies
268
+ β”œβ”€β”€ tools.csv # Tool definitions (create this)
269
+ └── README.md # Documentation
270
+ ```
271
+
272
+ ### Next Steps
273
+
274
+ 1. Create your `tools.csv` file with tool definitions
275
+ 2. Configure your `.env` file with API keys
276
+ 3. Test the agent with your custom tools
277
+ 4. Extend with additional capabilities as needed
278
+
279
+ ---
280
+
281
+ Built with ❀️ for the AI agent community
282
+ """)
283
 
284
+ # Launch the app
285
+ if __name__ == "__main__":
286
+ demo.launch(
287
+ server_name=os.getenv('GRADIO_SERVER_HOST', '0.0.0.0'),
288
+ server_port=int(os.getenv('GRADIO_SERVER_PORT', 7860)),
289
+ share=False
290
+ )