-
Notifications
You must be signed in to change notification settings - Fork 3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Migration to New Custom Components in Langflow #2335
Comments
To integrate the function signatures as new fields in the UI using the new
Here is the updated code with these steps: from langflow import CustomComponent
from typing import Any, Dict, List, Union
import ast
from langchain_core.tools import Tool
from langchain.tools import StructuredTool
from langflow.schema.dotdict import dotdict
from langchain.pydantic_v1 import BaseModel, Field, create_model
from loguru import logger
from langflow.custom.code_parser import CodeParser # Already defined methods included
class PythonMethodTool(CustomComponent):
display_name = "Python Method Tool"
description = "Creates a StructuredTool from a given Python function code."
documentation = "https://python.langchain.com/docs/modules/tools/custom_tools/#structuredtool-dataclass"
icon = "Python"
field_order = ["name", "description", "tool_code", "return_direct", "tool_function"]
def build_config(self) -> Dict[str, Any]:
return {
"tool_code": {
"display_name": "Tool Code",
"info": "Enter the dataclass code.",
"placeholder": "def my_function(args):\n pass",
},
"name": {
"display_name": "Tool Name",
"info": "Enter the name of the tool.",
},
"description": {
"display_name": "Description",
"info": "Provide a brief description of what the tool does.",
},
"return_direct": {
"display_name": "Return Directly",
"info": "Should the tool return the function output directly?",
},
"tool_function": {
"display_name": "Tool Function",
"info": "Select the function for additional expressions.",
"options": [],
"real_time_refresh": True,
"refresh_button": True,
},
}
def parse_source_name(self, code: str) -> List[str]:
try:
parser = CodeParser(code)
return [node.name for node in parser.get_tree().body if isinstance(node, ast.FunctionDef)]
except SyntaxError as e:
logger.error(f"Syntax error in code: {e}")
return []
def get_function_args(self, code: str, func_name: str) -> Dict[str, str]:
try:
parser = CodeParser(code)
func_def = next(node for node in parser.get_tree().body if isinstance(node, ast.FunctionDef) and node.name == func_name)
args_info = {}
for arg in func_def.args.args:
arg_name = arg.arg
param_type_str = 'Any'
if arg.annotation:
if isinstance(arg.annotation, ast.Subscript) and isinstance(arg.annotation.value, ast.Name) and arg.annotation.value.id == 'Optional':
param_type_str = f"Optional[{arg.annotation.slice.id}]"
else:
param_type_str = arg.annotation.id if isinstance(arg.annotation, ast.Name) else 'Any'
args_info[arg_name] = param_type_str
return args_info
except Exception as e:
logger.error(f"Error getting function args: {e}")
return {}
def update_build_config(self, build_config: dotdict, field_value: Any, field_name: Union[str, None] = None) -> dotdict:
try:
if field_name in ["tool_code", "tool_function"]:
build_config["tool_function"]["options"] = self.parse_source_name(build_config["tool_code"]["value"])
if field_name == "tool_function" and build_config["tool_function"]["value"]:
inputs = self.get_function_args(build_config["tool_code"]["value"], build_config["tool_function"]["value"])
build_config.update({name: {"display_name": name, "name": name, "field_type": "str", "required": True, "info": f"Write a description of the parameter {name}"} for name in inputs})
except Exception as e:
logger.error(f"Error updating build config: {e}")
self.status = f"Failed to update build config: {str(e)}"
return build_config
def create_args_schema(self, tool_code: str, function_name: str) -> Dict[str, BaseModel]:
inputs = self.get_function_args(tool_code, function_name)
fields = {name: (eval(_type), Field(description=name)) for name, _type in inputs.items()}
model = create_model('ToolInput', **fields, __base__=BaseModel)
return {'ToolInput': model}
async def build(self, tool_code: str, name: str, description: str, tool_function: str, return_direct: bool) -> Tool:
parser = CodeParser(tool_code)
func_node = next(node for node in parser.get_tree().body if isinstance(node, ast.FunctionDef) and node.name == tool_function)
local_namespace = {}
exec(compile(ast.Module(body=[func_node]), filename="<ast>", mode="exec"), globals(), local_namespace)
func = local_namespace[tool_function]
schema_dict = self.create_args_schema(tool_code, tool_function)
tool = StructuredTool.from_function(
func=func,
args_schema=schema_dict['ToolInput'],
name=name,
description=description,
return_direct=return_direct
)
return tool This code leverages the |
I would like an explanation of the structure that inherits from the |
To create custom components in Langflow, you need to define a class that inherits from
Here is an example: from langflow.custom import Component
from langflow.io import MessageTextInput, Output
from langflow.schema import Data
class MyCustomComponent(Component):
display_name = "My Custom Component"
description = "A template for creating custom components."
documentation = "http:https://docs.langflow.org/components/custom"
icon = "custom_components"
inputs = [
MessageTextInput(
name="input_value",
display_name="Input Value",
value="Hello, World!",
),
]
outputs = [
Output(display_name="Output", name="output", method="build_output"),
]
def build_output(self) -> Data:
data = Data(value=self.input_value)
self.status = data
return data Key Points:
By following these steps and examples, you can create custom components in Langflow tailored to your specific needs. The modular structure of Custom Components allows for flexible and reusable components that can be easily integrated into your workflows [1][2][3]. |
Hey @YamonBot The new component system is much more usable and easy. My suggestion would be to look at an existing component: All the paramters now must be in the The |
Thank you for your response. In other words, I want to dynamically add input objects directly to the |
We have previously written code that parses the function signatures from source code entered as a Code type in real-time and adds the relevant details as fields in the build configuration.
Now, it seems that Langflow has introduced a new concept of custom components (from langflow.custom import Component).
How can we use the existing design to add the signatures of specific methods as new fields in the UI?
The text was updated successfully, but these errors were encountered: