Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,12 +15,15 @@ from pathlib import Path
|
|
| 15 |
import aiohttp
|
| 16 |
import json
|
| 17 |
import os
|
|
|
|
| 18 |
import asyncio
|
| 19 |
|
|
|
|
| 20 |
from gradio_client import Client, handle_file
|
| 21 |
HF_TOKEN = os.environ.get('HF_TOKEN')
|
| 22 |
|
| 23 |
|
|
|
|
| 24 |
##### LLM #####
|
| 25 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 26 |
|
|
@@ -372,6 +375,49 @@ async def query_context(
|
|
| 372 |
|
| 373 |
|
| 374 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
|
| 376 |
|
| 377 |
# Configuración de la interfaz Gradio
|
|
@@ -439,10 +485,49 @@ with gr.Blocks(title="Herramientas MCP") as tools_tab:
|
|
| 439 |
|
| 440 |
# Creamos el Agente MCP (puedes personalizar esto según necesites)
|
| 441 |
with gr.Blocks(title="Agente MCP") as agent_tab:
|
| 442 |
-
gr.Markdown("#
|
| 443 |
-
gr.Markdown("
|
| 444 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
|
|
|
|
| 446 |
# Creamos la interfaz con las dos pestañas principales
|
| 447 |
demo = gr.TabbedInterface(
|
| 448 |
[agent_tab, tools_tab],
|
|
|
|
| 15 |
import aiohttp
|
| 16 |
import json
|
| 17 |
import os
|
| 18 |
+
from mcp_agent import MCPAgent
|
| 19 |
import asyncio
|
| 20 |
|
| 21 |
+
|
| 22 |
from gradio_client import Client, handle_file
|
| 23 |
HF_TOKEN = os.environ.get('HF_TOKEN')
|
| 24 |
|
| 25 |
|
| 26 |
+
|
| 27 |
##### LLM #####
|
| 28 |
openai_api_key = os.environ.get('OPENAI_API_KEY')
|
| 29 |
|
|
|
|
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
+
##### MCP AGENT #####
|
| 379 |
+
sse_url = "https://pharma-ia-gradio-mcp-server.hf.space/gradio_api/mcp/sse"
|
| 380 |
+
|
| 381 |
+
# Crear instancia del agente (debes tener tu llm definido)
|
| 382 |
+
mcp_agent = MCPAgent(sse_url, HF_TOKEN, llm)
|
| 383 |
+
|
| 384 |
+
# Historial de chat
|
| 385 |
+
chat_history = []
|
| 386 |
+
|
| 387 |
+
def format_tool_call(tool_name, arguments):
|
| 388 |
+
return f"🔧 **Llamando a herramienta**: `{tool_name}`\n```json\n{arguments}\n```"
|
| 389 |
+
|
| 390 |
+
def format_tool_result(tool_name, result):
|
| 391 |
+
return f"✅ **Resultado de `{tool_name}`**\n```\n{result}\n```"
|
| 392 |
+
|
| 393 |
+
async def chat_with_agent(message, history):
|
| 394 |
+
history = history or []
|
| 395 |
+
|
| 396 |
+
# Agregar mensaje del usuario al historial
|
| 397 |
+
history.append((message, ""))
|
| 398 |
+
|
| 399 |
+
# Procesar con el agente
|
| 400 |
+
full_response = ""
|
| 401 |
+
async for event in mcp_agent.stream_response(message):
|
| 402 |
+
if event["type"] == "tool_call":
|
| 403 |
+
tool_msg = format_tool_call(event["tool_name"], event["arguments"])
|
| 404 |
+
history.append((None, tool_msg))
|
| 405 |
+
yield history
|
| 406 |
+
elif event["type"] == "tool_result":
|
| 407 |
+
result_msg = format_tool_result(event["tool_name"], event["result"])
|
| 408 |
+
history.append((None, result_msg))
|
| 409 |
+
yield history
|
| 410 |
+
elif event["type"] == "final_response":
|
| 411 |
+
full_response = event["content"]
|
| 412 |
+
|
| 413 |
+
# Reemplazar el último mensaje vacío con la respuesta completa
|
| 414 |
+
history[-1] = (message, full_response)
|
| 415 |
+
yield history
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
|
| 421 |
|
| 422 |
|
| 423 |
# Configuración de la interfaz Gradio
|
|
|
|
| 485 |
|
| 486 |
# Creamos el Agente MCP (puedes personalizar esto según necesites)
|
| 487 |
with gr.Blocks(title="Agente MCP") as agent_tab:
|
| 488 |
+
gr.Markdown("# Agente MCP - Asistente con Herramientas")
|
| 489 |
+
gr.Markdown("Interactúa con el agente que puede consultar múltiples fuentes de información especializada.")
|
| 490 |
+
|
| 491 |
+
with gr.Row():
|
| 492 |
+
with gr.Column(scale=3):
|
| 493 |
+
chatbot = gr.Chatbot(
|
| 494 |
+
label="Conversación",
|
| 495 |
+
height=600,
|
| 496 |
+
bubble_full_width=False,
|
| 497 |
+
render_markdown=True
|
| 498 |
+
)
|
| 499 |
+
msg = gr.Textbox(
|
| 500 |
+
label="Mensaje",
|
| 501 |
+
placeholder="Escribe tu pregunta aquí...",
|
| 502 |
+
container=False
|
| 503 |
+
)
|
| 504 |
+
btn = gr.Button("Enviar")
|
| 505 |
+
clear = gr.ClearButton([msg, chatbot])
|
| 506 |
+
|
| 507 |
+
with gr.Column(scale=1):
|
| 508 |
+
gr.Markdown("### Herramientas Disponibles")
|
| 509 |
+
tools_info = gr.JSON(label="Herramientas", value=[])
|
| 510 |
+
|
| 511 |
+
# Inicializar el agente y cargar herramientas
|
| 512 |
+
async def init_agent():
|
| 513 |
+
tools = await mcp_agent.initialize()
|
| 514 |
+
return {"tools": [tool.name for tool in tools.tools]}
|
| 515 |
+
|
| 516 |
+
agent_tab.load(init_agent, outputs=[tools_info])
|
| 517 |
+
|
| 518 |
+
# Manejar interacción del chat
|
| 519 |
+
msg.submit(
|
| 520 |
+
chat_with_agent,
|
| 521 |
+
inputs=[msg, chatbot],
|
| 522 |
+
outputs=[chatbot]
|
| 523 |
+
)
|
| 524 |
+
btn.click(
|
| 525 |
+
chat_with_agent,
|
| 526 |
+
inputs=[msg, chatbot],
|
| 527 |
+
outputs=[chatbot]
|
| 528 |
+
).then(lambda: "", None, [msg])
|
| 529 |
|
| 530 |
+
|
| 531 |
# Creamos la interfaz con las dos pestañas principales
|
| 532 |
demo = gr.TabbedInterface(
|
| 533 |
[agent_tab, tools_tab],
|