Spaces:
Sleeping
Sleeping
Download app.py from RevolutionGroup/deer-fire-scraper: direct link, hf CLI and curl.
- Browser
- Download file 5.08 kB
-
https://huggingface.co/spaces/RevolutionGroup/deer-fire-scraper/resolve/main/app.py
- Command line
-
hf download hf://spaces/RevolutionGroup/deer-fire-scraper/app.py
-
curl -L -o app.py https://huggingface.co/spaces/RevolutionGroup/deer-fire-scraper/resolve/main/app.py
5.08 kB
| import streamlit as st | |
| import os | |
| import sys | |
| from pathlib import Path | |
| # --- Configuración del Entorno para Deer-Flow --- | |
| PROJECT_ROOT = Path(__file__).parent.absolute() | |
| HARNESS_PATH = PROJECT_ROOT / "backend" / "packages" / "harness" | |
| if str(HARNESS_PATH) not in sys.path: | |
| sys.path.append(str(HARNESS_PATH)) | |
| try: | |
| from deerflow.client import DeerFlowClient | |
| except Exception as e: | |
| st.error(f"Error al cargar DeerFlowClient: {e}") | |
| st.stop() | |
| # --- Page Config --- | |
| st.set_page_config(page_title="Deer-Flow Agent", page_icon="🦌", layout="wide") | |
| st.title("🦌 Deer-Flow: Autonomous Agent") | |
| st.markdown("Agente inteligente capaz de navegar, buscar y razonar usando el motor de Deer-Flow.") | |
| # --- Sidebar: Configuración --- | |
| with st.sidebar: | |
| st.header("🔑 Autenticación") | |
| # OpenAI Key (Requerida para el razonamiento) | |
| openai_key = st.text_input("OPENAI_API_KEY", type="password", help="Necesaria para el motor de razonamiento (GPT-4o)") | |
| if openai_key: | |
| os.environ["OPENAI_API_KEY"] = openai_key | |
| # Firecrawl Key (Opcional si está en env, pero útil aquí) | |
| firecrawl_key = st.text_input("FIRECRAWL_API_KEY", type="password", help="Necesaria para herramientas de búsqueda y scraping") | |
| if firecrawl_key: | |
| os.environ["FIRECRAWL_API_KEY"] = firecrawl_key | |
| st.divider() | |
| st.info("Deer-Flow utiliza estos tokens para orquestar agentes autónomos que pueden navegar la web.") | |
| if st.button("Limpiar Chat"): | |
| st.session_state.messages = [] | |
| st.rerun() | |
| # --- Inicialización del Cliente --- | |
| def get_client(): | |
| return DeerFlowClient() | |
| client = get_client() | |
| # --- Chat Interface --- | |
| if "messages" not in st.session_state: | |
| st.session_state.messages = [] | |
| # Mostrar historial | |
| for message in st.session_state.messages: | |
| with st.chat_message(message["role"]): | |
| st.markdown(message["content"]) | |
| # Input del usuario | |
| if prompt := st.chat_input("¿En qué puedo ayudarte hoy? (ej: Scrapea teclab.edu.ar y resume sus carreras)"): | |
| # Añadir mensaje del usuario | |
| st.session_state.messages.append({"role": "user", "content": prompt}) | |
| with st.chat_message("user"): | |
| st.markdown(prompt) | |
| # Respuesta del Agente | |
| with st.chat_message("assistant"): | |
| message_placeholder = st.empty() | |
| full_response = "" | |
| # Contenedor para logs de pensamiento/herramientas | |
| with st.status("El agente está pensando...", expanded=False) as status: | |
| try: | |
| # Streaming de eventos de Deer-Flow | |
| for event in client.stream(prompt): | |
| if event.type == "messages-tuple": | |
| data = event.data | |
| msg_type = data.get("type") | |
| # Manejo de llamadas a herramientas | |
| if msg_type == "ai" and data.get("tool_calls"): | |
| for tc in data["tool_calls"]: | |
| st.write(f"🛠️ **Llamando herramienta:** `{tc['name']}`") | |
| st.code(tc["args"], language="json") | |
| status.update(label=f"Ejecutando {tc['name']}...") | |
| # Manejo de resultados de herramientas | |
| elif msg_type == "tool": | |
| st.write(f"✅ **Resultado de** `{data['name']}`") | |
| # No usamos st.expander aquí porque st.status ya actúa como uno | |
| st.text(data["content"][:500] + "...") | |
| # Manejo de texto de la IA (Respuesta final o parcial) | |
| elif msg_type == "ai" and data.get("content"): | |
| # El contenido crece dinámicamente | |
| full_response = data["content"] | |
| message_placeholder.markdown(full_response) | |
| status.update(label="Generando respuesta final...", expanded=False) | |
| elif event.type == "values": | |
| # Actualizaciones de estado del grafo (opcional mostrar) | |
| pass | |
| status.update(label="Tarea completada", state="complete") | |
| except Exception as e: | |
| status.update(label="Error en la ejecución", state="error") | |
| st.error(f"Error del Agente: {e}") | |
| full_response = f"Lo siento, ocurrió un error: {e}" | |
| # Guardar respuesta final si no se guardó durante el stream | |
| if not full_response: | |
| full_response = "El agente terminó sin generar una respuesta textual." | |
| message_placeholder.markdown(full_response) | |
| st.session_state.messages.append({"role": "assistant", "content": full_response}) | |
| # Footer | |
| st.divider() | |
| st.caption("Posta 3: Agente Autónomo Completo. Powered by Deer-Flow Engine.") | |