File size: 4,766 Bytes
6d9b477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b6ff605
6d9b477
b6ff605
 
 
 
 
6d9b477
 
 
 
 
 
 
 
b6ff605
 
 
 
 
 
6d9b477
 
b6ff605
6d9b477
 
 
 
b6ff605
6d9b477
 
0096d47
6d9b477
 
3ef2fca
 
 
 
 
 
 
6d9b477
 
3ef2fca
6d9b477
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
from typing import Annotated, Any, Dict, List, Optional, TypedDict
from langchain_core.runnables import RunnableConfig
from langgraph.graph import StateGraph, START, END
from firecrawl import FirecrawlApp
from deerflow.config.app_config import get_app_config

# --- Engine Logic: Deer-Flow Scraping Motor ---

class WorkflowState(TypedDict):
    """Estado del flujo de orquestaci贸n de scraping."""
    url: str
    result: Optional[str]
    retries: int
    error: Optional[str]

class ActionNode:
    """Abstracci贸n base para Action Nodes con l贸gica integrada de reintentos y timeout."""
    def __init__(self, name: str, timeout: int = 60, max_retries: int = 3):
        self.name = name
        self.timeout = timeout
        self.max_retries = max_retries

    async def execute(self, state: WorkflowState, config: RunnableConfig) -> WorkflowState:
        raise NotImplementedError

class ScrapeNode(ActionNode):
    """ActionNode especializado en web scraping a trav茅s de la API de Firecrawl."""
    def __init__(self):
        super().__init__(name="scrape", timeout=60, max_retries=3)
        self._client = None

    def get_client(self) -> FirecrawlApp:
        """Inicializa el cliente de Firecrawl de forma tard铆a (lazy)."""
        if self._client:
            return self._client
            
        import os
        api_key = os.environ.get("FIRECRAWL_API_KEY")
        if not api_key:
            try:
                config = get_app_config().get_tool_config("web_search")
                api_key = config.model_extra.get("api_key") if config else None
            except Exception:
                api_key = None
        
        if not api_key:
            raise ValueError("No se ha proporcionado la API Key de Firecrawl. Por favor, config煤rala en la barra lateral o en las variables de entorno.")
            
        self._client = FirecrawlApp(api_key=api_key)
        return self._client

    async def execute(self, state: WorkflowState, config: RunnableConfig) -> WorkflowState:
        """Ejecuta la l贸gica de scraping con el cliente inicializado bajo demanda."""
        url = state.get("url")
        retries = state.get("retries", 0)

        try:
            client = self.get_client()
            # Requisito: Timeout de 60s por nodo
            response = await asyncio.wait_for(
                asyncio.to_thread(client.scrape, url, formats=["markdown"]),
                timeout=self.timeout
            )
            
            # Soporte dual: diccionario (SDK antiguo/API) u objeto (SDK nuevo)
            if isinstance(response, dict):
                markdown_content = response.get("markdown", "")
            else:
                markdown_content = getattr(response, "markdown", "") or ""

            return {
                **state, 
                "result": markdown_content, 
                "error": None
            }
        except asyncio.TimeoutError:
            return self._handle_error(state, "Node execution timed out (60s limit)")
        except Exception as e:
            return self._handle_error(state, str(e))

    def _handle_error(self, state: WorkflowState, error_msg: str) -> WorkflowState:
        """Actualiza el estado interno de reintentos."""
        retries = int(state.get("retries", 0))
        return {
            **state,
            "retries": retries + 1,
            "error": error_msg
        }

class Flow:
    """Motor de orquestaci贸n para flujos de scraping en Deer-Flow."""
    def __init__(self, concurrency_limit: int = 10):
        # El l铆mite de concurrencia de 10 ejecuciones se define aqu铆 para el motor
        self.concurrency_limit = concurrency_limit
        self.builder = StateGraph(WorkflowState)
        self._init_orchestration()

    def _init_orchestration(self):
        """Construye el Grafo de Estados con pol铆tica de reintentos (max 3)."""
        node = ScrapeNode()

        # A帽adir nodos al grafo
        self.builder.add_node("scrape", node.execute)

        # Punto de entrada
        self.builder.add_edge(START, "scrape")

        # L贸gica de ruteo: Pol铆tica de reintentos (Max 3) integrada en el grafo
        def should_continue(state: WorkflowState):
            retries = int(state.get("retries", 0))
            if state.get("error") and retries <= 3:
                return "scrape" # Ciclo de reintento
            return END

        self.builder.add_conditional_edges(
            "scrape",
            should_continue,
            {"scrape": "scrape", END: END}
        )

    def compile(self):
        """Compila el flujo en un grafo ejecutable compatible con Deer-Flow."""
        return self.builder.compile()

# --- Exportaci贸n del Motor Funcional ---

workflow = Flow(concurrency_limit=10).compile()