Spaces:
Sleeping
Sleeping
Download main.py from Darshanpurohit/workflow_backend: direct link, hf CLI and curl.
- Browser
- Download file 20.6 kB
-
https://huggingface.co/spaces/Darshanpurohit/workflow_backend/resolve/main/main.py
- Command line
-
hf download hf://spaces/Darshanpurohit/workflow_backend/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Darshanpurohit/workflow_backend/resolve/main/main.py
20.6 kB
| from fastapi import FastAPI, HTTPException, Header | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, Field | |
| from typing import List, Dict, Any, Optional | |
| from collections import defaultdict, deque | |
| import httpx | |
| import base64 | |
| import re | |
| import io | |
| import os | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| try: | |
| import pypdf | |
| except ImportError: | |
| pypdf = None | |
| try: | |
| from PIL import Image | |
| import pytesseract | |
| except ImportError: | |
| Image = None | |
| pytesseract = None | |
| app = FastAPI() | |
| CORS_ORIGINS = [ | |
| origin.strip() | |
| for origin in os.getenv("CORS_ORIGINS", "http://localhost:3000,http://127.0.0.1:3000").split(",") | |
| if origin.strip() | |
| ] | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=CORS_ORIGINS, | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| class Node(BaseModel): | |
| id: str | |
| type: str | |
| class Edge(BaseModel): | |
| id: str | |
| source: str | |
| target: str | |
| class PipelineRequest(BaseModel): | |
| nodes: List[Node] | |
| edges: List[Edge] | |
| class PipelineResponse(BaseModel): | |
| num_nodes: int | |
| num_edges: int | |
| is_dag: bool | |
| message: str | |
| def is_dag(nodes: List[Node], edges: List[Edge]) -> bool: | |
| graph = defaultdict(list) | |
| in_degree = defaultdict(int) | |
| node_ids = {node.id for node in nodes} | |
| for node_id in node_ids: | |
| in_degree[node_id] = 0 | |
| for edge in edges: | |
| if edge.source not in node_ids or edge.target not in node_ids: | |
| return False | |
| graph[edge.source].append(edge.target) | |
| in_degree[edge.target] += 1 | |
| queue = deque([node_id for node_id in node_ids if in_degree[node_id] == 0]) | |
| visited_count = 0 | |
| while queue: | |
| current = queue.popleft() | |
| visited_count += 1 | |
| for neighbor in graph[current]: | |
| in_degree[neighbor] -= 1 | |
| if in_degree[neighbor] == 0: | |
| queue.append(neighbor) | |
| return visited_count == len(node_ids) | |
| def has_valid_edges(nodes: List[Node], edges: List[Edge]) -> bool: | |
| node_ids = {node.id for node in nodes} | |
| return all(edge.source in node_ids and edge.target in node_ids for edge in edges) | |
| def read_root(): | |
| return {'Ping': 'Pong'} | |
| def parse_pipeline(pipeline: PipelineRequest): | |
| """ | |
| Parse a pipeline and return statistics: | |
| - Number of nodes | |
| - Number of edges | |
| - Whether the pipeline forms a DAG (Directed Acyclic Graph) | |
| """ | |
| num_nodes = len(pipeline.nodes) | |
| num_edges = len(pipeline.edges) | |
| valid_edges = has_valid_edges(pipeline.nodes, pipeline.edges) | |
| dag_status = valid_edges and is_dag(pipeline.nodes, pipeline.edges) | |
| if dag_status: | |
| message = "Valid DAG pipeline" | |
| elif not valid_edges: | |
| message = "Invalid: Contains edges connected to missing nodes" | |
| else: | |
| message = "Invalid: Contains cycles" | |
| return PipelineResponse( | |
| num_nodes=num_nodes, | |
| num_edges=num_edges, | |
| is_dag=dag_status, | |
| message=message | |
| ) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # LLM EXECUTION ENDPOINT (Groq API Integration) | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class LLMRequest(BaseModel): | |
| prompt: str | |
| model: str = "llama-3.3-70b-versatile" | |
| temperature: float = Field(default=0.7, ge=0, le=2) | |
| max_tokens: int = Field(default=1024, ge=1, le=4096) | |
| api_key: Optional[str] = None | |
| class LLMResponse(BaseModel): | |
| output: str | |
| model: str | |
| tokens_used: Optional[int] = None | |
| GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions" | |
| GROQ_MODELS = [ | |
| "llama-3.3-70b-versatile" | |
| ] | |
| async def execute_llm(request: LLMRequest): | |
| """ | |
| Execute LLM inference using Groq API. | |
| Requires Groq API key (can be passed in request or header). | |
| """ | |
| api_key = request.api_key or os.environ.get("GROQ_API_KEY") | |
| if not api_key: | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Groq API key is required. Provide it in the request or set GROQ_API_KEY in the backend environment." | |
| ) | |
| if request.model not in GROQ_MODELS: | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Invalid model. Supported models: {', '.join(GROQ_MODELS)}" | |
| ) | |
| try: | |
| async with httpx.AsyncClient(timeout=60.0) as client: | |
| response = await client.post( | |
| GROQ_API_URL, | |
| headers={ | |
| "Authorization": f"Bearer {api_key}", | |
| "Content-Type": "application/json" | |
| }, | |
| json={ | |
| "model": request.model, | |
| "messages": [ | |
| {"role": "system", "content": "You are a helpful assistant."}, | |
| {"role": "user", "content": request.prompt} | |
| ], | |
| "temperature": request.temperature, | |
| "max_tokens": request.max_tokens | |
| } | |
| ) | |
| if response.status_code != 200: | |
| error_data = response.json() if response.text else {"error": "Unknown error"} | |
| raise HTTPException( | |
| status_code=response.status_code, | |
| detail=f"Groq API error: {error_data}" | |
| ) | |
| data = response.json() | |
| output = data["choices"][0]["message"]["content"] | |
| tokens_used = data.get("usage", {}).get("total_tokens") | |
| return LLMResponse( | |
| output=output, | |
| model=request.model, | |
| tokens_used=tokens_used | |
| ) | |
| except httpx.TimeoutException: | |
| raise HTTPException(status_code=504, detail="Request timed out. Try again later.") | |
| except httpx.RequestError as e: | |
| raise HTTPException(status_code=503, detail=f"Failed to connect to Groq API: {str(e)}") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}") | |
| def get_available_models(): | |
| """Get list of available Groq models.""" | |
| return {"models": GROQ_MODELS} | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # PIPELINE EXECUTION ENGINE | |
| # βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class ExecutionNode(BaseModel): | |
| id: str | |
| type: str | |
| data: Dict[str, Any] = Field(default_factory=dict) | |
| class ExecutionEdge(BaseModel): | |
| id: str | |
| source: str | |
| target: str | |
| sourceHandle: Optional[str] = None | |
| targetHandle: Optional[str] = None | |
| class ExecutePipelineRequest(BaseModel): | |
| nodes: List[ExecutionNode] | |
| edges: List[ExecutionEdge] | |
| inputs: Dict[str, Any] = Field(default_factory=dict) | |
| class ExecutePipelineResponse(BaseModel): | |
| success: bool | |
| results: Dict[str, Any] | |
| execution_order: List[str] | |
| errors: List[str] | |
| def topological_sort(nodes: List[ExecutionNode], edges: List[ExecutionEdge]) -> List[str]: | |
| """Topological sort to determine execution order (Kahn's algorithm).""" | |
| graph = defaultdict(list) | |
| in_degree = defaultdict(int) | |
| node_ids = {node.id for node in nodes} | |
| for node_id in node_ids: | |
| in_degree[node_id] = 0 | |
| for edge in edges: | |
| graph[edge.source].append(edge.target) | |
| in_degree[edge.target] += 1 | |
| queue = deque([node_id for node_id in node_ids if in_degree[node_id] == 0]) | |
| result = [] | |
| while queue: | |
| current = queue.popleft() | |
| result.append(current) | |
| for neighbor in graph[current]: | |
| in_degree[neighbor] -= 1 | |
| if in_degree[neighbor] == 0: | |
| queue.append(neighbor) | |
| return result | |
| async def execute_node(node: ExecutionNode, inputs: Dict[str, Any], api_key: Optional[str] = None) -> Any: | |
| """Execute a single node based on its type.""" | |
| node_type = node.type | |
| data = node.data | |
| if node_type == 'customInput': | |
| # Input node - check for file upload first | |
| file_upload = data.get('fileUpload') | |
| input_value = data.get('inputValue', '') | |
| input_type = data.get('inputType', 'Text') | |
| # If there's a file upload, try to extract content | |
| if file_upload and isinstance(file_upload, dict): | |
| file_name = file_upload.get('name', '') | |
| file_content = file_upload.get('content') # Actual text content from browser | |
| if file_content: | |
| if isinstance(file_content, str) and file_content.startswith('data:'): | |
| match = re.match(r'data:(.*?)(;base64)?,(.*)', file_content) | |
| if match: | |
| mime_type = match.group(1) | |
| is_base64 = match.group(2) | |
| data_str = match.group(3) | |
| if is_base64: | |
| binary_data = base64.b64decode(data_str) | |
| else: | |
| import urllib.parse | |
| binary_data = urllib.parse.unquote(data_str).encode('utf-8') | |
| # Handle PDF parsing | |
| if mime_type == 'application/pdf' or file_name.lower().endswith('.pdf'): | |
| if pypdf: | |
| try: | |
| pdf_reader = pypdf.PdfReader(io.BytesIO(binary_data)) | |
| extracted_text = "" | |
| for page in pdf_reader.pages: | |
| text = page.extract_text() | |
| if text: | |
| extracted_text += text + "\n" | |
| return extracted_text.strip() if extracted_text else "[No text could be extracted from PDF]" | |
| except Exception as e: | |
| return f"[Error parsing PDF: {str(e)}]" | |
| else: | |
| return f"[PDF: {file_name} - 'pypdf' Python package missing]" | |
| # Handle Image OCR | |
| elif mime_type.startswith('image/') or file_name.lower().endswith(('.png', '.jpg', '.jpeg')): | |
| if Image and pytesseract: | |
| try: | |
| img = Image.open(io.BytesIO(binary_data)) | |
| text = pytesseract.image_to_string(img) | |
| return text.strip() if text.strip() else "[No text identified in Image]" | |
| except pytesseract.TesseractNotFoundError: | |
| return "[OCR Error: Tesseract Engine is not installed on your operating system. Please install 'tesseract' via brew/apt-get]" | |
| except Exception as e: | |
| return f"[OCR Error: {str(e)}]" | |
| else: | |
| return f"[Image: {file_name} - OCR packages missing]" | |
| # Handle other typical text files | |
| else: | |
| try: | |
| return binary_data.decode('utf-8', errors='ignore') | |
| except: | |
| return f"[File: {file_name} - Binary files not supported yet]" | |
| # If content is not a data URL (e.g. plain text sent directly) | |
| return file_content | |
| # Return text/number value if provided. Also tolerate the common | |
| # copied format "name: foo, value: bar" and use only the value. | |
| if input_value: | |
| if isinstance(input_value, str): | |
| value_match = re.match(r'^\s*name\s*:\s*[^,]+,\s*value\s*:\s*(.*)\s*$', input_value) | |
| if value_match: | |
| return value_match.group(1) | |
| return input_value | |
| # Default: return input name | |
| return data.get('inputName', 'input') | |
| elif node_type == 'text': | |
| # Text node processes template with variables | |
| text = data.get('text', '') | |
| for key, value in inputs.items(): | |
| if isinstance(value, list): | |
| value = ", ".join(str(v) for v in value) | |
| text = re.sub( | |
| r'\{\{\s*' + re.escape(str(key)) + r'\s*\}\}', | |
| str(value), | |
| text | |
| ) | |
| return text | |
| elif node_type == 'llm': | |
| # LLM node calls Groq API | |
| api_key = api_key or os.environ.get("GROQ_API_KEY") | |
| if not api_key: | |
| raise ValueError("Groq API key required for LLM node. Add it in the UI or backend .env.") | |
| prompt_template = data.get('prompt', '') | |
| model = data.get('model', 'llama-3.3-70b-versatile') | |
| temperature = float(data.get('temperature', 0.7)) | |
| max_tokens = int(data.get('maxTokens', 1024)) | |
| # ALWAYS use the template as the base | |
| prompt = prompt_template if prompt_template.strip() else "" | |
| # Gather all connected inputs and append them to the prompt | |
| input_texts = [] | |
| for handle_id, value in inputs.items(): | |
| if isinstance(value, list): | |
| input_texts.extend([str(v) for v in value if v]) | |
| else: | |
| if value: | |
| input_texts.append(str(value)) | |
| if input_texts: | |
| prompt += "\n\n--- INPUT DATA ---\n" + "\n\n".join(input_texts) | |
| async with httpx.AsyncClient(timeout=60.0) as client: | |
| response = await client.post( | |
| GROQ_API_URL, | |
| headers={ | |
| "Authorization": f"Bearer {api_key}", | |
| "Content-Type": "application/json" | |
| }, | |
| json={ | |
| "model": model, | |
| "messages": [ | |
| {"role": "system", "content": "You are a helpful assistant."}, | |
| {"role": "user", "content": prompt} | |
| ], | |
| "temperature": temperature, | |
| "max_tokens": max_tokens | |
| } | |
| ) | |
| if response.status_code != 200: | |
| raise ValueError(f"Groq API error: {response.text}") | |
| result = response.json() | |
| return result["choices"][0]["message"]["content"] | |
| elif node_type == 'customOutput': | |
| # Output node just passes through its input | |
| return list(inputs.values())[0] if inputs else None | |
| elif node_type == 'filter': | |
| # Filter node - simple condition | |
| value = list(inputs.values())[0] if inputs else "" | |
| condition = data.get('condition', '') | |
| return f"Filtered: {value}" if condition else value | |
| elif node_type == 'delay': | |
| # Delay node | |
| import asyncio | |
| duration = int(data.get('delay', data.get('duration', 1))) | |
| unit = data.get('unit', 'seconds') | |
| delay_seconds = duration / 1000 if unit == 'milliseconds' else duration * 60 if unit == 'minutes' else duration | |
| await asyncio.sleep(delay_seconds) | |
| return list(inputs.values())[0] if inputs else None | |
| elif node_type == 'merge': | |
| # Merge node - combines inputs based on strategy | |
| strategy = data.get('strategy', 'concat') | |
| # Flatten all values into a single list | |
| all_values = [] | |
| for val in inputs.values(): | |
| if isinstance(val, list): | |
| all_values.extend(str(v) for v in val if v is not None) | |
| else: | |
| if val is not None: | |
| all_values.append(str(val)) | |
| if not all_values: | |
| return "" | |
| if strategy == 'concat': | |
| separator = data.get('separator', '\\n') | |
| # Handle escaped characters like \n or \t | |
| separator = separator.encode().decode('unicode_escape') | |
| return separator.join(all_values) | |
| elif strategy == 'first': | |
| return all_values[0] | |
| elif strategy == 'last': | |
| return all_values[-1] | |
| elif strategy == 'array': | |
| return all_values | |
| else: | |
| return ", ".join(all_values) | |
| else: | |
| # Default: return inputs | |
| return list(inputs.values())[0] if inputs else None | |
| async def execute_pipeline(request: ExecutePipelineRequest): | |
| """ | |
| Execute a pipeline by running each node in topological order. | |
| """ | |
| try: | |
| # Get execution order | |
| execution_order = topological_sort(request.nodes, request.edges) | |
| if len(execution_order) != len(request.nodes): | |
| return ExecutePipelineResponse( | |
| success=False, | |
| results={}, | |
| execution_order=execution_order, | |
| errors=["Pipeline contains cycles - cannot execute"] | |
| ) | |
| # Build adjacency for data flow | |
| edge_map = defaultdict(list) | |
| for edge in request.edges: | |
| edge_map[edge.target].append((edge.source, edge.sourceHandle, edge.targetHandle)) | |
| # Execute nodes | |
| node_results = {} | |
| errors = [] | |
| api_key = None | |
| for node_id in execution_order: | |
| node = next((n for n in request.nodes if n.id == node_id), None) | |
| if not node: | |
| continue | |
| # Gather inputs from connected nodes | |
| inputs = {} | |
| for source_id, source_handle, target_handle in edge_map[node_id]: | |
| if source_id in node_results: | |
| key = target_handle or 'input' | |
| # Strip the nodeId prefix from the handle id if present (e.g., "llm_1-prompt" -> "prompt") | |
| if key.startswith(f"{node_id}-"): | |
| key = key[len(node_id)+1:] | |
| # Accumulate multiple inputs for the same handle as a list | |
| if key in inputs: | |
| if not isinstance(inputs[key], list): | |
| inputs[key] = [inputs[key]] | |
| inputs[key].append(node_results[source_id]) | |
| else: | |
| inputs[key] = node_results[source_id] | |
| # Also use provided inputs for input nodes | |
| if node.type == 'input' and node_id in request.inputs: | |
| inputs['value'] = request.inputs[node_id] | |
| # Capture API key from LLM nodes | |
| if node.type == 'llm' and node.data.get('apiKey'): | |
| api_key = node.data.get('apiKey') | |
| try: | |
| result = await execute_node(node, inputs, api_key) | |
| node_results[node_id] = result | |
| except Exception as e: | |
| errors.append(f"Node {node_id} ({node.type}): {str(e)}") | |
| return ExecutePipelineResponse( | |
| success=len(errors) == 0, | |
| results=node_results, | |
| execution_order=execution_order, | |
| errors=errors | |
| ) | |
| except Exception as e: | |
| return ExecutePipelineResponse( | |
| success=False, | |
| results={}, | |
| execution_order=[], | |
| errors=[f"Execution failed: {str(e)}"] | |
| ) | |