fix: Handle KeyError in template parameter mapping and suggest closest match if not found (#3366)

This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-08-16 16:42:36 -03:00 committed by GitHub
commit 212a566dfc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 21 additions and 1 deletions

View file

@ -16,6 +16,7 @@ from langflow.services.tracing.schema import Log
from langflow.template.field.base import UNDEFINED, Input, Output
from langflow.template.frontend_node.custom_components import ComponentFrontendNode
from langflow.utils.async_helpers import run_until_complete
from langflow.utils.util import find_closest_match
from .custom_component import CustomComponent
@ -415,7 +416,15 @@ class Component(CustomComponent):
def _map_parameters_on_template(self, template: dict):
for name, value in self._parameters.items():
template[name]["value"] = value
try:
template[name]["value"] = value
except KeyError:
close_match = find_closest_match(name, list(template.keys()))
if close_match:
raise ValueError(
f"Parameter '{name}' not found in {self.__class__.__name__}. " f"Did you mean '{close_match}'?"
)
raise ValueError(f"Parameter {name} not found in {self.__class__.__name__}. ")
def _get_method_return_type(self, method_name: str) -> List[str]:
method = getattr(self, method_name)

View file

@ -1,3 +1,4 @@
import difflib
import importlib
import inspect
import json
@ -465,3 +466,13 @@ def is_class_method(func, cls):
def escape_json_dump(edge_dict):
return json.dumps(edge_dict).replace('"', "œ")
def find_closest_match(string: str, list_of_strings: list[str]) -> str | None:
"""
Find the closest match in a list of strings.
"""
closest_match = difflib.get_close_matches(string, list_of_strings, n=1, cutoff=0.2)
if closest_match:
return closest_match[0]
return None