Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit0f6098a

Browse files
edwinjosechittilappillyogabrielluizanovazzi1Cristhianzlautofix-ci[bot]
authored
feat: add tool mode to components, Added current date tool to agent (langflow-ai#4439)
* Fix incorrect parameter names in _build_source method across multiple JSON files* ✅ (freeze.spec.ts, playground.spec.ts, stop-building.spec.ts, linkComponent.spec.ts, sliderComponent.spec.ts, tableInputComponent.spec.ts, stop-button-playground.spec.ts, generalBugs-shard-7.spec.ts): enable tests that were previously skipped to ensure proper functionality and coverage. Remove outdated comments and update test descriptions for clarity.* Refactor agent event processing to support message streaming and improve content handling* Refactor ChatOutput to enhance message handling and streamline property assignment* Fix session ID assignment in send_message method for better message handling* Add OnTokenFunctionType protocol for enhanced token handling* Add BorderTrail component for animated border effects* Add ContentBlockDisplay component for enhanced content visualization and loading state* Refactor TextShimmer to use motion.create for improved component animation* Add ContentBlockDisplay to render chat content blocks in newChatMessage component* Refactor `ChatOutput` class to use `MessageInput` instead of `MessageTextInput` for `input_value` across starter projects.* Update edge class name from 'runned' to 'ran' in flow components and store* Add 'on_build_start' and 'on_build_end' events to EventManager* Add build status updates for 'build_start' and 'build_end' events in buildUtils.ts* Integrate event management for output function in ComponentToolkit to track build start and end events* Refactor event handling in ComponentToolkit to improve build event tracking* Refactor messagesStore to update existing message if it already exists* update properties to have state attribute* format* Refactor chatMessage component to display loading state for partial chat messages* Refactor reactflowUtils to handle broken edges with missing display names* fix agent text output* [autofix.ci] apply automated fixes* [autofix.ci] apply automated fixes (attempt 2/3)* fix agent component initialization* Enhance error message formatting to include detailed exception information* Refactor agent component for improved performance and stability* Refactor `LCAgentComponent` to streamline agent execution logic and remove redundant methods* Add type casting for send_message function in agent.py* Change return type of function to 'Message' in log schema* Add `embedding_service` and `client` fields to JSON configurations and refactor ChatOutput class- Introduced `embedding_service` field in `Vector Store RAG.json` and `Travel Planning Agents.json` to support Astra Vectorize and embedding model selection.- Added `client` field to `OpenAIEmbeddingsComponent` in JSON configurations for enhanced client configuration.- Refactored `ChatOutput` class across multiple JSON files to include a new `_build_source` method for constructing `Source` objects, improving code modularity and readability.- Updated import paths for `OpenAIEmbeddings` to reflect changes in the module structure.* Update attribute handling in Component class to merge inputs with existing attributes* Update ChatInput and ChatOutput initialization to include session_id* Refactor test_load_flow_from_json_object to be asynchronous* Add asynchronous tests for agent event handling in test_agent_events.py* Add event handling functions for agent tool and chain events- Implement functions to handle various agent events such as `on_chain_start`, `on_chain_end`, `on_tool_start`, `on_tool_end`, and `on_tool_error`.- Introduce helper functions to build content blocks for agent messages.- Create mappings for chain and tool event handlers.- Refactor `process_agent_events` to utilize the new event handling functions.- Remove the old `process_agent_events` implementation from `agent.py` and import the new one from `events.py`.* feat: update content structure and validation logicEnhance content block to accept a list of contents instead of a single item, and implement validation to ensure proper format. Refactor tool-related content types for improved clarity and functionality.* Handle ValidationError in error message generation and update import paths* feat: enhance error event creation to include structured error content* move validators and remove utils.py* feat: add event handler tests for agent tool and chain events* refactor: streamline tool content structureCombine multiple tool-related types into a single, more flexible interface. This simplifies the content handling by allowing optional properties for output, error, and timestamp, enhancing overall code maintainability. Adjust the ContentBlock interface to accommodate an array of contents for improved flexibility.* feat: refactor error handling in ChatMessage component to support dynamic content blocks* feat: enhance ContentBlockDisplay to support Markdown rendering and dynamic content handling* Refactor agent event handling to simplify content block management* Enhance `ContentBlockDisplay` with separators and improved content rendering logic* add inline block to prevent text overflow in reason* Refactor code to enhance Markdown rendering and dynamic content handling in ChatMessage component* [autofix.ci] apply automated fixes* Add timestamp field to BaseContent class and remove from ToolContent class* Update timestamp validation to include fractional seconds in BaseContent class* Add duration calculation for agent and tool events in events.py* Refactor ContentBlock to use Pydantic's Discriminator and Tag for content types* Add field validators for content_blocks and properties in Message class* Add field serializer for source in Properties class* Add type hint for serialize_properties method in MessageTable class* create duration component and refactor contents* [autofix.ci] apply automated fixes* Refactor duration calculation to use perf_counter for improved accuracy and update ContentBlockDict to use dict for contents* Update properties field validator to use 'before' mode for improved validation* Refactor MessageTable to use ContentBlock instead of ContentBlockDict and enhance validation and serialization for properties and content_blocks* Refactor AgentComponent to streamline agent initialization by using the set method directly* Refactor event handling functions to use synchronous definitions and improve performance with asyncio.to_thread* Refactor PythonREPLToolComponent to raise ToolException on error instead of returning error message* Refactor CalculatorToolComponent to enhance error handling by raising ToolException and improving expression evaluation feedback* Fix TextShimmer width in ContentBlockDisplay for improved layout consistency* Enhance ContentBlockDisplay to support external links and math rendering in Markdown* Enhance error handling in Calculator and Python REPL tools by introducing `ToolException` and improving expression evaluation logic.* Refactor agent message properties to remove unnecessary icons and update content block titles for clarity* feat: enhance agent and tool content messagingAdd headers to agent and tool content messages for better clarity and user experience.* Handle nested schema structure in ContentBlock initialization* fix: update agent input text content return type and enhance error message formatting* Add placeholder and default value for model selection in AstraVectorStoreComponent* Refactor event handling functions to remove `send_message_method` parameter and streamline message processing logic.* Add model configuration to ToolContent for alias population* Refactor agent event tests to improve message handling and content block initialization* test: Update test durations for performance metricsAdjust the recorded execution times for various test cases to ensure accurate performance tracking and facilitate optimization efforts.* Refactor test_load_flow_from_json_object to improve project loading logic* Make `HeaderDict` fields optional and update `header` field in `BaseContent`* Enhance `Message` and `ChatOutput` with additional attributes for testing* Update test duration metrics in .test_durations file* Refactor `ContentDisplay` component to support multiple content types and improve rendering logic* feat: Enhance duration display with human-readable formatIntegrate the pretty-ms library to convert duration display metrics into a more user-friendly format, improving the overall user experience. Update dependencies to ensure compatibility with the latest version and optimize for newer Node.js versions.* feat: Add optional duration and header properties to BaseContent interface* fix: Change duration type from float to int in BaseContent class* Remove default value for 'start_time' in duration calculations* Enhance `ContentBlockDisplay` with dynamic header and expand/collapse animation- Added `state` prop to `ContentBlockDisplay` to dynamically set header icon and title based on content state.- Implemented `renderContent` function to encapsulate content rendering logic with animation.- Integrated `ForwardedIconComponent` for displaying header icons.- Updated `newChatMessage.tsx` to pass `state` prop to `ContentBlockDisplay`.* Add animation to header title using AnimatePresence and motion components* Add support for processing zip files with multithreading in FileComponent- Enhanced FileComponent to handle individual and zipped text files.- Introduced multithreading option for parallel processing of files within zip archives.- Updated supported file types to include zip files.- Improved error handling and logging for file processing.* Expand `Message` conversion to support `AsyncIterator` and `Iterator` types.* Remove unused function _find_or_create_tool_content from events.py* Add header information to tool content and streamline message sending in event processing* Add send_message_method parameter to event handlers for message dispatching- Updated event handler functions to include a new parameter, `send_message_method`, allowing for message dispatching within the handlers.- Modified the logic in each handler to utilize the `send_message_method` for sending messages.- Adjusted the main event processing logic to pass the `send_message_method` to the appropriate handlers.* Refactor ContentBlockDisplay component to improve rendering performance and user experience* Refactor `ContentBlockDisplay.tsx` to improve readability and update header title logic* [autofix.ci] apply automated fixes* Add 'start_time' to event data and update test functions to include send_message mock* Refactor ContentBlockDisplay component to include total duration and improve user experience* Refactor ContentBlockDisplay component to handle isLoading state for total duration calculation* Refactor animatedNumbers component and add AnimatedNumberBasic component- Refactor the animatedNumbers component to improve readability and update the header title logic.- Add a new component called AnimatedNumberBasic that displays an animated number with a specific value.* Refactor agent message creation to improve event processing efficiency* Refactor session ID assignment in run_graph_internal for improved clarity* [autofix.ci] apply automated fixes* fix: update agent message properties handling for improved compatibility* fix: enhance message property validation to support dictionary input* Add session_id to agent message initialization in tests- Updated test cases in `test_agent_events.py` to include `session_id` in the `Message` initialization.- Adjusted calls to `process_agent_events` to pass the `agent_message` with `session_id`.* feat: Enhance event handling with duration trackingAdd start_time parameter to event handling functions to ensure consistent duration calculations across different stages of agent processing. This improves accuracy in measuring event durations and enhances overall event management.* Add optional humanized value to AnimatedNumber component and update DurationDisplay usage* Refactor `ContentDisplay` and add separator to `ContentBlockDisplay` component* Add header to text content in agent message events* Add separator between each content block in ContentBlockDisplay component* Refactor layout in ContentDisplay component for improved styling and positioning* Refactor event handlers to return updated start_time and agent_message- Modified event handler functions to return a tuple of `agent_message` and `start_time`.- Updated `_calculate_duration` to handle `start_time` as an integer.- Ensured `start_time` is reset using `perf_counter()` after each event handling.- Adjusted tool and chain event handler calls to accommodate the new return type.* Add start_time and duration checks to agent event handlers in tests- Updated test cases for `handle_on_chain_start`, `handle_on_chain_end`, `handle_on_tool_start`, `handle_on_tool_end`, `handle_on_tool_error`, and `handle_on_chain_stream` to include `start_time` as a return value.- Added assertions to verify that `start_time` is a float and `duration` is an integer where applicable.* [autofix.ci] apply automated fixes* update colors and spacing of time* [autofix.ci] apply automated fixes* Refactor DurationDisplay component to display duration in seconds* Rename case from "message" to "add_message" in buildUtils.ts switch statement* Add event registration for message removal in EventManager* Add category handling for message events in Component class* Add custom exception handling for agent message processing* Handle exceptions in agent event processing with message deletion and event notification* Add new LLM options and refactor AgentComponent for dynamic provider handling- Introduced new language model options: Anthropic, Groq, and NVIDIA.- Refactored `AgentComponent` to utilize `MODEL_PROVIDERS_DICT` for dynamic provider handling.- Simplified input management by removing hardcoded provider inputs and using a dictionary-based approach.- Enhanced `update_build_config` to support flexible provider configurations and custom options.* Refactor buildUtils.ts and add message removal handling* Update Source model to allow None values for id, display_name, and source fields* Refactor event handler functions to return tuple of Message and float* Refactor `ChatOutput` class to use `MessageInput` instead of `MessageTextInput` for `input_value` across starter projects.* Add test for updating component outputs with dynamic code input* feat: add ToolModeMixin to manage tool mode state* feat: add parameterName to mutateTemplate for enhanced template mutation* feat: add tool mode functionality to node toolbarImplement a toggle for tool mode, allowing users to easily switch functionalities within the node toolbar. This enhancement improves user interaction by providing a dedicated mode for tool-related tasks.* feat: integrate ToolModeMixin into MessageTextInput for enhanced functionality* Update parameterId to "tool_mode" in nodeToolbarComponent* feat: implement tool mode output handling in run_and_validate_update_outputs* feat: add conditional rendering for tool mode button based on template fields* fix: enhance null checks for tool mode button visibility and output validation* feat: add isToolMode property to NodeInputFieldComponentType for enhanced functionality* feat: add isToolMode prop to NodeInputField for conditional styling* feat: implement sorting logic for tool mode fields in GenericNode component* feat: add isToolMode prop to NodeOutputField for conditional styling* feat: pass isToolMode prop to NodeOutputField for conditional styling* feat: update disabled logic in NodeInputField to include isToolMode* Add default placeholder to getPlaceholder function and constants file* feat: Enable dynamic placeholders in input componentsAdd support for customizable placeholder text across various input components to enhance usability and improve user experience.* feat: Add optional placeholder prop to InputProps type* feat: Add placeholder prop to InputGlobalComponent and CustomParameterComponent* feat: Set dynamic placeholder for NodeInputField based on tool mode* feat: Update NodeOutputField styling for tool mode and pass isToolMode prop* feat: Add isToolMode prop to OutputComponent for dynamic styling* feat: Add TOOL_OUTPUT_DISPLAY_NAME constant for toolset display* feat: Update tool output display name to use TOOL_OUTPUT_DISPLAY_NAME constant* feat: Conditionally render Freeze Path button based on tool mode* Add support for asynchronous output methods and tool mode validation in component tools* feat: Validate required inputs for tool mode before executing output methods* Refactor: Rename method to indicate private access in custom_component- Changed `get_function_entrypoint_return_type` to `_get_function_entrypoint_return_type` in `custom_component.py` to reflect its intended private usage.- Updated references to the renamed method in `utils.py` and `directory_reader.py` to maintain consistency.* feat: Implement tool output mapping based on tool mode presence in inputs* Refactor tests to use private method _get_function_entrypoint_return_type* feat: Enable tool mode for input_value in LCAgentComponent* Add test for updating component outputs with dynamic code input* feat: add tool mode functionality to node toolbarImplement a toggle for tool mode, allowing users to easily switch functionalities within the node toolbar. This enhancement improves user interaction by providing a dedicated mode for tool-related tasks.* feat: add conditional rendering for tool mode button based on template fields* feat: add isToolMode prop to NodeInputField for conditional styling* feat: Set dynamic placeholder for NodeInputField based on tool mode* feat: Add TOOL_OUTPUT_DISPLAY_NAME constant for toolset display* feat: Conditionally render Freeze Path button based on tool mode* Add tool mode support to LCAgentComponent- Introduced new input fields: `agent_name`, `agent_description`, and `add_tools_to_description` to support tool mode.- Implemented methods `get_tool_name`, `get_tool_description`, `_build_tools_description`, and `to_toolkit` for handling tool-related functionalities.- Enhanced `MessageTextInput` with additional information for better user guidance.- Updated agent message sender name to use `agent_name` if available.* Fix return statement placement in event handling logic* Add tool mode enhancements and error handling in component_tool- Introduce optional parameters `tool_name`, `tool_description`, and `callbacks` to `get_tools` method.- Implement error handling for tool creation with `handle_tool_error` and `callbacks`.- Ensure single tool validation when `tool_name` or `tool_description` is provided.- Add support for `BaseModel` result serialization using `model_dump`.* Refactor agent response method and update output configuration* Remove unused 'input_value' field from tool_calling.py configuration* Refactor source property assignment to use _build_source method* Enhance callable input check and add callbacks to toolkit conversion* Add unit tests for message update functionality in backend- Implement tests for updating single and multiple messages.- Add tests for handling nonexistent messages during updates.- Include tests for updating messages with timestamps, content blocks, and nested properties.- Ensure proper serialization and storage of message properties.* Add field serializer for 'output' using jsonable_encoder in content_types.py* Add tool mode fields and refactor message response in starter projects- Introduced new fields `add_tools_to_description`, `agent_description`, and `agent_name` for tool mode configuration in JSON starter projects.- Refactored `message_response` method to utilize `_build_source` for constructing message source properties.- Updated method references from `get_response` to `message_response` for consistency.- Adjusted input field descriptions and added missing metadata attributes.* Implement no-op send_message function and patching decorator for component tools* Refactor output handling in component tool to support Message and Data types* Simplify exception handling by removing redundant exception re-raise* Enhance tool assignment logic to preserve existing name and description if not provided* feat: Enhance agent name and description handlingRefactor the agent component to dynamically include tool names in the default agent name and description. This improves clarity for users by providing more context about the agent's capabilities and ensures consistent representation of tools in the interface.* refactor: Update agent description and name info to include default values and dynamic tool integration* Add custom encoders for serialization and refactor schema modules- Introduce `CUSTOM_ENCODERS` in `encoders.py` to handle serialization of `Callable` and `datetime` objects.- Refactor `BaseContent` to use `model_serializer` for model serialization with custom encoders.- Remove redundant `encode_callable` function and `CUSTOM_ENCODERS` definition from `artifact.py`.- Update imports and clean up unused imports in schema modules.* Remove 'agent_name' field and update 'get_tool_name' method in agent.py* Enhance `serialize_model` method with `wrap` mode and improved error handling* Add 'tool_mode' attribute to frontend node class* Add unit tests for ContentBlock initialization and content handling* Add unit tests for content types serialization and creation* Refactor tool mode initialization logic in NodeToolbarComponent* Add tool mode functionality to node toolbar and flow store* Add updateNodeInternals call for tool_mode case in nodeToolbarComponent* Add condition to hide handle in tool mode in NodeInputField component* Add shortcut for activating Tool Mode and integrate into node toolbar* Add tool_mode parameter to MessageTextInput and update attributes mapping* Remove 'agent_name' field from Agent Flow configuration file* Update agent message to use display_name instead of agent_name* new components with tool mode* updated the tests and also updated api request to accept the data from tool calling agent* added current date as tool* [autofix.ci] apply automated fixes* Add validation for required tools in agent execution and component setup* Make 'tools' field required in AgentComponent configuration* test: add unit tests for run_and_validate_update_outputs functionalityImplement comprehensive tests for the `run_and_validate_update_outputs` method across various scenarios, including enabling/disabling tool mode, handling invalid output structures, and supporting custom update logic. Validate that outputs are correctly updated and ensure appropriate error handling for invalid cases.* remove tool_mode from Chrome* Update agent.pyadding current date tool to agent* test: update component toolkit tests to use CalculatorToolComponent* Enhance input schema creation logic for tool mode components* Include input expression in error responses for calculator tool* Enhance `visit_Attribute` to check for required inputs in `tree_visitor.py`* fix: add checks for graph attribute before accessing session and flow IDs in Component methods* fix: set default value to None for id field in PlaygroundEvent model* fix: remove unused add_toolkit_output flag from FeatureFlags model* Refactor JSON configurations to remove unnecessary required inputs across starter projects* Add tool mode validation and improve error handling- Updated import statement for ContentBlock to fix import path.- Modified `send_message_noop` to require a `Message` parameter and added type ignore for method assignment.- Enhanced error message in tool mode validation to handle `None` input names.- Changed return type of `send_error_message` to `Message` for consistency.- Provided default value for `get_tool_name` to handle missing display names.* Add pytest fixture to test_component_message_sending test* fix linkComponent test* Skip flaky test in stop-building.spec.ts* new components with tool mode* updated the tests and also updated api request to accept the data from tool calling agent* added current date as tool* [autofix.ci] apply automated fixes* remove tool_mode from Chrome* Update agent.pyadding current date tool to agent* Ensure tools is a list before appending CurrentDateComponent in AgentComponent* Add pytest fixture 'client' to component test functions* Use 'client' fixture in test_component_streaming_message* Skip flaky test in stop-building.spec and add tool_mode to MessageTextInput* [autofix.ci] apply automated fixes* Update agent.pyupdates to solve the error in Date component as tool.* Add `updateComponentCode` function to enhance code update flexibility- Introduced `updateComponentCode` function to handle import and input updates more flexibly using regex patterns.- Updated unit test to utilize the new function for modifying component code, including adding `LinkInput` configuration.* Add tool mode to components and introduce current date tool option- Added `tool_mode` attribute to `MessageTextInput` in `CalculatorToolComponent` and `URLComponent` to enable tool mode functionality.- Introduced `add_current_date_tool` option in `AgentComponent` to allow agents to include a tool that returns the current date.- Updated `AgentComponent` to handle the addition of the current date tool as a `StructuredTool`.* update test code generation* remove meta key to ctrl---------Co-authored-by: Gabriel Luiz Freitas Almeida <gabriel@langflow.org>Co-authored-by: anovazzi1 <otavio2204@gmail.com>Co-authored-by: cristhianzl <cristhian.lousa@gmail.com>Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>Co-authored-by: phact <estevezsebastian@gmail.com>
1 parent0bf7dda commit0f6098a

File tree

12 files changed

+145
-25
lines changed

12 files changed

+145
-25
lines changed

‎src/backend/base/langflow/components/agents/agent.py‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1+
fromlangchain_core.toolsimportStructuredTool
2+
13
fromlangflow.base.agents.agentimportLCToolsAgentComponent
24
fromlangflow.base.models.model_input_constantsimportALL_PROVIDER_FIELDS,MODEL_PROVIDERS_DICT
35
fromlangflow.components.agents.tool_callingimportToolCallingAgentComponent
6+
fromlangflow.components.helpersimportCurrentDateComponent
47
fromlangflow.components.helpers.memoryimportMemoryComponent
5-
fromlangflow.ioimportDropdownInput,MultilineInput,Output
8+
fromlangflow.ioimportBoolInput,DropdownInput,MultilineInput,Output
69
fromlangflow.schema.dotdictimportdotdict
710
fromlangflow.schema.messageimportMessage
811

@@ -41,6 +44,13 @@ class AgentComponent(ToolCallingAgentComponent):
4144
),
4245
*LCToolsAgentComponent._base_inputs,
4346
*memory_inputs,
47+
BoolInput(
48+
name="add_current_date_tool",
49+
display_name="Add tool Current Date",
50+
advanced=True,
51+
info="If true, will add a tool to the agent that returns the current date.",
52+
value=True,
53+
),
4454
]
4555
outputs= [Output(name="response",display_name="Response",method="message_response")]
4656

@@ -50,6 +60,18 @@ async def message_response(self) -> Message:
5060
msg="No language model selected"
5161
raiseValueError(msg)
5262
self.chat_history=self.get_memory_data()
63+
64+
ifself.add_current_date_tool:
65+
ifnotisinstance(self.tools,list):# type: ignore[has-type]
66+
self.tools= []
67+
# Convert CurrentDateComponent to a StructuredTool
68+
current_date_tool=CurrentDateComponent().to_toolkit()[0]
69+
ifisinstance(current_date_tool,StructuredTool):
70+
self.tools.append(current_date_tool)
71+
else:
72+
msg="CurrentDateComponent must be converted to a StructuredTool"
73+
raiseValueError(msg)
74+
5375
ifnotself.tools:
5476
msg="Tools are required to run the agent."
5577
raiseValueError(msg)
@@ -150,7 +172,19 @@ def update_build_config(self, build_config: dotdict, field_value: str, field_nam
150172
build_config=self.update_input_types(build_config)
151173

152174
# Validate required keys
153-
default_keys= ["code","_type","agent_llm","tools","input_value"]
175+
default_keys= [
176+
"code",
177+
"_type",
178+
"agent_llm",
179+
"tools",
180+
"input_value",
181+
"add_current_date_tool",
182+
"system_prompt",
183+
"agent_description",
184+
"max_iterations",
185+
"handle_parsing_errors",
186+
"verbose",
187+
]
154188
missing_keys= [keyforkeyindefault_keysifkeynotinbuild_config]
155189
ifmissing_keys:
156190
msg=f"Missing required keys in build_config:{missing_keys}"

‎src/backend/base/langflow/components/custom_component/custom_component.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,13 @@ class CustomComponent(Component):
1212
name="CustomComponent"
1313

1414
inputs= [
15-
MessageTextInput(name="input_value",display_name="Input Value",value="Hello, World!",tool_mode=True),
15+
MessageTextInput(
16+
name="input_value",
17+
display_name="Input Value",
18+
info="This is a custom component Input",
19+
value="Hello, World!",
20+
tool_mode=True,
21+
),
1622
]
1723

1824
outputs= [

‎src/backend/base/langflow/components/data/api_request.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ class APIRequestComponent(Component):
3838
"This will fill in the dictionary fields for headers and body.",
3939
advanced=False,
4040
refresh_button=True,
41+
real_time_refresh=True,
42+
tool_mode=True,
4143
),
4244
DropdownInput(
4345
name="method",
@@ -63,6 +65,7 @@ class APIRequestComponent(Component):
6365
name="query_params",
6466
display_name="Query Parameters",
6567
info="The query parameters to append to the URL.",
68+
tool_mode=True,
6669
),
6770
IntInput(
6871
name="timeout",
@@ -176,7 +179,11 @@ async def make_requests(self) -> list[Data]:
176179
headers=self.headersor {}
177180
body=self.bodyor {}
178181
timeout=self.timeout
179-
query_params=self.query_params.dataifself.query_paramselse {}
182+
183+
ifisinstance(self.query_params,str):
184+
query_params=dict(parse_qsl(self.query_params))
185+
else:
186+
query_params=self.query_params.dataifself.query_paramselse {}
180187

181188
ifcurl:
182189
self._build_config=self.parse_curl(curl,dotdict())

‎src/backend/base/langflow/components/data/url.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ class URLComponent(Component):
2121
display_name="URLs",
2222
info="Enter one or more URLs, by clicking the '+' button.",
2323
is_list=True,
24+
tool_mode=True,
2425
),
2526
DropdownInput(
2627
name="format",

‎src/backend/base/langflow/components/helpers/current_date.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ class CurrentDateComponent(Component):
5656
],
5757
value="UTC",
5858
info="Select the timezone for the current date and time.",
59+
tool_mode=True,
5960
),
6061
]
6162
outputs= [

‎src/backend/base/langflow/components/tools/calculator.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ class CalculatorToolComponent(LCToolComponent):
2323
name="expression",
2424
display_name="Expression",
2525
info="The arithmetic expression to evaluate (e.g., '4*4*(33/22)+12-20').",
26+
tool_mode=True,
2627
),
2728
]
2829

‎src/backend/base/langflow/initial_setup/starter_projects/Agent Flow.json‎

Lines changed: 18 additions & 2 deletions
Large diffs are not rendered by default.

‎src/backend/base/langflow/initial_setup/starter_projects/Blog Writer.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@
202202
"show":true,
203203
"title_case":false,
204204
"type":"code",
205-
"value": "import re\n\nfrom langchain_community.document_loaders import AsyncHtmlLoader, WebBaseLoader\n\nfrom langflow.custom import Component\nfrom langflow.helpers.data import data_to_text\nfrom langflow.io import DropdownInput, MessageTextInput, Output\nfrom langflow.schema import Data\nfrom langflow.schema.message import Message\n\n\nclass URLComponent(Component):\n display_name = \"URL\"\n description = \"Fetch content from one or more URLs.\"\n icon = \"layout-template\"\n name = \"URL\"\n\n inputs = [\n MessageTextInput(\n name=\"urls\",\n display_name=\"URLs\",\n info=\"Enter one or more URLs, by clicking the '+' button.\",\n is_list=True,\n ),\n DropdownInput(\n name=\"format\",\n display_name=\"Output format\",\n info=\"Output format. Use 'Text' to extract the text from the HTML or 'Raw HTML' for the raw HTML content.\",\n options=[\"Text\", \"Raw HTML\"],\n value=\"Text\",\n ),\n ]\n\n outputs = [\n Output(display_name=\"Data\", name=\"data\", method=\"fetch_content\"),\n Output(display_name=\"Text\", name=\"text\", method=\"fetch_content_text\"),\n ]\n\n def ensure_url(self, string: str) -> str:\n \"\"\"Ensures the given string is a URL by adding 'http://' if it doesn't start with 'http://' or 'https://'.\n\n Raises an error if the string is not a valid URL.\n\n Parameters:\n string (str): The string to be checked and possibly modified.\n\n Returns:\n str: The modified string that is ensured to be a URL.\n\n Raises:\n ValueError: If the string is not a valid URL.\n \"\"\"\n if not string.startswith((\"http://\", \"https://\")):\n string = \"http://\" + string\n\n # Basic URL validation regex\n url_regex = re.compile(\n r\"^(https?:\\/\\/)?\" # optional protocol\n r\"(www\\.)?\" # optional www\n r\"([a-zA-Z0-9.-]+)\" # domain\n r\"(\\.[a-zA-Z]{2,})?\" # top-level domain\n r\"(:\\d+)?\" # optional port\n r\"(\\/[^\\s]*)?$\", # optional path\n re.IGNORECASE,\n )\n\n if not url_regex.match(string):\n msg = f\"Invalid URL: {string}\"\n raise ValueError(msg)\n\n return string\n\n def fetch_content(self) -> list[Data]:\n urls = [self.ensure_url(url.strip()) for url in self.urls if url.strip()]\n if self.format == \"Raw HTML\":\n loader = AsyncHtmlLoader(web_path=urls, encoding=\"utf-8\")\n else:\n loader = WebBaseLoader(web_paths=urls, encoding=\"utf-8\")\n docs = loader.load()\n data = [Data(text=doc.page_content, **doc.metadata) for doc in docs]\n self.status = data\n return data\n\n def fetch_content_text(self) -> Message:\n data = self.fetch_content()\n\n result_string = data_to_text(\"{text}\", data)\n self.status = result_string\n return Message(text=result_string)\n"
205+
"value": "import re\n\nfrom langchain_community.document_loaders import AsyncHtmlLoader, WebBaseLoader\n\nfrom langflow.custom import Component\nfrom langflow.helpers.data import data_to_text\nfrom langflow.io import DropdownInput, MessageTextInput, Output\nfrom langflow.schema import Data\nfrom langflow.schema.message import Message\n\n\nclass URLComponent(Component):\n display_name = \"URL\"\n description = \"Fetch content from one or more URLs.\"\n icon = \"layout-template\"\n name = \"URL\"\n\n inputs = [\n MessageTextInput(\n name=\"urls\",\n display_name=\"URLs\",\n info=\"Enter one or more URLs, by clicking the '+' button.\",\n is_list=True,\n tool_mode=True,\n ),\n DropdownInput(\n name=\"format\",\n display_name=\"Output format\",\n info=\"Output format. Use 'Text' to extract the text from the HTML or 'Raw HTML' for the raw HTML content.\",\n options=[\"Text\", \"Raw HTML\"],\n value=\"Text\",\n ),\n ]\n\n outputs = [\n Output(display_name=\"Data\", name=\"data\", method=\"fetch_content\"),\n Output(display_name=\"Text\", name=\"text\", method=\"fetch_content_text\"),\n ]\n\n def ensure_url(self, string: str) -> str:\n \"\"\"Ensures the given string is a URL by adding 'http://' if it doesn't start with 'http://' or 'https://'.\n\n Raises an error if the string is not a valid URL.\n\n Parameters:\n string (str): The string to be checked and possibly modified.\n\n Returns:\n str: The modified string that is ensured to be a URL.\n\n Raises:\n ValueError: If the string is not a valid URL.\n \"\"\"\n if not string.startswith((\"http://\", \"https://\")):\n string = \"http://\" + string\n\n # Basic URL validation regex\n url_regex = re.compile(\n r\"^(https?:\\/\\/)?\" # optional protocol\n r\"(www\\.)?\" # optional www\n r\"([a-zA-Z0-9.-]+)\" # domain\n r\"(\\.[a-zA-Z]{2,})?\" # top-level domain\n r\"(:\\d+)?\" # optional port\n r\"(\\/[^\\s]*)?$\", # optional path\n re.IGNORECASE,\n )\n\n if not url_regex.match(string):\n msg = f\"Invalid URL: {string}\"\n raise ValueError(msg)\n\n return string\n\n def fetch_content(self) -> list[Data]:\n urls = [self.ensure_url(url.strip()) for url in self.urls if url.strip()]\n if self.format == \"Raw HTML\":\n loader = AsyncHtmlLoader(web_path=urls, encoding=\"utf-8\")\n else:\n loader = WebBaseLoader(web_paths=urls, encoding=\"utf-8\")\n docs = loader.load()\n data = [Data(text=doc.page_content, **doc.metadata) for doc in docs]\n self.status = data\n return data\n\n def fetch_content_text(self) -> Message:\n data = self.fetch_content()\n\n result_string = data_to_text(\"{text}\", data)\n self.status = result_string\n return Message(text=result_string)\n"
206206
},
207207
"format": {
208208
"_input_type":"DropdownInput",

‎src/backend/base/langflow/initial_setup/starter_projects/Travel Planning Agents.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2475,7 +2475,7 @@
24752475
"show":true,
24762476
"title_case":false,
24772477
"type":"code",
2478-
"value": "import ast\nimport operator\n\nfrom langchain.tools import StructuredTool\nfrom langchain_core.tools import ToolException\nfrom loguru import logger\nfrom pydantic import BaseModel, Field\n\nfrom langflow.base.langchain_utilities.model import LCToolComponent\nfrom langflow.field_typing import Tool\nfrom langflow.inputs import MessageTextInput\nfrom langflow.schema import Data\n\n\nclass CalculatorToolComponent(LCToolComponent):\n display_name = \"Calculator\"\n description = \"Perform basic arithmetic operations on a given expression.\"\n icon = \"calculator\"\n name = \"CalculatorTool\"\n\n inputs = [\n MessageTextInput(\n name=\"expression\",\n display_name=\"Expression\",\n info=\"The arithmetic expression to evaluate (e.g., '4*4*(33/22)+12-20').\",\n ),\n ]\n\n class CalculatorToolSchema(BaseModel):\n expression: str = Field(..., description=\"The arithmetic expression to evaluate.\")\n\n def run_model(self) -> list[Data]:\n return self._evaluate_expression(self.expression)\n\n def build_tool(self) -> Tool:\n return StructuredTool.from_function(\n name=\"calculator\",\n description=\"Evaluate basic arithmetic expressions. Input should be a string containing the expression.\",\n func=self._eval_expr_with_error,\n args_schema=self.CalculatorToolSchema,\n )\n\n def _eval_expr(self, node):\n # Define the allowed operators\n operators = {\n ast.Add: operator.add,\n ast.Sub: operator.sub,\n ast.Mult: operator.mul,\n ast.Div: operator.truediv,\n ast.Pow: operator.pow,\n }\n if isinstance(node, ast.Num):\n return node.n\n if isinstance(node, ast.BinOp):\n return operators[type(node.op)](self._eval_expr(node.left), self._eval_expr(node.right))\n if isinstance(node, ast.UnaryOp):\n return operators[type(node.op)](self._eval_expr(node.operand))\n if isinstance(node, ast.Call):\n msg = (\n \"Function calls like sqrt(), sin(), cos() etc. are not supported. \"\n \"Only basic arithmetic operations (+, -, *, /, **) are allowed.\"\n )\n raise TypeError(msg)\n msg = f\"Unsupported operation or expression type: {type(node).__name__}\"\n raise TypeError(msg)\n\n def _eval_expr_with_error(self, expression: str) -> list[Data]:\n try:\n return self._evaluate_expression(expression)\n except Exception as e:\n raise ToolException(str(e)) from e\n\n def _evaluate_expression(self, expression: str) -> list[Data]:\n try:\n # Parse the expression and evaluate it\n tree = ast.parse(expression, mode=\"eval\")\n result = self._eval_expr(tree.body)\n\n # Format the result to a reasonable number of decimal places\n formatted_result = f\"{result:.6f}\".rstrip(\"0\").rstrip(\".\")\n\n self.status = formatted_result\n return [Data(data={\"result\": formatted_result})]\n\n except (SyntaxError, TypeError, KeyError) as e:\n error_message = f\"Invalid expression: {e}\"\n self.status = error_message\n return [Data(data={\"error\": error_message, \"input\": expression})]\n except ZeroDivisionError:\n error_message = \"Error: Division by zero\"\n self.status = error_message\n return [Data(data={\"error\": error_message, \"input\": expression})]\n except Exception as e: # noqa: BLE001\n logger.opt(exception=True).debug(\"Error evaluating expression\")\n error_message = f\"Error: {e}\"\n self.status = error_message\n return [Data(data={\"error\": error_message, \"input\": expression})]\n"
2478+
"value": "import ast\nimport operator\n\nfrom langchain.tools import StructuredTool\nfrom langchain_core.tools import ToolException\nfrom loguru import logger\nfrom pydantic import BaseModel, Field\n\nfrom langflow.base.langchain_utilities.model import LCToolComponent\nfrom langflow.field_typing import Tool\nfrom langflow.inputs import MessageTextInput\nfrom langflow.schema import Data\n\n\nclass CalculatorToolComponent(LCToolComponent):\n display_name = \"Calculator\"\n description = \"Perform basic arithmetic operations on a given expression.\"\n icon = \"calculator\"\n name = \"CalculatorTool\"\n\n inputs = [\n MessageTextInput(\n name=\"expression\",\n display_name=\"Expression\",\n info=\"The arithmetic expression to evaluate (e.g., '4*4*(33/22)+12-20').\",\n tool_mode=True,\n ),\n ]\n\n class CalculatorToolSchema(BaseModel):\n expression: str = Field(..., description=\"The arithmetic expression to evaluate.\")\n\n def run_model(self) -> list[Data]:\n return self._evaluate_expression(self.expression)\n\n def build_tool(self) -> Tool:\n return StructuredTool.from_function(\n name=\"calculator\",\n description=\"Evaluate basic arithmetic expressions. Input should be a string containing the expression.\",\n func=self._eval_expr_with_error,\n args_schema=self.CalculatorToolSchema,\n )\n\n def _eval_expr(self, node):\n # Define the allowed operators\n operators = {\n ast.Add: operator.add,\n ast.Sub: operator.sub,\n ast.Mult: operator.mul,\n ast.Div: operator.truediv,\n ast.Pow: operator.pow,\n }\n if isinstance(node, ast.Num):\n return node.n\n if isinstance(node, ast.BinOp):\n return operators[type(node.op)](self._eval_expr(node.left), self._eval_expr(node.right))\n if isinstance(node, ast.UnaryOp):\n return operators[type(node.op)](self._eval_expr(node.operand))\n if isinstance(node, ast.Call):\n msg = (\n \"Function calls like sqrt(), sin(), cos() etc. are not supported. \"\n \"Only basic arithmetic operations (+, -, *, /, **) are allowed.\"\n )\n raise TypeError(msg)\n msg = f\"Unsupported operation or expression type: {type(node).__name__}\"\n raise TypeError(msg)\n\n def _eval_expr_with_error(self, expression: str) -> list[Data]:\n try:\n return self._evaluate_expression(expression)\n except Exception as e:\n raise ToolException(str(e)) from e\n\n def _evaluate_expression(self, expression: str) -> list[Data]:\n try:\n # Parse the expression and evaluate it\n tree = ast.parse(expression, mode=\"eval\")\n result = self._eval_expr(tree.body)\n\n # Format the result to a reasonable number of decimal places\n formatted_result = f\"{result:.6f}\".rstrip(\"0\").rstrip(\".\")\n\n self.status = formatted_result\n return [Data(data={\"result\": formatted_result})]\n\n except (SyntaxError, TypeError, KeyError) as e:\n error_message = f\"Invalid expression: {e}\"\n self.status = error_message\n return [Data(data={\"error\": error_message, \"input\": expression})]\n except ZeroDivisionError:\n error_message = \"Error: Division by zero\"\n self.status = error_message\n return [Data(data={\"error\": error_message, \"input\": expression})]\n except Exception as e: # noqa: BLE001\n logger.opt(exception=True).debug(\"Error evaluating expression\")\n error_message = f\"Error: {e}\"\n self.status = error_message\n return [Data(data={\"error\": error_message, \"input\": expression})]\n"
24792479
},
24802480
"expression": {
24812481
"_input_type":"MessageTextInput",

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp