refactor: (codeflash) ️ Speed up function update_target_handle by 27% in src/backend/base/langflow/graph/graph/utils.py (#5388)

* ️ Speed up function `update_target_handle` by 27%
Sure, here are the optimized versions of the given functions. The key optimizations include avoiding redundant dictionary lookups, removing unnecessary condition checks, and simplifying the logic where possible.

* lint fix

* Apply suggestions from code review

Co-authored-by: Christophe Bornet <cbornet@hotmail.com>

---------

Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com>
Co-authored-by: Christophe Bornet <cbornet@hotmail.com>
This commit is contained in:
Saurabh Misra 2025-02-11 03:02:48 -08:00 committed by GitHub
commit 1bf6c847b7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -151,10 +151,13 @@ def update_target_handle(new_edge, g_nodes):
dict: The updated edge.
"""
target_handle = new_edge["data"]["targetHandle"]
if target_handle.get("proxy"):
proxy_id = target_handle["proxy"]["id"]
if node := next((n for n in g_nodes if n["id"] == proxy_id), None):
set_new_target_handle(proxy_id, new_edge, target_handle, node)
if proxy := target_handle.get("proxy"):
proxy_id = proxy["id"]
for node in g_nodes:
if node["id"] == proxy_id:
set_new_target_handle(proxy_id, new_edge, target_handle, node)
break
return new_edge
@ -179,13 +182,18 @@ def set_new_target_handle(proxy_id, new_edge, target_handle, node) -> None:
"type": type_,
"id": proxy_id,
}
if node["data"]["node"].get("flow"):
node_data = node["data"]["node"]
if node_data.get("flow"):
field_template_proxy = node_data["template"][field]["proxy"]
new_target_handle["proxy"] = {
"field": node["data"]["node"]["template"][field]["proxy"]["field"],
"id": node["data"]["node"]["template"][field]["proxy"]["id"],
"field": field_template_proxy["field"],
"id": field_template_proxy["id"],
}
if input_types := target_handle.get("inputTypes"):
new_target_handle["inputTypes"] = input_types
new_edge["data"]["targetHandle"] = new_target_handle