Skip to content

Commit

Permalink
fix: Refactor import statements and enhance error logging (langflow-a…
Browse files Browse the repository at this point in the history
…i#4071)

* Refactor import paths for `get_patched_openai_client` in astra_assistants components

* Enhance error logging with file information in directory_reader.py

* Refactor MetaphorToolkit to use new input/output structure and update imports

* Enhance error message with code snippet preview in class validation function

* update import statements and refactoring input handling in JSON files.

* [autofix.ci] apply automated fixes

* Remove unused import of 'Tool' from Metaphor.py

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
  • Loading branch information
2 people authored and diogocabral committed Nov 26, 2024
1 parent eebcd4b commit 2db7e8a
Show file tree
Hide file tree
Showing 24 changed files with 89 additions and 73 deletions.
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from astra_assistants.astra_assistants_manager import AssistantManager

from langflow.components.astra_assistants.util import (
from langflow.base.astra_assistants.util import (
get_patched_openai_client,
litellm_model_names,
tool_names,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from langflow.components.astra_assistants.util import get_patched_openai_client
from langflow.base.astra_assistants.util import get_patched_openai_client
from langflow.custom.custom_component.component_with_cache import ComponentWithCache
from langflow.inputs import MultilineInput, StrInput
from langflow.schema.message import Message
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from langflow.components.astra_assistants.util import get_patched_openai_client
from langflow.base.astra_assistants.util import get_patched_openai_client
from langflow.custom.custom_component.component_with_cache import ComponentWithCache
from langflow.inputs import MultilineInput
from langflow.schema.message import Message
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from langflow.components.astra_assistants.util import get_patched_openai_client
from langflow.base.astra_assistants.util import get_patched_openai_client
from langflow.custom.custom_component.component_with_cache import ComponentWithCache
from langflow.inputs import MultilineInput, StrInput
from langflow.schema.message import Message
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from langflow.components.astra_assistants.util import get_patched_openai_client
from langflow.base.astra_assistants.util import get_patched_openai_client
from langflow.custom.custom_component.component_with_cache import ComponentWithCache
from langflow.schema.message import Message
from langflow.template.field.base import Output
Expand Down
10 changes: 5 additions & 5 deletions src/backend/base/langflow/components/astra_assistants/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,14 @@
from openai import OpenAI
from openai.lib.streaming import AssistantEventHandler

from langflow.components.astra_assistants.util import get_patched_openai_client
from langflow.base.astra_assistants.util import get_patched_openai_client
from langflow.custom.custom_component.component_with_cache import ComponentWithCache
from langflow.inputs import MultilineInput
from langflow.schema import dotdict
from langflow.schema.message import Message
from langflow.template import Output


class AssistantsRunError(Exception):
"""Error running assistant"""


class AssistantsRun(ComponentWithCache):
display_name = "Run Assistant"
description = "Executes an Assistant Run against a thread"
Expand Down Expand Up @@ -101,3 +97,7 @@ def on_exception(self, exception: Exception) -> None:
print(e)
msg = f"Error running assistant: {e}"
raise AssistantsRunError(msg) from e


class AssistantsRunError(Exception):
"""AssistantsRun error"""
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@
from langflow.schema import Data


class SpiderToolError(Exception):
"""SpiderTool error"""


class SpiderTool(Component):
display_name: str = "Spider Web Crawler & Scraper"
description: str = "Spider API for web crawling and scraping."
Expand Down Expand Up @@ -130,3 +126,7 @@ def crawl(self) -> list[Data]:
else:
records.append(Data(data={"content": record["content"], "url": record["url"]}))
return records


class SpiderToolError(Exception):
"""SpiderTool error"""
65 changes: 40 additions & 25 deletions src/backend/base/langflow/components/toolkits/Metaphor.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,51 @@
from langchain_community.agent_toolkits.base import BaseToolkit
from langchain_core.tools import Tool, tool
from langchain_core.tools import tool
from metaphor_python import Metaphor

from langflow.custom import CustomComponent
from langflow.custom import Component
from langflow.field_typing import Tool
from langflow.io import BoolInput, IntInput, Output, SecretStrInput


class MetaphorToolkit(CustomComponent):
display_name: str = "Metaphor"
description: str = "Metaphor Toolkit"
class MetaphorToolkit(Component):
display_name = "Metaphor"
description = "Metaphor Toolkit for search and content retrieval"
documentation = "https://python.langchain.com/docs/integrations/tools/metaphor_search"
beta: bool = True
name = "Metaphor"
# api key should be password = True
field_config = {
"metaphor_api_key": {"display_name": "Metaphor API Key", "password": True},
"code": {"advanced": True},
}

def build(
self,
metaphor_api_key: str,
use_autoprompt: bool = True,
search_num_results: int = 5,
similar_num_results: int = 5,
) -> Tool | BaseToolkit:
# If documents, then we need to create a Vectara instance using .from_documents
client = Metaphor(api_key=metaphor_api_key)
beta = True

inputs = [
SecretStrInput(
name="metaphor_api_key",
display_name="Metaphor API Key",
password=True,
),
BoolInput(
name="use_autoprompt",
display_name="Use Autoprompt",
value=True,
),
IntInput(
name="search_num_results",
display_name="Search Number of Results",
value=5,
),
IntInput(
name="similar_num_results",
display_name="Similar Number of Results",
value=5,
),
]

outputs = [
Output(name="tools", display_name="Tools", method="build_toolkit"),
]

def build_toolkit(self) -> Tool:
client = Metaphor(api_key=self.metaphor_api_key)

@tool
def search(query: str):
"""Call search engine with a query."""
return client.search(query, use_autoprompt=use_autoprompt, num_results=search_num_results)
return client.search(query, use_autoprompt=self.use_autoprompt, num_results=self.search_num_results)

@tool
def get_contents(ids: list[str]):
Expand All @@ -46,6 +61,6 @@ def find_similar(url: str):
The url passed in should be a URL returned from `search`
"""
return client.find_similar(url, num_results=similar_num_results)
return client.find_similar(url, num_results=self.similar_num_results)

return [search, get_contents, find_similar]
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import nanoid
import yaml
from loguru import logger
from pydantic import BaseModel

from langflow.base.tools.constants import TOOL_OUTPUT_NAME
Expand Down Expand Up @@ -340,7 +339,6 @@ def _set_output_required_inputs(self):
source_code = inspect.getsource(method)
ast_tree = ast.parse(dedent(source_code))
except Exception: # noqa: BLE001
logger.opt(exception=True).debug(f"Could not get source code for method {method}")
source_code = self._code
ast_tree = ast.parse(dedent(source_code))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def filter_loaded_components(self, data: dict, with_errors: bool) -> dict:
component_tuple = (*build_component(component), component)
components.append(component_tuple)
except Exception: # noqa: BLE001
logger.opt(exception=True).debug(f"Error while loading component {component['name']}")
logger.debug(f"Error while loading component {component['name']} from {component['file']}")
continue
items.append({"name": menu["name"], "path": menu["path"], "components": components})
filtered = [menu for menu in items if menu["components"]]
Expand Down
7 changes: 5 additions & 2 deletions src/backend/base/langflow/graph/vertex/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,9 +370,12 @@ def _build_params(self):
val = field.get("value")
if field.get("type") == "code":
try:
params[field_name] = ast.literal_eval(val) if val else None
if field_name == "code":
params[field_name] = val
else:
params[field_name] = ast.literal_eval(val) if val else None
except Exception: # noqa: BLE001
logger.opt(exception=True).debug(f"Error evaluating code for {field_name}")
logger.debug(f"Error evaluating code for {field_name}")
params[field_name] = val
elif field.get("type") in ["dict", "NestedDict"]:
# When dict comes from the frontend it comes as a
Expand Down
Loading

0 comments on commit 2db7e8a

Please sign in to comment.