feat: Implement tool mode functionality and dynamic placeholders across input components (#4402)

* Update content_blocks initialization and add flow_id parameter to ErrorMessage

* feat: include vertex ID in class instantiation

Pass the vertex ID to the custom component during instantiation to facilitate event tracking or management capabilities.

* fix: update message streaming logic to handle None messages and refactor _stream_message parameters

* feat: include flow_id in ChatOutput initialization

Add flow_id to the ChatOutput class to improve the tracking of conversational flows, enhancing the context management within the chat system.

* fix: update chat message source display to use 'source' instead of 'display_name'

* feat: add flow_id to message initialization in ChatOutput class

* fix: handle JSON parsing with type checks for message properties

Refine JSON loading to ensure proper type handling for message properties and content blocks, enhancing stability and preventing potential errors with non-string inputs.

* refactor: update logging structure and message handling

Improve the output logs to support logging multiple entries and ensure robust message streaming with type checking. Adjust error handling parameters for consistency.

* feat: restrict event types in registration and sending

Enhance event management by explicitly defining allowed event types, improving code clarity and reducing potential errors. This ensures only valid event types are registered and sent, leading to more robust event handling.

* Update `logs` attribute to store lists of `Log` objects in `Vertex` class

* feat: introduce TypedDicts for ContentBlock and Properties, update default values in Message model

* fix: restrict event types in send_event method to improve data validation

* Set default values for 'id', 'display_name', and 'source' fields in Source schema

* [autofix.ci] apply automated fixes

* fix: update query to use equality check for error messages

* make lint

* update simple agent test

* test: enhance EventManager tests for event_id validation

* feat: add background, chat icon, and text color properties to component toolkit

* fix: update LogComponent name to display_name for consistency

* remove playground from new cards on main page

* refactor: Update Properties handling in MessageTable and remove unused PropertiesDict

* fix: Set default value for category in MessageBase model

* fix: Update properties default factory in MessageTable model to use model_dump

* Add _build_source method to ChatOutput and update test inputs to use Message objects

* 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 logic

Enhance 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 structure

Combine 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 messaging

Add 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 metrics

Adjust 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 format

Integrate 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 tracking

Add 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 toolbar

Implement 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 components

Add 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 toolbar

Implement 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 handling

Refactor 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

* 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 functionality

Implement 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.

* 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

---------

Co-authored-by: anovazzi1 <otavio2204@gmail.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: cristhianzl <cristhian.lousa@gmail.com>
This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-11-07 23:31:04 -03:00 • committed by GitHub
commit 1e4594ad43
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
68 changed files with 1624 additions and 597 deletions

View file

@ -10,7 +10,9 @@ from langflow.base.agents.callback import AgentAsyncHandler
from langflow.base.agents.events import ExceptionWithMessageError, process_agent_events
from langflow.base.agents.utils import data_to_messages
from langflow.custom import Component
from langflow.inputs.inputs import InputTypes
from langflow.custom.custom_component.component import _get_component_toolkit
from langflow.field_typing import Tool
from langflow.inputs.inputs import InputTypes, MultilineInput
from langflow.io import BoolInput, HandleInput, IntInput, MessageTextInput
from langflow.memory import delete_message
from langflow.schema import Data
@ -24,10 +26,19 @@ if TYPE_CHECKING:
from langchain_core.messages import BaseMessage
DEFAULT_TOOLS_DESCRIPTION = "A helpful assistant with access to the following tools:"
DEFAULT_AGENT_NAME = "Agent ({tools_names})"
class LCAgentComponent(Component):
trace_type = "agent"
_base_inputs: list[InputTypes] = [
MessageTextInput(name="input_value", display_name="Input"),
MessageTextInput(
name="input_value",
display_name="Input",
info="The input provided by the user for the agent to process.",
tool_mode=True,
),
BoolInput(
name="handle_parsing_errors",
display_name="Handle Parse Errors",
@ -46,6 +57,16 @@ class LCAgentComponent(Component):
value=15,
advanced=True,
),
MultilineInput(
name="agent_description",
display_name="Agent Description",
info=(
"The description of the agent. This is only used when in Tool Mode. "
f"Defaults to '{DEFAULT_TOOLS_DESCRIPTION}' and tools are added dynamically."
),
advanced=True,
value=DEFAULT_TOOLS_DESCRIPTION,
),
]
outputs = [
@ -104,6 +125,9 @@ class LCAgentComponent(Component):
if isinstance(agent, AgentExecutor):
runnable = agent
else:
if not self.tools:
msg = "Tools are required to run the agent."
raise ValueError(msg)
runnable = AgentExecutor.from_agent_and_tools(
agent=agent,
tools=self.tools,
@ -117,7 +141,7 @@ class LCAgentComponent(Component):
agent_message = Message(
sender=MESSAGE_SENDER_AI,
sender_name="Agent",
sender_name=self.display_name or "Agent",
properties={"icon": "Bot", "state": "partial"},
content_blocks=[ContentBlock(title="Agent Steps", contents=[])],
session_id=self.graph.session_id,
@ -151,7 +175,11 @@ class LCAgentComponent(Component):
class LCToolsAgentComponent(LCAgentComponent):
_base_inputs = [
HandleInput(
name="tools", display_name="Tools", input_types=["Tool", "BaseTool", "StructuredTool"], is_list=True
name="tools",
display_name="Tools",
input_types=["Tool", "BaseTool", "StructuredTool"],
is_list=True,
required=True,
),
*LCAgentComponent._base_inputs,
]
@ -167,3 +195,28 @@ class LCToolsAgentComponent(LCAgentComponent):
@abstractmethod
def create_agent_runnable(self) -> Runnable:
"""Create the agent."""
def get_tool_name(self) -> str:
return self.display_name or "Agent"
def get_tool_description(self) -> str:
return self.agent_description or DEFAULT_TOOLS_DESCRIPTION
def _build_tools_names(self):
tools_names = ""
if self.tools:
tools_names = ", ".join([tool.name for tool in self.tools])
return tools_names
def to_toolkit(self) -> list[Tool]:
component_toolkit = _get_component_toolkit()
tools_names = self._build_tools_names()
agent_description = self.get_tool_description()
# Check if tools_description is the default value
if agent_description == DEFAULT_TOOLS_DESCRIPTION:
description = f"{agent_description}{tools_names}"
else:
description = agent_description
return component_toolkit(component=self).get_tools(
tool_name=self.get_tool_name(), tool_description=description, callbacks=self.get_langchain_callbacks()
)

View file

@ -252,6 +252,6 @@ async def process_agent_events(
agent_message, start_time = chain_handler(event, agent_message, send_message_method, start_time)
start_time = start_time or perf_counter()
agent_message.properties.state = "complete"
return Message(**agent_message.model_dump())
except Exception as e:
raise ExceptionWithMessageError(e, agent_message) from e
return Message(**agent_message.model_dump())

View file

@ -1,24 +1,30 @@
from __future__ import annotations
import asyncio
import re
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Literal
from langchain_core.tools import ToolException
from langchain_core.tools.structured import StructuredTool
from loguru import logger
from pydantic import BaseModel
from langflow.base.tools.constants import TOOL_OUTPUT_NAME
from langflow.io.schema import create_input_schema
from langflow.schema.data import Data
from langflow.schema.message import Message
if TYPE_CHECKING:
from collections.abc import Callable
from langchain_core.callbacks import Callbacks
from langchain_core.tools import BaseTool
from langflow.custom.custom_component.component import Component
from langflow.events.event_manager import EventManager
from langflow.inputs.inputs import InputTypes
from langflow.io import Output
from langflow.schema.content_block import ContentBlock
def _get_input_type(_input: InputTypes):
@ -47,10 +53,57 @@ def build_description(component: Component, output: Output) -> str:
return f"{output.method}({args}) - {component.description}"
def send_message_noop(
message: Message,
text: str | None = None, # noqa: ARG001
background_color: str | None = None, # noqa: ARG001
text_color: str | None = None, # noqa: ARG001
icon: str | None = None, # noqa: ARG001
content_blocks: list[ContentBlock] | None = None, # noqa: ARG001
format_type: Literal["default", "error", "warning", "info"] = "default", # noqa: ARG001
id_: str | None = None, # noqa: ARG001
*,
allow_markdown: bool = True, # noqa: ARG001
) -> Message:
"""No-op implementation of send_message."""
return message
def patch_components_send_message(component: Component):
old_send_message = component.send_message
component.send_message = send_message_noop # type: ignore[method-assign, assignment]
return old_send_message
def _patch_send_message_decorator(component, func):
"""Decorator to patch the send_message method of a component.
This is useful when we want to use a component as a tool, but we don't want to
send any messages to the UI. With this only the Component calling the tool
will send messages to the UI.
"""
async def async_wrapper(*args, **kwargs):
original_send_message = component.send_message
component.send_message = send_message_noop
try:
return await func(*args, **kwargs)
finally:
component.send_message = original_send_message
def sync_wrapper(*args, **kwargs):
original_send_message = component.send_message
component.send_message = send_message_noop
try:
return func(*args, **kwargs)
finally:
component.send_message = original_send_message
return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper
def _build_output_function(component: Component, output_method: Callable, event_manager: EventManager | None = None):
def output_function(*args, **kwargs):
# set the component with the arguments
# set functionality was updatedto handle list of components and other values separately
try:
if event_manager:
event_manager.on_build_start(data={"id": component._id})
@ -60,10 +113,40 @@ def _build_output_function(component: Component, output_method: Callable, event_
event_manager.on_build_end(data={"id": component._id})
except Exception as e:
raise ToolException(e) from e
else:
return result
return output_function
if isinstance(result, Message):
return result.get_text()
if isinstance(result, Data):
return result.data
if isinstance(result, BaseModel):
return result.model_dump()
return result
return _patch_send_message_decorator(component, output_function)
def _build_output_async_function(
component: Component, output_method: Callable, event_manager: EventManager | None = None
):
async def output_function(*args, **kwargs):
try:
if event_manager:
event_manager.on_build_start(data={"id": component._id})
component.set(*args, **kwargs)
result = await output_method()
if event_manager:
event_manager.on_build_end(data={"id": component._id})
except Exception as e:
raise ToolException(e) from e
if isinstance(result, Message):
return result.get_text()
if isinstance(result, Data):
return result.data
if isinstance(result, BaseModel):
return result.model_dump()
return result
return _patch_send_message_decorator(component, output_function)
def _format_tool_name(name: str):
@ -77,7 +160,9 @@ class ComponentToolkit:
def __init__(self, component: Component):
self.component = component
def get_tools(self) -> list[BaseTool]:
def get_tools(
self, tool_name: str | None = None, tool_description: str | None = None, callbacks: Callbacks | None = None
) -> list[BaseTool]:
tools = []
for output in self.component.outputs:
if output.name == TOOL_OUTPUT_NAME:
@ -89,23 +174,67 @@ class ComponentToolkit:
output_method: Callable = getattr(self.component, output.method)
args_schema = None
tool_mode_inputs = [_input for _input in self.component.inputs if getattr(_input, "tool_mode", False)]
if output.required_inputs:
inputs = [self.component._inputs[input_name] for input_name in output.required_inputs]
inputs = [
self.component._inputs[input_name]
for input_name in output.required_inputs
if getattr(self.component, input_name) is None
]
# If any of the required inputs are not in tool mode, this means
# that when the tool is called it will raise an error.
# so we should raise an error here.
if not all(getattr(_input, "tool_mode", False) for _input in inputs):
non_tool_mode_inputs = [
input_.name
for input_ in inputs
if not getattr(input_, "tool_mode", False) and input_.name is not None
]
non_tool_mode_inputs_str = ", ".join(non_tool_mode_inputs)
msg = (
f"Output '{output.name}' requires inputs that are not in tool mode. "
f"The following inputs are not in tool mode: {non_tool_mode_inputs_str}. "
"Please ensure all required inputs are set to tool mode."
)
raise ValueError(msg)
args_schema = create_input_schema(inputs)
elif tool_mode_inputs:
args_schema = create_input_schema(tool_mode_inputs)
else:
args_schema = create_input_schema(self.component.inputs)
name = f"{self.component.name}.{output.method}"
formatted_name = _format_tool_name(name)
tools.append(
StructuredTool(
name=formatted_name,
description=build_description(component=self.component, output=output),
func=_build_output_function(
component=self.component,
output_method=output_method,
event_manager=self.component._event_manager,
),
args_schema=args_schema,
event_manager = self.component._event_manager
if asyncio.iscoroutinefunction(output_method):
tools.append(
StructuredTool(
name=formatted_name,
description=build_description(self.component, output),
coroutine=_build_output_async_function(self.component, output_method, event_manager),
args_schema=args_schema,
handle_tool_error=True,
callbacks=callbacks,
)
)
else:
tools.append(
StructuredTool(
name=formatted_name,
description=build_description(self.component, output),
func=_build_output_function(self.component, output_method, event_manager),
args_schema=args_schema,
handle_tool_error=True,
callbacks=callbacks,
)
)
if len(tools) == 1 and (tool_name or tool_description):
tool = tools[0]
tool.name = tool_name or tool.name
tool.description = tool_description or tool.description
elif tool_name or tool_description:
msg = (
"When passing a tool name or description, there must be only one tool, "
f"but {len(tools)} tools were found."
)
raise ValueError(msg)
return tools

View file

@ -1 +1,2 @@
TOOL_OUTPUT_NAME = "component_as_tool"
TOOL_OUTPUT_DISPLAY_NAME = "Toolset"

View file

@ -42,24 +42,26 @@ class AgentComponent(ToolCallingAgentComponent):
*LCToolsAgentComponent._base_inputs,
*memory_inputs,
]
outputs = [Output(name="response", display_name="Response", method="get_response")]
outputs = [Output(name="response", display_name="Response", method="message_response")]
async def get_response(self) -> Message:
async def message_response(self) -> Message:
llm_model = self.get_llm()
if llm_model is None:
msg = "No language model selected"
raise ValueError(msg)
self.chat_history = self.get_memory_data()
agent = self.set(
if not self.tools:
msg = "Tools are required to run the agent."
raise ValueError(msg)
self.set(
llm=llm_model,
tools=[self.tools],
tools=self.tools,
chat_history=self.chat_history,
input_value=self.input_value,
system_prompt=self.system_prompt,
)
return await agent.message_response()
agent = self.create_agent_runnable()
return await self.run_agent(agent)
def get_memory_data(self):
memory_kwargs = {

View file

@ -23,11 +23,6 @@ class ToolCallingAgentComponent(LCToolsAgentComponent):
info="Initial instructions and context provided to guide the agent's behavior.",
value="You are a helpful assistant that can use tools to answer questions and perform tasks.",
),
MessageTextInput(
name="input_value",
display_name="Input",
info="The input provided by the user for the agent to process.",
),
DataInput(name="chat_history", display_name="Chat Memory", is_list=True, advanced=True),
]

View file

@ -12,7 +12,7 @@ class CustomComponent(Component):
name = "CustomComponent"
inputs = [
MessageTextInput(name="input_value", display_name="Input Value", value="Hello, World!"),
MessageTextInput(name="input_value", display_name="Input Value", value="Hello, World!", tool_mode=True),
]
outputs = [

View file

@ -101,7 +101,7 @@ class ChatOutput(ChatComponent):
message.sender_name = self.sender_name
message.session_id = self.session_id
message.flow_id = self.graph.flow_id
message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)
message.properties.source = self._build_source(_source_id, _display_name, _source)
message.properties.icon = _icon
message.properties.background_color = _background_color
message.properties.text_color = _text_color

View file

@ -85,13 +85,13 @@ class CalculatorToolComponent(LCToolComponent):
except (SyntaxError, TypeError, KeyError) as e:
error_message = f"Invalid expression: {e}"
self.status = error_message
return [Data(data={"error": error_message})]
return [Data(data={"error": error_message, "input": expression})]
except ZeroDivisionError:
error_message = "Error: Division by zero"
self.status = error_message
return [Data(data={"error": error_message})]
return [Data(data={"error": error_message, "input": expression})]
except Exception as e: # noqa: BLE001
logger.opt(exception=True).debug("Error evaluating expression")
error_message = f"Error: {e}"
self.status = error_message
return [Data(data={"error": error_message})]
return [Data(data={"error": error_message, "input": expression})]

View file

@ -73,4 +73,5 @@ ATTR_FUNC_MAPPING: dict[str, Callable] = {
"outputs": getattr_return_list_of_object,
"inputs": getattr_return_list_of_object,
"metadata": getattr_return_dict,
"tool_mode": getattr_return_bool,
}

View file

@ -12,7 +12,7 @@ import nanoid
import yaml
from pydantic import BaseModel, ValidationError
from langflow.base.tools.constants import TOOL_OUTPUT_NAME
from langflow.base.tools.constants import TOOL_OUTPUT_DISPLAY_NAME, TOOL_OUTPUT_NAME
from langflow.custom.tree_visitor import RequiredInputsVisitor
from langflow.exceptions.component import StreamingError
from langflow.field_typing import Tool # noqa: TCH001 Needed by _add_toolkit_output
@ -23,7 +23,6 @@ from langflow.schema.artifact import get_artifact_type, post_process_raw
from langflow.schema.data import Data
from langflow.schema.message import ErrorMessage, Message
from langflow.schema.properties import Source
from langflow.services.settings.feature_flags import FEATURE_FLAGS
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
@ -98,8 +97,6 @@ class Component(CustomComponent):
self.__config = config
self._reset_all_output_values()
super().__init__(**config)
if (FEATURE_FLAGS.add_toolkit_output) and hasattr(self, "_append_tool_output") and self.add_tool_output:
self._append_tool_output()
if hasattr(self, "_trace_type"):
self.trace_type = self._trace_type
if not hasattr(self, "trace_type"):
@ -325,6 +322,10 @@ class Component(CustomComponent):
def run_and_validate_update_outputs(self, frontend_node: dict, field_name: str, field_value: Any):
frontend_node = self.update_outputs(frontend_node, field_name, field_value)
if field_name == "tool_mode":
# Replace all outputs with the tool_output value if tool_mode is True
# else replace it with the original outputs
frontend_node["outputs"] = [self._build_tool_output()] if field_value else frontend_node["outputs"]
return self._validate_frontend_node(frontend_node)
def _validate_frontend_node(self, frontend_node: dict):
@ -590,7 +591,7 @@ class Component(CustomComponent):
f"You should pass one of the following: {methods}"
)
raise ValueError(msg)
if callable(input_value):
if callable(input_value) and hasattr(input_value, "__self__"):
msg = f"Input {name} is connected to {input_value.__self__.display_name}.{input_value.__name__}"
raise ValueError(msg)
self._inputs[name].value = value
@ -766,7 +767,10 @@ class Component(CustomComponent):
async def _build_results(self) -> tuple[dict, dict]:
_results = {}
_artifacts = {}
if hasattr(self, "outputs"):
if any(getattr(_input, "tool_mode", False) for _input in self.inputs):
self._append_tool_to_outputs_map()
for output in self._outputs_map.values():
# Build the output if it's connected to some other vertex
# or if it's not connected to any vertex
@ -872,7 +876,7 @@ class Component(CustomComponent):
def to_toolkit(self) -> list[Tool]:
component_toolkit = _get_component_toolkit()
return component_toolkit(component=self).get_tools()
return component_toolkit(component=self).get_tools(callbacks=self.get_langchain_callbacks())
def get_project_name(self):
if hasattr(self, "_tracing_service") and self._tracing_service:
@ -900,10 +904,17 @@ class Component(CustomComponent):
def _append_tool_output(self) -> None:
if next((output for output in self.outputs if output.name == TOOL_OUTPUT_NAME), None) is None:
self.outputs.append(Output(name=TOOL_OUTPUT_NAME, display_name="Tool", method="to_toolkit", types=["Tool"]))
self.outputs.append(
Output(
name=TOOL_OUTPUT_NAME,
display_name=TOOL_OUTPUT_DISPLAY_NAME,
method="to_toolkit",
types=["Tool"],
)
)
def send_message(self, message: Message, id_: str | None = None):
if self.graph.session_id and message is not None and not message.session_id:
if (hasattr(self, "graph") and self.graph.session_id) and (message is not None and not message.session_id):
message.session_id = self.graph.session_id
stored_message = self._store_message(message)
@ -929,7 +940,8 @@ class Component(CustomComponent):
return stored_message
def _store_message(self, message: Message) -> Message:
messages = store_message(message, flow_id=self.graph.flow_id)
flow_id = self.graph.flow_id if hasattr(self, "graph") else None
messages = store_message(message, flow_id=flow_id)
if len(messages) != 1:
msg = "Only one message can be stored at a time."
raise ValueError(msg)
@ -1022,13 +1034,21 @@ class Component(CustomComponent):
session_id: str,
trace_name: str,
source: Source,
) -> None:
) -> Message:
"""Send an error message to the frontend."""
flow_id = self.graph.flow_id if hasattr(self, "graph") else None
error_message = ErrorMessage(
flow_id=self.graph.flow_id,
flow_id=flow_id,
exception=exception,
session_id=session_id,
trace_name=trace_name,
source=source,
)
self.send_message(error_message)
return error_message
def _append_tool_to_outputs_map(self):
self._outputs_map[TOOL_OUTPUT_NAME] = self._build_tool_output()
def _build_tool_output(self) -> Output:
return Output(name=TOOL_OUTPUT_NAME, display_name=TOOL_OUTPUT_DISPLAY_NAME, method="to_toolkit", types=["Tool"])

View file

@ -363,7 +363,7 @@ class CustomComponent(BaseComponent):
return build_methods[0] if build_methods else {}
@property
def get_function_entrypoint_return_type(self) -> list[Any]:
def _get_function_entrypoint_return_type(self) -> list[Any]:
"""Gets the return type of the function entrypoint for the custom component.
Returns:

View file

@ -337,7 +337,7 @@ class DirectoryReader:
def get_output_types_from_code(code: str) -> list:
"""Get the output types from the code."""
custom_component = Component(_code=code)
types_list = custom_component.get_function_entrypoint_return_type
types_list = custom_component._get_function_entrypoint_return_type
# Get the name of types classes
return [type_.__name__ for type_ in types_list if hasattr(type_, "__name__")]

View file

@ -11,6 +11,11 @@ class RequiredInputsVisitor(ast.NodeVisitor):
@override
def visit_Attribute(self, node) -> None:
if isinstance(node.value, ast.Name) and node.value.id == "self" and node.attr in self.inputs:
if (
isinstance(node.value, ast.Name)
and node.value.id == "self"
and node.attr in self.inputs
and self.inputs[node.attr].required
):
self.required_inputs.add(node.attr)
self.generic_visit(node)

View file

@ -424,8 +424,8 @@ def build_custom_component_template(
frontend_node = add_code_field(frontend_node, custom_component._code)
add_base_classes(frontend_node, custom_component.get_function_entrypoint_return_type)
add_output_types(frontend_node, custom_component.get_function_entrypoint_return_type)
add_base_classes(frontend_node, custom_component._get_function_entrypoint_return_type)
add_output_types(frontend_node, custom_component._get_function_entrypoint_return_type)
reorder_fields(frontend_node, custom_instance._get_field_order())

File diff suppressed because one or more lines are too long

View file

@ -587,7 +587,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"advanced": true,
@ -785,11 +785,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -801,17 +797,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"

View file

@ -748,7 +748,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"advanced": true,
@ -946,11 +946,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -962,17 +958,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -1247,11 +1233,11 @@
},
"description": "This flow can be used to create a blog post following instructions from the user, using two other blogs as reference.",
"endpoint_name": null,
"icon": "FileText",
"id": "5e9b5662-0985-4d40-8ffe-b7f42fa86421",
"is_component": false,
"last_tested_version": "1.0.19.post1",
"name": "Blog Writer",
"icon": "FileText",
"tags": [
"chatbots"
]

View file

@ -886,11 +886,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -902,17 +898,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -1281,7 +1267,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"advanced": true,
@ -2121,11 +2107,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -2137,17 +2119,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -2958,11 +2930,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -2974,17 +2942,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -3409,11 +3367,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -3425,17 +3379,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -3884,11 +3828,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -3900,17 +3840,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -4386,12 +4316,7 @@
"method": "run_model",
"name": "api_run_model",
"required_inputs": [
"api_key",
"engine",
"input_value",
"max_results",
"max_snippet_length",
"search_params"
"api_key"
],
"selected": "Data",
"types": [
@ -4405,12 +4330,7 @@
"method": "build_tool",
"name": "api_build_tool",
"required_inputs": [
"api_key",
"engine",
"input_value",
"max_results",
"max_snippet_length",
"search_params"
"api_key"
],
"selected": "Tool",
"types": [

View file

@ -665,7 +665,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"advanced": true,
@ -863,11 +863,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -879,17 +875,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"

View file

@ -586,11 +586,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -602,17 +598,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -985,7 +971,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"advanced": true,
@ -1841,11 +1827,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -1857,17 +1839,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -2833,12 +2805,7 @@
"method": "run_model",
"name": "api_run_model",
"required_inputs": [
"api_key",
"engine",
"input_value",
"max_results",
"max_snippet_length",
"search_params"
"api_key"
],
"selected": "Data",
"types": [
@ -2852,12 +2819,7 @@
"method": "build_tool",
"name": "api_build_tool",
"required_inputs": [
"api_key",
"engine",
"input_value",
"max_results",
"max_snippet_length",
"search_params"
"api_key"
],
"selected": "Tool",
"types": [

View file

@ -578,11 +578,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -594,17 +590,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -973,7 +959,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"advanced": true,

View file

@ -599,11 +599,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -615,17 +611,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -995,7 +981,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"advanced": true,

View file

@ -762,7 +762,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"_input_type": "MessageTextInput",
@ -966,11 +966,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -982,17 +978,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"
@ -1583,12 +1569,7 @@
"method": "run_model",
"name": "api_run_model",
"required_inputs": [
"api_key",
"engine",
"input_value",
"max_results",
"max_snippet_length",
"search_params"
"api_key"
],
"selected": "Data",
"types": [
@ -1602,12 +1583,7 @@
"method": "build_tool",
"name": "api_build_tool",
"required_inputs": [
"api_key",
"engine",
"input_value",
"max_results",
"max_snippet_length",
"search_params"
"api_key"
],
"selected": "Tool",
"types": [
@ -2460,9 +2436,7 @@
"display_name": "Data",
"method": "run_model",
"name": "api_run_model",
"required_inputs": [
"expression"
],
"required_inputs": [],
"selected": "Data",
"types": [
"Data"
@ -2474,9 +2448,7 @@
"display_name": "Tool",
"method": "build_tool",
"name": "api_build_tool",
"required_inputs": [
"expression"
],
"required_inputs": [],
"selected": "Tool",
"types": [
"Tool"
@ -2503,7 +2475,7 @@
"show": true,
"title_case": false,
"type": "code",
"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})]\n except ZeroDivisionError:\n error_message = \"Error: Division by zero\"\n self.status = error_message\n return [Data(data={\"error\": error_message})]\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})]\n"
"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"
},
"expression": {
"_input_type": "MessageTextInput",

View file

@ -611,26 +611,7 @@
"name": "search_results",
"required_inputs": [
"api_endpoint",
"batch_size",
"bulk_delete_concurrency",
"bulk_insert_batch_concurrency",
"bulk_insert_overwrite_concurrency",
"collection_indexing_policy",
"collection_name",
"embedding",
"embedding_service",
"ingest_data",
"metadata_indexing_exclude",
"metadata_indexing_include",
"metric",
"namespace",
"number_of_results",
"pre_delete_collection",
"search_filter",
"search_input",
"search_score_threshold",
"search_type",
"setup_mode",
"token"
],
"selected": "Data",
@ -1447,7 +1428,7 @@
"show": true,
"title_case": false,
"type": "code",
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = Source(id=_source_id, display_name=_display_name, source=_source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
"value": "from langflow.base.io.chat import ChatComponent\nfrom langflow.inputs import BoolInput\nfrom langflow.io import DropdownInput, MessageInput, MessageTextInput, Output\nfrom langflow.schema.message import Message\nfrom langflow.schema.properties import Source\nfrom langflow.utils.constants import MESSAGE_SENDER_AI, MESSAGE_SENDER_NAME_AI, MESSAGE_SENDER_USER\n\n\nclass ChatOutput(ChatComponent):\n display_name = \"Chat Output\"\n description = \"Display a chat message in the Playground.\"\n icon = \"MessagesSquare\"\n name = \"ChatOutput\"\n\n inputs = [\n MessageInput(\n name=\"input_value\",\n display_name=\"Text\",\n info=\"Message to be passed as output.\",\n ),\n BoolInput(\n name=\"should_store_message\",\n display_name=\"Store Messages\",\n info=\"Store the message in the history.\",\n value=True,\n advanced=True,\n ),\n DropdownInput(\n name=\"sender\",\n display_name=\"Sender Type\",\n options=[MESSAGE_SENDER_AI, MESSAGE_SENDER_USER],\n value=MESSAGE_SENDER_AI,\n advanced=True,\n info=\"Type of sender.\",\n ),\n MessageTextInput(\n name=\"sender_name\",\n display_name=\"Sender Name\",\n info=\"Name of the sender.\",\n value=MESSAGE_SENDER_NAME_AI,\n advanced=True,\n ),\n MessageTextInput(\n name=\"session_id\",\n display_name=\"Session ID\",\n info=\"The session ID of the chat. If empty, the current session ID parameter will be used.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"data_template\",\n display_name=\"Data Template\",\n value=\"{text}\",\n advanced=True,\n info=\"Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.\",\n ),\n MessageTextInput(\n name=\"background_color\",\n display_name=\"Background Color\",\n info=\"The background color of the icon.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"chat_icon\",\n display_name=\"Icon\",\n info=\"The icon of the message.\",\n advanced=True,\n ),\n MessageTextInput(\n name=\"text_color\",\n display_name=\"Text Color\",\n info=\"The text color of the name\",\n advanced=True,\n ),\n ]\n outputs = [\n Output(\n display_name=\"Message\",\n name=\"message\",\n method=\"message_response\",\n ),\n ]\n\n def _build_source(self, _id: str | None, display_name: str | None, source: str | None) -> Source:\n source_dict = {}\n if _id:\n source_dict[\"id\"] = _id\n if display_name:\n source_dict[\"display_name\"] = display_name\n if source:\n source_dict[\"source\"] = source\n return Source(**source_dict)\n\n def message_response(self) -> Message:\n _source, _icon, _display_name, _source_id = self.get_properties_from_source_component()\n _background_color = self.background_color\n _text_color = self.text_color\n if self.chat_icon:\n _icon = self.chat_icon\n message = self.input_value if isinstance(self.input_value, Message) else Message(text=self.input_value)\n message.sender = self.sender\n message.sender_name = self.sender_name\n message.session_id = self.session_id\n message.flow_id = self.graph.flow_id\n message.properties.source = self._build_source(_source_id, _display_name, _source)\n message.properties.icon = _icon\n message.properties.background_color = _background_color\n message.properties.text_color = _text_color\n if self.session_id and isinstance(message, Message) and self.should_store_message:\n stored_message = self.send_message(\n message,\n )\n self.message.value = stored_message\n message = stored_message\n\n self.status = message\n return message\n"
},
"data_template": {
"advanced": true,
@ -1962,26 +1943,7 @@
"name": "search_results",
"required_inputs": [
"api_endpoint",
"batch_size",
"bulk_delete_concurrency",
"bulk_insert_batch_concurrency",
"bulk_insert_overwrite_concurrency",
"collection_indexing_policy",
"collection_name",
"embedding",
"embedding_service",
"ingest_data",
"metadata_indexing_exclude",
"metadata_indexing_include",
"metric",
"namespace",
"number_of_results",
"pre_delete_collection",
"search_filter",
"search_input",
"search_score_threshold",
"search_type",
"setup_mode",
"token"
],
"selected": "Data",
@ -2464,29 +2426,7 @@
"display_name": "Embeddings",
"method": "build_embeddings",
"name": "embeddings",
"required_inputs": [
"chunk_size",
"client",
"default_headers",
"default_query",
"deployment",
"dimensions",
"embedding_ctx_length",
"max_retries",
"model",
"model_kwargs",
"openai_api_base",
"openai_api_key",
"openai_api_type",
"openai_api_version",
"openai_organization",
"openai_proxy",
"request_timeout",
"show_progress_bar",
"skip_empty",
"tiktoken_enable",
"tiktoken_model_name"
],
"required_inputs": [],
"selected": "Embeddings",
"types": [
"Embeddings"
@ -2942,29 +2882,7 @@
"display_name": "Embeddings",
"method": "build_embeddings",
"name": "embeddings",
"required_inputs": [
"chunk_size",
"client",
"default_headers",
"default_query",
"deployment",
"dimensions",
"embedding_ctx_length",
"max_retries",
"model",
"model_kwargs",
"openai_api_base",
"openai_api_key",
"openai_api_type",
"openai_api_version",
"openai_organization",
"openai_proxy",
"request_timeout",
"show_progress_bar",
"skip_empty",
"tiktoken_enable",
"tiktoken_model_name"
],
"required_inputs": [],
"selected": "Embeddings",
"types": [
"Embeddings"
@ -3412,11 +3330,7 @@
"display_name": "Text",
"method": "text_response",
"name": "text_output",
"required_inputs": [
"input_value",
"stream",
"system_message"
],
"required_inputs": [],
"selected": "Message",
"types": [
"Message"
@ -3428,17 +3342,7 @@
"display_name": "Language Model",
"method": "build_model",
"name": "model_output",
"required_inputs": [
"api_key",
"json_mode",
"max_tokens",
"model_kwargs",
"model_name",
"openai_api_base",
"output_schema",
"seed",
"temperature"
],
"required_inputs": [],
"selected": "LanguageModel",
"types": [
"LanguageModel"

View file

@ -106,6 +106,10 @@ class BaseInputMixin(BaseModel, validate_assignment=True): # type: ignore[call-
return dump
class ToolModeMixin(BaseModel):
tool_mode: bool = False
class InputTraceMixin(BaseModel):
trace_as_input: bool = True

View file

@ -25,6 +25,7 @@ from .input_mixin import (
SerializableFieldTypes,
SliderMixin,
TableMixin,
ToolModeMixin,
)
@ -154,7 +155,7 @@ class MessageInput(StrInput, InputTraceMixin):
raise ValueError(msg)
class MessageTextInput(StrInput, MetadataTraceMixin, InputTraceMixin):
class MessageTextInput(StrInput, MetadataTraceMixin, InputTraceMixin, ToolModeMixin):
"""Represents a text input component for the Langflow system.
This component is used to handle text inputs in the Langflow system.

View file

@ -1,4 +1,4 @@
from collections.abc import Callable, Generator
from collections.abc import Generator
from enum import Enum
from fastapi.encoders import jsonable_encoder
@ -6,6 +6,7 @@ from loguru import logger
from pydantic import BaseModel
from langflow.schema.data import Data
from langflow.schema.encoders import CUSTOM_ENCODERS
from langflow.schema.message import Message
from langflow.schema.serialize import recursive_serialize_or_str
@ -51,13 +52,6 @@ def get_artifact_type(value, build_result=None) -> str:
return result.value
def encode_callable(obj: Callable):
return obj.__name__ if hasattr(obj, "__name__") else str(obj)
CUSTOM_ENCODERS = {Callable: encode_callable}
def post_process_raw(raw, artifact_type: str):
if artifact_type == ArtifactType.STREAM.value:
raw = ""

View file

@ -1,8 +1,11 @@
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, ConfigDict, Field, model_serializer
from typing_extensions import TypedDict
from langflow.schema.encoders import CUSTOM_ENCODERS
class HeaderDict(TypedDict, total=False):
title: str | None
@ -23,6 +26,14 @@ class BaseContent(BaseModel):
def from_dict(cls, data: dict[str, Any]) -> "BaseContent":
return cls(**data)
@model_serializer(mode="wrap")
def serialize_model(self, nxt) -> dict[str, Any]:
try:
dump = nxt(self)
return jsonable_encoder(dump, custom_encoder=CUSTOM_ENCODERS)
except Exception: # noqa: BLE001
return nxt(self)
class ErrorContent(BaseContent):
"""Content type for error messages."""

View file

@ -0,0 +1,13 @@
from collections.abc import Callable
from datetime import datetime
def encode_callable(obj: Callable):
return obj.__name__ if hasattr(obj, "__name__") else str(obj)
def encode_datetime(obj: datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S %Z")
CUSTOM_ENCODERS = {Callable: encode_callable, datetime: encode_datetime}

View file

@ -350,17 +350,18 @@ class ErrorMessage(Message):
flow_id: str | None = None,
) -> None:
# Get the error reason
reason = ""
reason = f"**{exception.__class__.__name__}**\n"
if hasattr(exception, "body") and "message" in exception.body:
reason += f"{exception.body.get('message')}\n"
reason += f" - **{exception.body.get('message')}**\n"
elif hasattr(exception, "code"):
reason += f" - **Code: {exception.code}**\n"
elif hasattr(exception, "args") and exception.args:
reason += f"**{exception.args[0]}**\n"
reason += f" - **Details: {exception.args[0]}**\n"
elif isinstance(exception, ValidationError):
reason += f"```python\n{exception!s}\n```\n"
reason += f" - **Details:**\n\n```python\n{exception!s}\n```\n"
else:
reason += f"**{exception.__class__.__name__}**\n"
reason += " - **An unknown error occurred.**\n"
# Get the sender ID
if trace_name:
match = re.search(r"\((.*?)\)", trace_name)

View file

@ -24,7 +24,7 @@ class PlaygroundEvent(BaseModel):
timestamp: Annotated[str, timestamp_to_str_validator] = Field(
default_factory=lambda: datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S %Z")
)
id_: UUID | str | None = Field(alias="id")
id_: UUID | str | None = Field(default=None, alias="id")
@field_serializer("timestamp")
@classmethod

View file

@ -2,7 +2,6 @@ from pydantic_settings import BaseSettings
class FeatureFlags(BaseSettings):
add_toolkit_output: bool = False
mvp_components: bool = False
class Config:

View file

@ -57,6 +57,8 @@ class FrontendNode(BaseModel):
"""Whether the frontend node has been edited."""
metadata: dict = {}
"""Metadata for the component node."""
tool_mode: bool = False
"""Whether the frontend node is in tool mode."""
def set_documentation(self, documentation: str) -> None:
"""Sets the documentation of the frontend node."""