diff --git a/src/backend/langflow/api/endpoints.py b/src/backend/langflow/api/endpoints.py index 7211eb8d6..a7c26c20e 100644 --- a/src/backend/langflow/api/endpoints.py +++ b/src/backend/langflow/api/endpoints.py @@ -1,10 +1,12 @@ from typing import Any, Dict from fastapi import APIRouter, HTTPException +from langflow.interface.custom_types import PythonFunction from langflow.interface.run import process_graph from langflow.interface.types import build_langchain_types_dict + # build router router = APIRouter() @@ -20,3 +22,12 @@ def get_load(data: Dict[str, Any]): return process_graph(data) except Exception as e: return HTTPException(status_code=500, detail=str(e)) + + +@router.post("/validate", status_code=200) +def validate_code(data: PythonFunction): + try: + # if the data var gets here then it is valid python code + return {"valid": True} + except Exception as e: + return HTTPException(status_code=500, detail=str(e)) diff --git a/src/backend/langflow/interface/custom_types.py b/src/backend/langflow/interface/custom_types.py index cf14e8fd8..41e745212 100644 --- a/src/backend/langflow/interface/custom_types.py +++ b/src/backend/langflow/interface/custom_types.py @@ -1,16 +1,24 @@ +from typing import Callable from langflow.utils import util from pydantic import BaseModel, validator -from langchain.agents import tool + class Function(BaseModel): code: str + # Eval code and store the function + def __init__(self, **data): + super().__init__(**data) + # Validate the function @validator("code") def validate_func(cls, v): # Validate with LangChain's tool decorator - tool(v) + func = util.eval_function(v) + if not isinstance(func, Callable): + raise ValueError("Function must be a callable") + return v def get_function(self):