File size: 12,682 Bytes
bd97c5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env python3
"""
Hugging Face Spaces frontend for UniversalAPIAgentTool
Connects to Modal Labs backend for API execution
"""

import gradio as gr
import requests
import json
import time
from typing import Dict, Any, Optional

# Modal backend URL (will be updated after deployment)
MODAL_BACKEND_URL = "https://jomasego--execute-api-call.modal.run"

def execute_api_call_via_modal(
    base_url: str,
    endpoint: str,
    method: str = "GET",
    headers: str = "",
    params: str = "",
    json_body: str = "",
    timeout: int = 30
) -> tuple:
    """
    Execute API call via Modal Labs backend
    """
    try:
        # Prepare request data for Modal backend
        request_data = {
            "base_url": base_url,
            "endpoint": endpoint,
            "method": method,
            "headers": headers,
            "params": params,
            "json_body": json_body,
            "timeout": timeout
        }
        
        # Call Modal backend
        start_time = time.time()
        response = requests.post(
            MODAL_BACKEND_URL,
            json=request_data,
            timeout=60  # Give Modal more time
        )
        modal_execution_time = time.time() - start_time
        
        if response.status_code == 200:
            result = response.json()
            
            # Format the response for display
            status_code = result.get("status_code", 0)
            response_headers = result.get("response_headers", {})
            response_body = result.get("response_body", "")
            execution_time = result.get("execution_time", 0.0)
            error_message = result.get("error_message")
            
            # Create formatted output
            output_lines = [
                f"πŸš€ **API Call Executed via Modal Labs**",
                f"⏱️ **Execution Time**: {execution_time:.3f}s (Modal: {modal_execution_time:.3f}s)",
                f"πŸ“Š **Status Code**: {status_code}",
                ""
            ]
            
            if error_message:
                output_lines.extend([
                    f"❌ **Error**: {error_message}",
                    ""
                ])
            
            if response_headers:
                output_lines.extend([
                    "πŸ“‹ **Response Headers**:",
                    "```json",
                    json.dumps(response_headers, indent=2),
                    "```",
                    ""
                ])
            
            if response_body:
                output_lines.extend([
                    "πŸ“„ **Response Body**:",
                    "```json" if response_body.strip().startswith(('{', '[')) else "```",
                    response_body,
                    "```"
                ])
            
            return "\n".join(output_lines), f"Status: {status_code}"
            
        else:
            return f"❌ **Modal Backend Error**\nStatus: {response.status_code}\nResponse: {response.text}", "Modal Error"
            
    except requests.exceptions.Timeout:
        return "❌ **Timeout Error**\nModal backend request timed out", "Timeout"
    except requests.exceptions.ConnectionError:
        return "❌ **Connection Error**\nCannot connect to Modal backend", "Connection Error"
    except Exception as e:
        return f"❌ **Error**\n{str(e)}", "Error"

def create_gradio_interface():
    """Create the Gradio interface"""
    
    # Example configurations
    examples = [
        [
            "https://api.coingecko.com",
            "/api/v3/simple/price",
            "GET",
            "",
            '{"ids": "bitcoin,ethereum", "vs_currencies": "usd"}',
            "",
            30
        ],
        [
            "https://api.github.com",
            "/repos/microsoft/vscode",
            "GET",
            "",
            "",
            "",
            30
        ],
        [
            "https://jsonplaceholder.typicode.com",
            "/posts",
            "POST",
            '{"Content-Type": "application/json"}',
            "",
            '{"title": "Test Post", "body": "This is a test", "userId": 1}',
            30
        ]
    ]
    
    with gr.Blocks(
        title="UniversalAPIAgentTool - HF Spaces + Modal Labs",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 1200px !important;
        }
        .tab-nav {
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        }
        """
    ) as interface:
        
        gr.Markdown("""
        # πŸš€ UniversalAPIAgentTool
        
        **Powered by Hugging Face Spaces + Modal Labs**
        
        Universal MCP tool that enables AI agents to access any REST API. This frontend runs on HF Spaces while the backend executes on Modal Labs for optimal performance.
        """)
        
        with gr.Tab("πŸ”§ API Executor"):
            gr.Markdown("### Execute HTTP requests to any REST API")
            
            with gr.Row():
                with gr.Column(scale=2):
                    base_url = gr.Textbox(
                        label="Base URL",
                        placeholder="https://api.example.com",
                        value="https://api.coingecko.com"
                    )
                    endpoint = gr.Textbox(
                        label="Endpoint",
                        placeholder="/api/v1/resource",
                        value="/api/v3/simple/price"
                    )
                    
                with gr.Column(scale=1):
                    method = gr.Dropdown(
                        choices=["GET", "POST", "PUT", "DELETE", "PATCH"],
                        value="GET",
                        label="HTTP Method"
                    )
                    timeout = gr.Slider(
                        minimum=5,
                        maximum=120,
                        value=30,
                        step=5,
                        label="Timeout (seconds)"
                    )
            
            with gr.Row():
                headers = gr.Textbox(
                    label="Headers (JSON)",
                    placeholder='{"Authorization": "Bearer token", "Content-Type": "application/json"}',
                    lines=2
                )
                params = gr.Textbox(
                    label="Query Parameters (JSON)",
                    placeholder='{"key": "value", "limit": 10}',
                    lines=2,
                    value='{"ids": "bitcoin,ethereum", "vs_currencies": "usd"}'
                )
            
            json_body = gr.Textbox(
                label="JSON Body (for POST/PUT)",
                placeholder='{"name": "value", "data": [1, 2, 3]}',
                lines=3
            )
            
            with gr.Row():
                execute_btn = gr.Button("πŸš€ Execute API Call", variant="primary", size="lg")
                clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
            
            with gr.Row():
                with gr.Column(scale=3):
                    output = gr.Markdown(label="Response")
                with gr.Column(scale=1):
                    status = gr.Textbox(label="Status", interactive=False)
            
            # Examples
            gr.Markdown("### πŸ“ Quick Examples")
            gr.Examples(
                examples=examples,
                inputs=[base_url, endpoint, method, headers, params, json_body, timeout],
                label="Try these examples"
            )
        
        with gr.Tab("πŸ“š Documentation"):
            gr.Markdown("""
            ## 🎯 How to Use
            
            1. **Base URL**: The root URL of the API (e.g., `https://api.github.com`)
            2. **Endpoint**: The specific path (e.g., `/repos/owner/repo`)
            3. **Method**: HTTP method (GET, POST, PUT, DELETE, PATCH)
            4. **Headers**: Authentication and content type headers as JSON
            5. **Parameters**: URL query parameters as JSON
            6. **JSON Body**: Request payload for POST/PUT requests
            
            ## πŸ” Authentication Examples
            
            ### API Key in Headers
            ```json
            {"X-API-Key": "your-api-key-here"}
            ```
            
            ### Bearer Token
            ```json
            {"Authorization": "Bearer your-token-here"}
            ```
            
            ### Basic Auth (base64 encoded)
            ```json
            {"Authorization": "Basic dXNlcjpwYXNz"}
            ```
            
            ## 🌐 Example APIs to Try
            
            ### πŸͺ™ Cryptocurrency Prices (CoinGecko)
            - **URL**: `https://api.coingecko.com`
            - **Endpoint**: `/api/v3/simple/price`
            - **Params**: `{"ids": "bitcoin", "vs_currencies": "usd"}`
            
            ### πŸ™ GitHub Repository Info
            - **URL**: `https://api.github.com`
            - **Endpoint**: `/repos/microsoft/vscode`
            - **Method**: GET
            
            ### 🌍 Country Information
            - **URL**: `https://restcountries.com`
            - **Endpoint**: `/v3.1/name/germany`
            - **Method**: GET
            
            ### πŸ“ Test POST Requests
            - **URL**: `https://jsonplaceholder.typicode.com`
            - **Endpoint**: `/posts`
            - **Method**: POST
            - **Headers**: `{"Content-Type": "application/json"}`
            - **Body**: `{"title": "Test", "body": "Content", "userId": 1}`
            
            ## πŸ€– For AI Agents (MCP)
            
            This tool can be used by AI agents via MCP with this function call:
            
            ```json
            {
              "tool_name": "UniversalAPIAgentTool",
              "function_name": "execute_api_call",
              "parameters": {
                "base_url": "https://api.example.com",
                "endpoint": "/v1/resource",
                "method": "GET",
                "headers": {"Authorization": "Bearer token"},
                "params": {"query": "value"},
                "json_body": {"data": "value"}
              }
            }
            ```
            
            ## πŸ—οΈ Architecture
            
            - **Frontend**: Hugging Face Spaces (Gradio)
            - **Backend**: Modal Labs (Python + FastAPI)
            - **Benefits**: Scalable, fast, and reliable API execution
            
            ## πŸ† Hackathon Project
            
            Built for the **Agents & MCP Hackathon** to demonstrate how MCP can expand AI agent capabilities through universal API access.
            """)
        
        with gr.Tab("πŸ”§ Backend Status"):
            gr.Markdown(f"""
            ## πŸ–₯️ Modal Labs Backend
            
            **Backend URL**: `{MODAL_BACKEND_URL}`
            
            The backend is hosted on Modal Labs for optimal performance and scalability.
            """)
            
            def check_backend_health():
                try:
                    health_url = MODAL_BACKEND_URL.replace("execute-api-call", "health-check")
                    response = requests.get(health_url, timeout=10)
                    if response.status_code == 200:
                        data = response.json()
                        return f"βœ… **Backend Status**: Healthy\n**Service**: {data.get('service', 'Unknown')}\n**Version**: {data.get('version', 'Unknown')}"
                    else:
                        return f"⚠️ **Backend Status**: Unhealthy (Status: {response.status_code})"
                except Exception as e:
                    return f"❌ **Backend Status**: Error - {str(e)}"
            
            health_output = gr.Markdown()
            health_btn = gr.Button("πŸ” Check Backend Health")
            health_btn.click(fn=check_backend_health, outputs=health_output)
        
        # Event handlers
        execute_btn.click(
            fn=execute_api_call_via_modal,
            inputs=[base_url, endpoint, method, headers, params, json_body, timeout],
            outputs=[output, status]
        )
        
        def clear_inputs():
            return "", "", "GET", "", "", "", 30
        
        clear_btn.click(
            fn=clear_inputs,
            outputs=[base_url, endpoint, method, headers, params, json_body, timeout]
        )
    
    return interface

if __name__ == "__main__":
    # Create and launch the interface
    interface = create_gradio_interface()
    interface.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )