Spaces:
Sleeping
Sleeping
yellowgolfball commited on
Commit ·
ff26682
1
Parent(s): 68c1f7a
initial commit
Browse files- app.py +58 -0
- requirements.txt +2 -0
app.py
CHANGED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import atexit
|
| 4 |
+
|
| 5 |
+
from smolagents import InferenceClientModel, CodeAgent, MCPClient
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def create_agent_with_fallback():
|
| 9 |
+
"""Create agent with MCP tools if available, otherwise use basic tools"""
|
| 10 |
+
token = os.getenv("HUGGINGFACE_API_TOKEN") # use a generic env var name
|
| 11 |
+
if not token:
|
| 12 |
+
raise RuntimeError("HF_API_TOKEN environment variable not set.")
|
| 13 |
+
|
| 14 |
+
model = InferenceClientModel(token=token)
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
# Try to connect to MCP server
|
| 18 |
+
mcp_url = os.getenv("MCP_SERVER_URL", "https://trainhubai-mcp-sentiment.hf.space/gradio_api/mcp/sse")
|
| 19 |
+
mcp_client = MCPClient({"url": mcp_url})
|
| 20 |
+
tools = mcp_client.get_tools()
|
| 21 |
+
agent = CodeAgent(tools=tools, model=model)
|
| 22 |
+
return agent, mcp_client
|
| 23 |
+
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"Failed to connect to MCP server: {e}")
|
| 26 |
+
print("Creating agent with basic tools...")
|
| 27 |
+
agent = CodeAgent(tools=[], model=model)
|
| 28 |
+
return agent, None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Initialize agent globally
|
| 32 |
+
agent, mcp_client = create_agent_with_fallback()
|
| 33 |
+
|
| 34 |
+
# Chat function
|
| 35 |
+
def chat_function(message, history):
|
| 36 |
+
try:
|
| 37 |
+
return str(agent.run(message))
|
| 38 |
+
except Exception as e:
|
| 39 |
+
return f"Error: {str(e)}"
|
| 40 |
+
|
| 41 |
+
# Gradio ChatInterface defined at the top level (needed for Spaces)
|
| 42 |
+
demo = gr.ChatInterface(
|
| 43 |
+
fn=chat_function,
|
| 44 |
+
type="messages",
|
| 45 |
+
examples=["What's the sentiment of this?"],
|
| 46 |
+
title="Agent with MCP Tools",
|
| 47 |
+
description="This is a simple agent that uses MCP tools to analyze the sentiment of text.",
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Cleanup on exit
|
| 51 |
+
def cleanup():
|
| 52 |
+
if mcp_client:
|
| 53 |
+
try:
|
| 54 |
+
mcp_client.disconnect()
|
| 55 |
+
except:
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
atexit.register(cleanup)
|
requirements.txt
CHANGED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio[mcp]
|
| 2 |
+
smolagents[mcp]
|