📝 (utils.py): Add get_flow function and update Python API code (#2075)

* feat: Add upload_file function for file uploading

This commit adds a new function called `upload_file` to the `load/utils.py` module. This function allows users to upload a file to the storage service and returns the file path. It takes in parameters such as `file_path`, `host`, `port`, `flow_id`, `components`, and `tweaks`. The function makes use of the `upload` function to send a POST request to the storage service API and handle the response.

The `upload_file` function is useful for scenarios where users need to upload files to the flow and associate them with specific components. It provides flexibility by allowing users to specify the components that require the file and any tweaks that should be applied to the file.

This feature enhances the functionality of the codebase and improves the overall user experience when working with file uploads in the application.

* 📝 (utils.py): Add get_flow function to retrieve flow details from Langflow

📝 (utils.py): Remove unused 'port' parameter from upload functions
📝 (utils.py): Update upload function to use Langflow host URL and remove port parameter
📝 (utils.py): Update upload_file function to use Langflow host URL and port number
📝 (utils.py): Update function descriptions and variable names for clarity and consistency
📝 (model.py): Remove 'folder_id' field from FlowBase model in langflow services database

* 📝 (load/__init__.py): add get_flow function to __all__ list to expose it to other modules
📝 (utils.py): fix docstring formatting issue in get_flow function

* make getPythonApiCode receive endpointname
This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-06-05 10:30:54 -07:00 • committed by GitHub
commit 80f6249a50
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 165 additions and 22 deletions

View file

@ -1,3 +1,4 @@
from .load import load_flow_from_json, run_flow_from_json # noqa: F401
from .load import load_flow_from_json, run_flow_from_json
from .utils import upload_file, get_flow
__all__ = ["load_flow_from_json", "run_flow_from_json"]
__all__ = ["load_flow_from_json", "run_flow_from_json", "upload_file", "get_flow"]

View file

@ -0,0 +1,89 @@
import httpx
from langflow.services.database.models.flow.model import FlowBase
def upload(file_path, host, flow_id):
"""
Upload a file to Langflow and return the file path.
Args:
file_path (str): The path to the file to be uploaded.
host (str): The host URL of Langflow.
flow_id (UUID): The ID of the flow to which the file belongs.
Returns:
dict: A dictionary containing the file path.
Raises:
Exception: If an error occurs during the upload process.
"""
try:
url = f"{host}/api/v1/upload/{flow_id}"
response = httpx.post(url, files={"file": open(file_path, "rb")})
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Error uploading file: {response.status_code}")
except Exception as e:
raise Exception(f"Error uploading file: {e}")
def upload_file(file_path, host, flow_id, components, tweaks={}):
"""
Upload a file to Langflow and return the file path.
Args:
file_path (str): The path to the file to be uploaded.
host (str): The host URL of Langflow.
port (int): The port number of Langflow.
flow_id (UUID): The ID of the flow to which the file belongs.
components (str): List of component IDs or names that need the file.
tweaks (dict): A dictionary of tweaks to be applied to the file.
Returns:
dict: A dictionary containing the file path and any tweaks that were applied.
Raises:
Exception: If an error occurs during the upload process.
"""
try:
response = upload(file_path, host, flow_id)
if response["file_path"]:
for component in components:
if isinstance(component, str):
tweaks[component] = {"file_path": response["file_path"]}
else:
raise ValueError(f"Component ID or name must be a string. Got {type(component)}")
return tweaks
else:
raise ValueError("Error uploading file")
except Exception as e:
raise ValueError(f"Error uploading file: {e}")
def get_flow(url: str, flow_id: str):
"""Get the details of a flow from Langflow.
Args:
url (str): The host URL of Langflow.
port (int): The port number of Langflow.
flow_id (UUID): The ID of the flow to retrieve.
Returns:
dict: A dictionary containing the details of the flow.
Raises:
Exception: If an error occurs during the retrieval process.
"""
try:
flow_url = f"{url}/api/v1/flows/{flow_id}"
response = httpx.get(flow_url)
if response.status_code == 200:
json_response = response.json()
flow = FlowBase(**json_response).model_dump()
return flow
else:
raise Exception(f"Error retrieving flow: {response.status_code}")
except Exception as e:
raise Exception(f"Error retrieving flow: {e}")

View file

@ -29,7 +29,6 @@ class FlowBase(SQLModel):
is_component: Optional[bool] = Field(default=False, nullable=True)
updated_at: Optional[datetime] = Field(default_factory=lambda: datetime.now(timezone.utc), nullable=True)
webhook: Optional[bool] = Field(default=False, nullable=True, description="Can be used on the webhook endpoint")
folder_id: Optional[UUID] = Field(default=None, nullable=True)
endpoint_name: Optional[str] = Field(default=None, nullable=True, index=True)
@field_validator("endpoint_name")