feat: Add ruff rules for pycodestyle Errors (E) (#3947)

Add ruff rules for pycodestyle Errors (E)
This commit is contained in:
Christophe Bornet 2024-10-01 13:41:30 +02:00 committed by GitHub
commit db9787c086
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
69 changed files with 282 additions and 126 deletions

View file

@ -72,7 +72,7 @@ def set_var_for_macos_issue():
import os
os.environ["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES"
# https://stackoverflow.com/questions/75747888/uwsgi-segmentation-fault-with-flask-python-app-behind-nginx-after-running-for-2 # noqa
# https://stackoverflow.com/questions/75747888/uwsgi-segmentation-fault-with-flask-python-app-behind-nginx-after-running-for-2 # noqa: E501
os.environ["no_proxy"] = "*" # to avoid error with gunicorn
logger.debug("Set OBJC_DISABLE_INITIALIZE_FORK_SAFETY to YES to avoid error")
@ -336,8 +336,14 @@ def print_banner(host: str, port: int):
styled_package_name = stylize_text(package_name, package_name, any("pre-release" in notice for notice in notices))
title = f"[bold]Welcome to :chains: {styled_package_name}[/bold]\n"
info_text = "Collaborate, and contribute at our [bold][link=https://github.com/langflow-ai/langflow]GitHub Repo[/link][/bold] :star2:"
telemetry_text = "We collect anonymous usage data to improve Langflow.\nYou can opt-out by setting [bold]DO_NOT_TRACK=true[/bold] in your environment."
info_text = (
"Collaborate, and contribute at our "
"[bold][link=https://github.com/langflow-ai/langflow]GitHub Repo[/link][/bold] :star2:"
)
telemetry_text = (
"We collect anonymous usage data to improve Langflow.\n"
"You can opt-out by setting [bold]DO_NOT_TRACK=true[/bold] in your environment."
)
access_link = f"Access [link=http://{host}:{port}]http://{host}:{port}[/link]"
panel_content = "\n\n".join([title, *styled_notices, info_text, telemetry_text, access_link])
@ -411,7 +417,8 @@ def copy_db():
"""
Copy the database files to the current directory.
This function copies the 'langflow.db' and 'langflow-pre.db' files from the cache directory to the current directory.
This function copies the 'langflow.db' and 'langflow-pre.db' files from the cache directory to the current
directory.
If the files exist in the cache directory, they will be copied to the same directory as this script (__main__.py).
Returns:

View file

@ -16,7 +16,8 @@ class HealthResponse(BaseModel):
chat: str = "error check the server logs"
db: str = "error check the server logs"
"""
Do not send exceptions and detailed error messages to the client because it might contain credentials and other sensitive server information.
Do not send exceptions and detailed error messages to the client because it might contain credentials and other
sensitive server information.
"""
def has_error(self) -> bool:

View file

@ -230,10 +230,16 @@ def get_suggestion_message(outdated_components: list[str]) -> str:
if count == 0:
return "The flow contains no outdated components."
elif count == 1:
return f"The flow contains 1 outdated component. We recommend updating the following component: {outdated_components[0]}."
return (
"The flow contains 1 outdated component. "
f"We recommend updating the following component: {outdated_components[0]}."
)
else:
components = ", ".join(outdated_components)
return f"The flow contains {count} outdated components. We recommend updating the following components: {components}."
return (
f"The flow contains {count} outdated components. "
f"We recommend updating the following components: {components}."
)
def parse_value(value: Any, input_type: str) -> Any:

View file

@ -411,7 +411,9 @@ async def build_flow(
get_time_yield = time.time()
client_consumed_queue.put_nowait(event_id)
logger.debug(
f"consumed event {str(event_id)} (time in queue, {get_time - put_time:.4f}, client {get_time_yield - get_time:.4f})"
f"consumed event {str(event_id)} "
f"(time in queue, {get_time - put_time:.4f}, "
f"client {get_time_yield - get_time:.4f})"
)
asyncio_queue: asyncio.Queue = asyncio.Queue()

View file

@ -186,31 +186,44 @@ async def simplified_run_flow(
telemetry_service: TelemetryService = Depends(get_telemetry_service),
):
"""
Executes a specified flow by ID with input customization, performance enhancements through caching, and optional data streaming.
Executes a specified flow by ID with input customization, performance enhancements through caching, and optional
data streaming.
### Parameters:
- `db` (Session): Database session for executing queries.
- `flow_id_or_name` (str): ID or endpoint name of the flow to run.
- `input_request` (SimplifiedAPIRequest): Request object containing input values, types, output selection, tweaks, and session ID.
- `input_request` (SimplifiedAPIRequest): Request object containing input values, types, output selection, tweaks,
and session ID.
- `api_key_user` (User): User object derived from the provided API key, used for authentication.
- `session_service` (SessionService): Service for managing flow sessions, essential for session reuse and caching.
### SimplifiedAPIRequest:
- `input_value` (Optional[str], default=""): Input value to pass to the flow.
- `input_type` (Optional[Literal["chat", "text", "any"]], default="chat"): Type of the input value, determining how the input is interpreted.
- `output_type` (Optional[Literal["chat", "text", "any", "debug"]], default="chat"): Desired type of output, affecting which components' outputs are included in the response. If set to "debug", all outputs are returned.
- `output_component` (Optional[str], default=None): Specific component output to retrieve. If provided, only the output of the specified component is returned. This overrides the `output_type` parameter.
- `tweaks` (Optional[Tweaks], default=None): Adjustments to the flow's behavior, allowing for custom execution parameters.
- `session_id` (Optional[str], default=None): An identifier for reusing session data, aiding in performance for subsequent requests.
- `input_type` (Optional[Literal["chat", "text", "any"]], default="chat"): Type of the input value,
determining how the input is interpreted.
- `output_type` (Optional[Literal["chat", "text", "any", "debug"]], default="chat"): Desired type of output,
affecting which components' outputs are included in the response. If set to "debug", all outputs are returned.
- `output_component` (Optional[str], default=None): Specific component output to retrieve. If provided,
only the output of the specified component is returned. This overrides the `output_type` parameter.
- `tweaks` (Optional[Tweaks], default=None): Adjustments to the flow's behavior, allowing for custom execution
parameters.
- `session_id` (Optional[str], default=None): An identifier for reusing session data, aiding in performance for
subsequent requests.
### Tweaks
A dictionary of tweaks to customize the flow execution. The tweaks can be used to modify the flow's parameters and components. Tweaks can be overridden by the input values.
You can use Component's `id` or Display Name as key to tweak a specific component (e.g., `{"Component Name": {"parameter_name": "value"}}`).
You can also use the parameter name as key to tweak all components with that parameter (e.g., `{"parameter_name": "value"}`).
A dictionary of tweaks to customize the flow execution.
The tweaks can be used to modify the flow's parameters and components.
Tweaks can be overridden by the input values.
You can use Component's `id` or Display Name as key to tweak a specific component
(e.g., `{"Component Name": {"parameter_name": "value"}}`).
You can also use the parameter name as key to tweak all components with that parameter
(e.g., `{"parameter_name": "value"}`).
### Returns:
- A `RunResponse` object containing the execution results, including selected (or all, based on `output_type`) outputs of the flow and the session ID, facilitating result retrieval and further interactions in a session context.
- A `RunResponse` object containing the execution results, including selected (or all, based on `output_type`)
outputs of the flow and the session ID, facilitating result retrieval and further interactions in a session
context.
### Raises:
- HTTPException: 404 if the specified flow ID curl -X 'POST' \
@ -231,7 +244,9 @@ async def simplified_run_flow(
}'
```
This endpoint provides a powerful interface for executing flows with enhanced flexibility and efficiency, supporting a wide range of applications by allowing for dynamic input and output configuration along with performance optimizations through session management and caching.
This endpoint provides a powerful interface for executing flows with enhanced flexibility and efficiency,
supporting a wide range of applications by allowing for dynamic input and output configuration along with
performance optimizations through session management and caching.
"""
if flow is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Flow not found")
@ -382,19 +397,27 @@ async def experimental_run_flow(
### Parameters:
- `flow_id` (str): The unique identifier of the flow to be executed.
- `inputs` (List[InputValueRequest], optional): A list of inputs specifying the input values and components for the flow. Each input can target specific components and provide custom values.
- `outputs` (List[str], optional): A list of output names to retrieve from the executed flow. If not provided, all outputs are returned.
- `tweaks` (Optional[Tweaks], optional): A dictionary of tweaks to customize the flow execution. The tweaks can be used to modify the flow's parameters and components. Tweaks can be overridden by the input values.
- `inputs` (List[InputValueRequest], optional): A list of inputs specifying the input values and components
for the flow. Each input can target specific components and provide custom values.
- `outputs` (List[str], optional): A list of output names to retrieve from the executed flow.
If not provided, all outputs are returned.
- `tweaks` (Optional[Tweaks], optional): A dictionary of tweaks to customize the flow execution.
The tweaks can be used to modify the flow's parameters and components.
Tweaks can be overridden by the input values.
- `stream` (bool, optional): Specifies whether the results should be streamed. Defaults to False.
- `session_id` (Union[None, str], optional): An optional session ID to utilize existing session data for the flow execution.
- `session_id` (Union[None, str], optional): An optional session ID to utilize existing session data for the flow
execution.
- `api_key_user` (User): The user associated with the current API key. Automatically resolved from the API key.
- `session_service` (SessionService): The session service object for managing flow sessions.
### Returns:
A `RunResponse` object containing the selected outputs (or all if not specified) of the executed flow and the session ID. The structure of the response accommodates multiple inputs, providing a nested list of outputs for each input.
A `RunResponse` object containing the selected outputs (or all if not specified) of the executed flow
and the session ID.
The structure of the response accommodates multiple inputs, providing a nested list of outputs for each input.
### Raises:
HTTPException: Indicates issues with finding the specified flow, invalid input formats, or internal errors during flow execution.
HTTPException: Indicates issues with finding the specified flow, invalid input formats, or internal errors during
flow execution.
### Example usage:
```json
@ -412,8 +435,9 @@ async def experimental_run_flow(
}
```
This endpoint facilitates complex flow executions with customized inputs, outputs, and configurations, catering to diverse application requirements.
"""
This endpoint facilitates complex flow executions with customized inputs, outputs, and configurations,
catering to diverse application requirements.
""" # noqa: E501
try:
flow_id_str = str(flow_id)
if outputs is None:
@ -582,7 +606,8 @@ async def custom_component_update(
Update a custom component with the provided code request.
This endpoint generates the CustomComponentFrontendNode normally but then runs the `update_build_config` method
on the latest version of the template. This ensures that every time it runs, it has the latest version of the template.
on the latest version of the template.
This ensures that every time it runs, it has the latest version of the template.
Args:
code_request (CustomComponentRequest): The code request containing the updated code for the custom component.

View file

@ -298,7 +298,8 @@ class InputValueRequest(BaseModel):
input_value: str | None = None
type: InputType | None = Field(
"any",
description="Defines on which components the input value should be applied. 'any' applies to all input components.",
description="Defines on which components the input value should be applied. "
"'any' applies to all input components.",
)
# add an example

View file

@ -20,4 +20,4 @@ XML_AGENT_PROMPT = """You are a helpful assistant. Help the user answer any ques
{chat_history}
Question: {input}
{agent_scratchpad}"""
{agent_scratchpad}""" # noqa: E501

View file

@ -1,11 +1,14 @@
"""
This file contains a fix for the implementation of the `uncurl` library, which is available at https://github.com/spulec/uncurl.git.
The `uncurl` library provides a way to parse and convert cURL commands into Python requests. However, there are some issues with the original implementation that this file aims to fix.
The `uncurl` library provides a way to parse and convert cURL commands into Python requests.
However, there are some issues with the original implementation that this file aims to fix.
The `parse_context` function in this file takes a cURL command as input and returns a `ParsedContext` object, which contains the parsed information from the cURL command, such as the HTTP method, URL, headers, cookies, etc.
The `parse_context` function in this file takes a cURL command as input and returns a `ParsedContext` object,
which contains the parsed information from the cURL command, such as the HTTP method, URL, headers, cookies, etc.
The `normalize_newlines` function is a helper function that replaces the line continuation character ("\") followed by a newline with a space.
The `normalize_newlines` function is a helper function that replaces the line continuation character ("\")
followed by a newline with a space.
"""

View file

@ -15,7 +15,8 @@ class TextComponent(Component):
"data_template": {
"display_name": "Data Template",
"multiline": True,
"info": "Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.",
"info": "Template to convert Data to Text. "
"If left empty, it will be dynamically set to the Data's text key.",
"advanced": True,
},
}

View file

@ -34,7 +34,8 @@ class BaseMemoryComponent(CustomComponent):
"data_template": {
"display_name": "Data Template",
"multiline": True,
"info": "Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.",
"info": "Template to convert Data to Text. "
"If left empty, it will be dynamically set to the Data's text key.",
"advanced": True,
},
}

View file

@ -9,7 +9,8 @@ def build_status_from_tool(tool: Tool):
tool (Tool): The tool object to build the status for.
Returns:
str: The status string representation of the tool, including its name, description, arguments (if any), and args_schema (if any).
str: The status string representation of the tool, including its name, description, arguments (if any),
and args_schema (if any).
"""
description_repr = repr(tool.description).strip("'")
args_str = "\n".join(

View file

@ -48,7 +48,8 @@ class LCVectorStoreComponent(Component):
method = cls.build_vector_store
if not hasattr(method, "_is_cached_vector_store_checked"):
raise TypeError(
f"The method 'build_vector_store' in class {cls.__name__} must be decorated with @check_cached_vector_store"
f"The method 'build_vector_store' in class {cls.__name__} "
"must be decorated with @check_cached_vector_store"
)
trace_type = "retriever"

View file

@ -55,7 +55,8 @@ class NotionPageCreator(LCToolComponent):
def build_tool(self) -> Tool:
return StructuredTool.from_function(
name="create_notion_page",
description="Create a new page in a Notion database. IMPORTANT: Use the tool to check the Database properties for more details before using this tool.",
description="Create a new page in a Notion database. "
"IMPORTANT: Use the tool to check the Database properties for more details before using this tool.",
func=self._create_notion_page,
args_schema=self.NotionPageCreatorSchema,
)

View file

@ -17,7 +17,8 @@ class NotionListPages(LCToolComponent):
"Query a Notion database with filtering and sorting. "
"The input should be a JSON string containing the 'filter' and 'sorts' objects. "
"Example input:\n"
'{"filter": {"property": "Status", "select": {"equals": "Done"}}, "sorts": [{"timestamp": "created_time", "direction": "descending"}]}'
'{"filter": {"property": "Status", "select": {"equals": "Done"}}, '
'"sorts": [{"timestamp": "created_time", "direction": "descending"}]}'
)
documentation: str = "https://docs.langflow.org/integrations/notion/list-pages"
icon = "NotionDirectoryLoader"
@ -37,7 +38,8 @@ class NotionListPages(LCToolComponent):
MultilineInput(
name="query_json",
display_name="Database query (JSON)",
info="A JSON string containing the filters and sorts that will be used for querying the database. Leave empty for no filters or sorts.",
info="A JSON string containing the filters and sorts that will be used for querying the database. "
"Leave empty for no filters or sorts.",
),
]
@ -45,7 +47,8 @@ class NotionListPages(LCToolComponent):
database_id: str = Field(..., description="The ID of the Notion database to query.")
query_json: str | None = Field(
default="",
description="A JSON string containing the filters and sorts for querying the database. Leave empty for no filters or sorts.",
description="A JSON string containing the filters and sorts for querying the database. "
"Leave empty for no filters or sorts.",
)
def run_model(self) -> list[Data]:

View file

@ -82,7 +82,8 @@ class NotionSearch(LCToolComponent):
def build_tool(self) -> Tool:
return StructuredTool.from_function(
name="notion_search",
description="Search Notion pages and databases. Input should include the search query and optionally filter type and sort direction.",
description="Search Notion pages and databases. "
"Input should include the search query and optionally filter type and sort direction.",
func=self._search_notion,
args_schema=self.NotionSearchSchema,
)

View file

@ -58,7 +58,8 @@ class NotionPageUpdate(LCToolComponent):
def build_tool(self) -> Tool:
return StructuredTool.from_function(
name="update_notion_page",
description="Update the properties of a Notion page. IMPORTANT: Use the tool to check the Database properties for more details before using this tool.",
description="Update the properties of a Notion page. "
"IMPORTANT: Use the tool to check the Database properties for more details before using this tool.",
func=self._update_notion_page,
args_schema=self.NotionPageUpdateSchema,
)

View file

@ -43,7 +43,7 @@ Begin!
Question: {input}
{agent_scratchpad}
""",
""", # noqa: E501
),
MultilineInput(
name="user_prompt", display_name="Prompt", info="This prompt must contain 'input' key.", value="{input}"

View file

@ -30,7 +30,8 @@ class AssistantsCreateAssistant(Component):
info=(
"Model for the assistant.\n\n"
"Environment variables for provider credentials can be set with the Dotenv Component.\n\n"
"Models are supported via LiteLLM, see (https://docs.litellm.ai/docs/providers) for supported model names and env vars."
"Models are supported via LiteLLM, "
"see (https://docs.litellm.ai/docs/providers) for supported model names and env vars."
),
# refresh_model=True
),

View file

@ -16,7 +16,8 @@ class Dotenv(Component):
MultilineSecretInput(
name="dotenv_file_content",
display_name="Dotenv file content",
info="Paste the content of your .env file directly, since contents are sensitive, using a Global variable set as 'password' is recommended",
info="Paste the content of your .env file directly, since contents are sensitive, "
"using a Global variable set as 'password' is recommended",
)
]

View file

@ -34,7 +34,8 @@ class APIRequestComponent(Component):
MessageTextInput(
name="curl",
display_name="Curl",
info="Paste a curl command to populate the fields. This will fill in the dictionary fields for headers and body.",
info="Paste a curl command to populate the fields. "
"This will fill in the dictionary fields for headers and body.",
advanced=False,
refresh_button=True,
),
@ -54,7 +55,8 @@ class APIRequestComponent(Component):
NestedDictInput(
name="body",
display_name="Body",
info="The body to send with the request as a dictionary (for POST, PATCH, PUT). This is populated when using the CURL field.",
info="The body to send with the request as a dictionary (for POST, PATCH, PUT). "
"This is populated when using the CURL field.",
input_types=["Data"],
),
DataInput(

View file

@ -11,7 +11,13 @@ class ShouldRunNextComponent(CustomComponent):
name = "ShouldRunNext"
def build(self, llm: LanguageModel, question: str, context: str, retries: int = 3) -> Text:
template = "Given the following question and the context below, answer with a yes or no.\n\n{error_message}\n\nQuestion: {question}\n\nContext: {context}\n\nAnswer:"
template = (
"Given the following question and the context below, answer with a yes or no.\n\n"
"{error_message}\n\n"
"Question: {question}\n\n"
"Context: {context}\n\n"
"Answer:"
)
prompt = PromptTemplate.from_template(template)
chain = prompt | llm

View file

@ -7,7 +7,10 @@ from langflow.schema import Data
class AssemblyAITranscriptionParser(Component):
display_name = "AssemblyAI Parse Transcript"
description = "Parse AssemblyAI transcription result. If Speaker Labels was enabled, format utterances with speakers and timestamps"
description = (
"Parse AssemblyAI transcription result. "
"If Speaker Labels was enabled, format utterances with speakers and timestamps"
)
documentation = "https://www.assemblyai.com/docs"
icon = "AssemblyAI"

View file

@ -90,10 +90,9 @@ class AssemblyAITranscriptionJobCreator(Component):
MessageTextInput(
name="language_code",
display_name="Language",
info="""
The language of the audio file. Can be set manually if automatic language detection is disabled.
See https://www.assemblyai.com/docs/getting-started/supported-languages for a list of supported language codes.
""",
info="The language of the audio file. Can be set manually if automatic language detection is disabled.\n"
"See https://www.assemblyai.com/docs/getting-started/supported-languages "
"for a list of supported language codes.",
),
BoolInput(
name="speaker_labels",

View file

@ -7,7 +7,10 @@ from langflow.template.field.base import Output
class AstraVectorizeComponent(Component):
display_name: str = "Astra Vectorize [DEPRECATED]"
description: str = "Configuration options for Astra Vectorize server-side embeddings. This component is deprecated. Please use the Astra DB Component directly."
description: str = (
"Configuration options for Astra Vectorize server-side embeddings. "
"This component is deprecated. Please use the Astra DB Component directly."
)
documentation: str = "https://docs.datastax.com/en/astra-db-serverless/databases/embedding-generation.html"
icon = "AstraDB"
name = "AstraVectorize"
@ -60,14 +63,15 @@ class AstraVectorizeComponent(Component):
MessageTextInput(
name="model_name",
display_name="Model Name",
info=f"The embedding model to use for the selected provider. Each provider has a different set of models "
info="The embedding model to use for the selected provider. Each provider has a different set of models "
f"available (full list at https://docs.datastax.com/en/astra-db-serverless/databases/embedding-generation.html):\n\n{VECTORIZE_MODELS_STR}",
required=True,
),
MessageTextInput(
name="api_key_name",
display_name="API Key name",
info="The name of the embeddings provider API key stored on Astra. If set, it will override the 'ProviderKey' in the authentication parameters.",
info="The name of the embeddings provider API key stored on Astra. "
"If set, it will override the 'ProviderKey' in the authentication parameters.",
),
DictInput(
name="authentication",
@ -78,7 +82,10 @@ class AstraVectorizeComponent(Component):
SecretStrInput(
name="provider_api_key",
display_name="Provider API Key",
info="An alternative to the Astra Authentication that passes an API key for the provider with each request to Astra DB. This may be used when Vectorize is configured for the collection, but no corresponding provider secret is stored within Astra's key management system.",
info="An alternative to the Astra Authentication that passes an API key for the provider with each request "
"to Astra DB. "
"This may be used when Vectorize is configured for the collection, "
"but no corresponding provider secret is stored within Astra's key management system.",
advanced=True,
),
DictInput(

View file

@ -56,7 +56,8 @@ class AzureOpenAIEmbeddingsComponent(LCModelComponent):
IntInput(
name="dimensions",
display_name="Dimensions",
info="The number of dimensions the resulting output embeddings should have. Only supported by certain models.",
info="The number of dimensions the resulting output embeddings should have. "
"Only supported by certain models.",
advanced=True,
),
]

View file

@ -13,7 +13,10 @@ from langflow.io import MessageTextInput, Output, SecretStrInput
class GoogleGenerativeAIEmbeddingsComponent(Component):
display_name = "Google Generative AI Embeddings"
description = "Connect to Google's generative AI embeddings service using the GoogleGenerativeAIEmbeddings class, found in the langchain-google-genai package."
description = (
"Connect to Google's generative AI embeddings service using the GoogleGenerativeAIEmbeddings class, "
"found in the langchain-google-genai package."
)
documentation: str = "https://python.langchain.com/v0.2/docs/integrations/text_embedding/google_generative_ai/"
icon = "Google"
name = "Google Generative AI Embeddings"

View file

@ -47,14 +47,17 @@ class HuggingFaceInferenceAPIEmbeddingsComponent(LCEmbeddingsModel):
parsed_url = urlparse(inference_endpoint)
if not all([parsed_url.scheme, parsed_url.netloc]):
raise ValueError(
f"Invalid inference endpoint format: '{self.inference_endpoint}'. Please ensure the URL includes both a scheme (e.g., 'http://' or 'https://') and a domain name. Example: 'http://localhost:8080' or 'https://api.example.com'"
f"Invalid inference endpoint format: '{self.inference_endpoint}'. "
"Please ensure the URL includes both a scheme (e.g., 'http://' or 'https://') and a domain name. "
"Example: 'http://localhost:8080' or 'https://api.example.com'"
)
try:
response = requests.get(f"{inference_endpoint}/health", timeout=5)
except requests.RequestException:
raise ValueError(
f"Inference endpoint '{inference_endpoint}' is not responding. Please ensure the URL is correct and the service is running."
f"Inference endpoint '{inference_endpoint}' is not responding. "
"Please ensure the URL is correct and the service is running."
)
if response.status_code != 200:

View file

@ -66,7 +66,8 @@ class OpenAIEmbeddingsComponent(LCEmbeddingsModel):
IntInput(
name="dimensions",
display_name="Dimensions",
info="The number of dimensions the resulting output embeddings should have. Only supported by certain models.",
info="The number of dimensions the resulting output embeddings should have. "
"Only supported by certain models.",
advanced=True,
),
]

View file

@ -62,7 +62,8 @@ class MemoryComponent(Component):
MultilineInput(
name="template",
display_name="Template",
info="The template to use for formatting the data. It can contain the keys {text}, {sender} or any other key in the message data.",
info="The template to use for formatting the data. "
"It can contain the keys {text}, {sender} or any other key in the message data.",
value="{sender_name}: {text}",
advanced=True,
),

View file

@ -15,7 +15,8 @@ class ParseDataComponent(Component):
MultilineInput(
name="template",
display_name="Template",
info="The template to use for formatting the data. It can contain the keys {text}, {data} or any other key in the Data.",
info="The template to use for formatting the data. "
"It can contain the keys {text}, {data} or any other key in the Data.",
value="{text}",
),
StrInput(name="sep", display_name="Separator", advanced=True, value="\n"),

View file

@ -23,7 +23,8 @@ class StoreMessageComponent(Component):
MessageInput(
name="sender",
display_name="Sender",
info="The sender of the message. Might be Machine or User. If empty, the current sender parameter will be used.",
info="The sender of the message. Might be Machine or User. "
"If empty, the current sender parameter will be used.",
advanced=True,
),
MessageInput(

View file

@ -43,7 +43,8 @@ class AIMLModelComponent(LCModelComponent):
name="aiml_api_base",
display_name="AIML API Base",
advanced=True,
info="The base URL of the OpenAI API. Defaults to https://api.aimlapi.com . You can change this to use other APIs like JinaChat, LocalAI e Prem.",
info="The base URL of the OpenAI API. Defaults to https://api.aimlapi.com . "
"You can change this to use other APIs like JinaChat, LocalAI and Prem.",
),
SecretStrInput(
name="api_key",

View file

@ -40,7 +40,8 @@ class GoogleGenerativeAIComponent(LCModelComponent):
IntInput(
name="n",
display_name="N",
info="Number of chat completions to generate for each prompt. Note that the API may not return the full n completions if duplicates are generated.",
info="Number of chat completions to generate for each prompt. "
"Note that the API may not return the full n completions if duplicates are generated.",
advanced=True,
),
IntInput(

View file

@ -42,7 +42,8 @@ class GroqModel(LCModelComponent):
IntInput(
name="n",
display_name="N",
info="Number of chat completions to generate for each prompt. Note that the API may not return the full n completions if duplicates are generated.",
info="Number of chat completions to generate for each prompt. "
"Note that the API may not return the full n completions if duplicates are generated.",
advanced=True,
),
DropdownInput(

View file

@ -3,7 +3,8 @@ from typing import Any
from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint
from tenacity import retry, stop_after_attempt, wait_fixed
# TODO: langchain_community.llms.huggingface_endpoint is depreciated. Need to update to langchain_huggingface, but have dependency with langchain_core 0.3.0
# TODO: langchain_community.llms.huggingface_endpoint is depreciated.
# Need to update to langchain_huggingface, but have dependency with langchain_core 0.3.0
from langflow.base.models.model import LCModelComponent
from langflow.field_typing import LanguageModel
from langflow.inputs.inputs import HandleInput

View file

@ -46,7 +46,9 @@ class OpenAIModelComponent(LCModelComponent):
is_list=True,
display_name="Schema",
advanced=True,
info="The schema for the Output of the model. You must pass the word JSON in the prompt. If left blank, JSON mode will be disabled.",
info="The schema for the Output of the model. "
"You must pass the word JSON in the prompt. "
"If left blank, JSON mode will be disabled.",
),
DropdownInput(
name="model_name",
@ -59,7 +61,9 @@ class OpenAIModelComponent(LCModelComponent):
name="openai_api_base",
display_name="OpenAI API Base",
advanced=True,
info="The base URL of the OpenAI API. Defaults to https://api.openai.com/v1. You can change this to use other APIs like JinaChat, LocalAI and Prem.",
info="The base URL of the OpenAI API. "
"Defaults to https://api.openai.com/v1. "
"You can change this to use other APIs like JinaChat, LocalAI and Prem.",
),
SecretStrInput(
name="api_key",

View file

@ -51,7 +51,8 @@ class PerplexityComponent(LCModelComponent):
IntInput(
name="n",
display_name="N",
info="Number of chat completions to generate for each prompt. Note that the API may not return the full n completions if duplicates are generated.",
info="Number of chat completions to generate for each prompt. "
"Note that the API may not return the full n completions if duplicates are generated.",
advanced=True,
),
IntInput(

View file

@ -10,7 +10,10 @@ from langflow.template import Output
class JSONCleaner(Component):
display_name = "JSON Cleaner"
description = "Cleans the messy and sometimes incorrect JSON strings produced by LLMs so that they are fully compliant with the JSON spec."
description = (
"Cleans the messy and sometimes incorrect JSON strings produced by LLMs "
"so that they are fully compliant with the JSON spec."
)
icon = "custom_components"
inputs = [

View file

@ -31,7 +31,11 @@ class VectaraSelfQueryRetriverComponent(CustomComponent):
},
"metadata_field_info": {
"display_name": "Metadata Field Info",
"info": 'Each metadata field info is a string in the form of key value pair dictionary containing additional search metadata.\nExample input: {"name":"speech","description":"what name of the speech","type":"string or list[string]"}.\nThe keys should remain constant(name, description, type)',
"info": "Each metadata field info is a string in the form of key value pair dictionary containing "
"additional search metadata.\n"
'Example input: {"name":"speech","description":"what name of the speech","type":'
'"string or list[string]"}.\n'
"The keys should remain constant(name, description, type)",
},
}

View file

@ -42,7 +42,8 @@ class NaturalLanguageTextSplitterComponent(LCTextSplitterComponent):
MessageTextInput(
name="language",
display_name="Language",
info='The language of the text. Default is "English". Supports multiple languages for better text boundary recognition.',
info='The language of the text. Default is "English". '
"Supports multiple languages for better text boundary recognition.",
),
]

View file

@ -26,7 +26,9 @@ class PythonREPLToolComponent(LCToolComponent):
name="description",
display_name="Tool Description",
info="A description of the tool.",
value="A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.",
value="A Python shell. Use this to execute python commands. "
"Input should be a valid python command. "
"If you want to see the output of a value, you should print it out with `print(...)`.",
),
StrInput(
name="global_imports",

View file

@ -192,7 +192,8 @@ class AstraVectorStoreComponent(LCVectorStoreComponent):
FloatInput(
name="search_score_threshold",
display_name="Search Score Threshold",
info="Minimum similarity score threshold for search results. (when using 'Similarity with score threshold')",
info="Minimum similarity score threshold for search results. "
"(when using 'Similarity with score threshold')",
value=0,
advanced=True,
),
@ -278,8 +279,10 @@ class AstraVectorStoreComponent(LCVectorStoreComponent):
new_parameter_0 = DropdownInput(
name="z_00_model_name",
display_name="Model Name",
info=f"The embedding model to use for the selected provider. Each provider has a different set of models "
f"available (full list at https://docs.datastax.com/en/astra-db-serverless/databases/embedding-generation.html):\n\n{', '.join(model_options)}",
info="The embedding model to use for the selected provider. Each provider has a different set of "
"models available (full list at "
"https://docs.datastax.com/en/astra-db-serverless/databases/embedding-generation.html):\n\n"
f"{', '.join(model_options)}",
options=model_options,
required=True,
).to_dict()
@ -293,13 +296,17 @@ class AstraVectorStoreComponent(LCVectorStoreComponent):
new_parameter_2 = MessageTextInput(
name="z_02_api_key_name",
display_name="API Key name",
info="The name of the embeddings provider API key stored on Astra. If set, it will override the 'ProviderKey' in the authentication parameters.",
info="The name of the embeddings provider API key stored on Astra. "
"If set, it will override the 'ProviderKey' in the authentication parameters.",
).to_dict()
new_parameter_3 = SecretStrInput(
name="z_03_provider_api_key",
display_name="Provider API Key",
info="An alternative to the Astra Authentication that passes an API key for the provider with each request to Astra DB. This may be used when Vectorize is configured for the collection, but no corresponding provider secret is stored within Astra's key management system.",
info="An alternative to the Astra Authentication that passes an API key for the provider "
"with each request to Astra DB. "
"This may be used when Vectorize is configured for the collection, "
"but no corresponding provider secret is stored within Astra's key management system.",
).to_dict()
new_parameter_4 = DictInput(

View file

@ -104,7 +104,8 @@ class CassandraVectorStoreComponent(LCVectorStoreComponent):
FloatInput(
name="search_score_threshold",
display_name="Search Score Threshold",
info="Minimum similarity score threshold for search results. (when using 'Similarity with score threshold')",
info="Minimum similarity score threshold for search results. "
"(when using 'Similarity with score threshold')",
value=0,
advanced=True,
),
@ -235,7 +236,8 @@ class CassandraVectorStoreComponent(LCVectorStoreComponent):
except KeyError as e:
if "content" in str(e):
raise ValueError(
"You should ingest data through Langflow (or LangChain) to query it in Langflow. Your collection does not contain a field name 'content'."
"You should ingest data through Langflow (or LangChain) to query it in Langflow. "
"Your collection does not contain a field name 'content'."
)
else:
raise e

View file

@ -106,7 +106,8 @@ class CassandraGraphVectorStoreComponent(LCVectorStoreComponent):
FloatInput(
name="search_score_threshold",
display_name="Search Score Threshold",
info="Minimum similarity score threshold for search results. (when using 'Similarity with score threshold')",
info="Minimum similarity score threshold for search results. "
"(when using 'Similarity with score threshold')",
value=0,
advanced=True,
),
@ -214,7 +215,8 @@ class CassandraGraphVectorStoreComponent(LCVectorStoreComponent):
except KeyError as e:
if "content" in str(e):
raise ValueError(
"You should ingest data through Langflow (or LangChain) to query it in Langflow. Your collection does not contain a field name 'content'."
"You should ingest data through Langflow (or LangChain) to query it in Langflow. "
"Your collection does not contain a field name 'content'."
) from e
else:
raise e

View file

@ -73,7 +73,8 @@ class ClickhouseVectorStoreComponent(LCVectorStoreComponent):
import clickhouse_connect # type: ignore
except ImportError as e:
raise ImportError(
"Failed to import Clickhouse dependencies. Install it using `pip install langflow[clickhouse-connect] --pre`"
"Failed to import Clickhouse dependencies. "
"Install it using `pip install langflow[clickhouse-connect] --pre`"
) from e
try:

View file

@ -41,7 +41,8 @@ class FaissVectorStoreComponent(LCVectorStoreComponent):
BoolInput(
name="allow_dangerous_deserialization",
display_name="Allow Dangerous Deserialization",
info="Set to True to allow loading pickle files from untrusted sources. Only enable this if you trust the source of the data.",
info="Set to True to allow loading pickle files from untrusted sources. "
"Only enable this if you trust the source of the data.",
advanced=True,
value=True,
),

View file

@ -128,7 +128,8 @@ class HCDVectorStoreComponent(LCVectorStoreComponent):
name="embedding",
display_name="Embedding or Astra Vectorize",
input_types=["Embeddings", "dict"],
info="Allows either an embedding model or an Astra Vectorize configuration.", # TODO: This should be optional, but need to refactor langchain-astradb first.
# TODO: This should be optional, but need to refactor langchain-astradb first.
info="Allows either an embedding model or an Astra Vectorize configuration.",
),
StrInput(
name="metadata_indexing_exclude",
@ -160,7 +161,8 @@ class HCDVectorStoreComponent(LCVectorStoreComponent):
FloatInput(
name="search_score_threshold",
display_name="Search Score Threshold",
info="Minimum similarity score threshold for search results. (when using 'Similarity with score threshold')",
info="Minimum similarity score threshold for search results. "
"(when using 'Similarity with score threshold')",
value=0,
advanced=True,
),

View file

@ -65,7 +65,8 @@ class VectaraRagComponent(Component):
range_spec=RangeSpec(min=0.005, max=0.1, step=0.005),
value=0.005,
advanced=True,
info="How much to weigh lexical scores compared to the embedding score. 0 means lexical search is not used at all, and 1 means only lexical search is used.",
info="How much to weigh lexical scores compared to the embedding score. "
"0 means lexical search is not used at all, and 1 means only lexical search is used.",
),
MessageTextInput(
name="filter",
@ -118,7 +119,8 @@ class VectaraRagComponent(Component):
options=SUMMARIZER_PROMPTS,
value=SUMMARIZER_PROMPTS[0],
advanced=True,
info="Only vectara-summary-ext-24-05-sml is for Growth customers; all other prompts are for Scale customers only.",
info="Only vectara-summary-ext-24-05-sml is for Growth customers; "
"all other prompts are for Scale customers only.",
),
]

View file

@ -341,7 +341,8 @@ class Component(CustomComponent):
if len(matching_pairs) > 1:
matching_pairs_str = self._build_error_string_from_matching_pairs(matching_pairs)
raise ValueError(
f"There are multiple outputs from {value.__class__.__name__} that can connect to inputs in {self.__class__.__name__}: {matching_pairs_str}"
f"There are multiple outputs from {value.__class__.__name__} "
f"that can connect to inputs in {self.__class__.__name__}: {matching_pairs_str}"
)
output, input_ = matching_pairs[0]
if not isinstance(output.method, str):

View file

@ -240,7 +240,8 @@ class CustomComponent(BaseComponent):
If the input data is a Langchain Document, text_key and data_key are ignored.
keys (List[str], optional): The keys to access the text and data values in each item.
It should be a list of strings where the first element is the text key and the second element is the data key.
It should be a list of strings where the first element is the text key and the second element
is the data key.
Defaults to None, in which case the default keys "text" and "data" are used.
Returns:

View file

@ -31,11 +31,13 @@ class Edge:
if hasattr(target, "_custom_component"):
display_name = getattr(target._custom_component, "display_name", "")
raise ValueError(
f"Component {display_name} field '{self._target_handle['fieldName']}' might not be a valid input."
f"Component {display_name} field '{self._target_handle['fieldName']}' "
"might not be a valid input."
) from e
else:
raise ValueError(
f"Field '{self._target_handle['fieldName']}' on {target.display_name} might not be a valid input."
f"Field '{self._target_handle['fieldName']}' on {target.display_name} "
"might not be a valid input."
) from e
else:
raise e

View file

@ -139,7 +139,10 @@ def generate_function_for_flow(
"""
# Prepare function arguments with type hints and default values
args = [
f"{input_.display_name.lower().replace(' ', '_')}: {INPUT_TYPE_MAP[input_.base_name]['type_hint']} = {INPUT_TYPE_MAP[input_.base_name]['default']}"
(
f"{input_.display_name.lower().replace(' ', '_')}: {INPUT_TYPE_MAP[input_.base_name]['type_hint']} = "
f"{INPUT_TYPE_MAP[input_.base_name]['default']}"
)
for input_ in inputs
]
@ -254,7 +257,8 @@ def get_arg_names(inputs: list["Vertex"]) -> list[dict[str, str]]:
inputs (List[Vertex]): A list of Vertex objects representing the inputs.
Returns:
List[dict[str, str]]: A list of dictionaries, where each dictionary contains the component name and its argument name.
List[dict[str, str]]: A list of dictionaries, where each dictionary contains the component name and its
argument name.
"""
return [
{"component_name": input_.display_name, "arg_name": input_.display_name.lower().replace(" ", "_")}

View file

@ -28,7 +28,8 @@ Blog:
text_input = TextInputComponent(_display_name="Instructions")
text_input.set(
input_value="Use the references above for style to write a new blog/tutorial about Langflow and AI. Suggest non-covered topics."
input_value="Use the references above for style to write a new blog/tutorial about Langflow and AI. "
"Suggest non-covered topics."
)
prompt_component = PromptComponent()

View file

@ -67,7 +67,8 @@ Backstory:""",
template="""User's query:
{query}
Respond to the user with as much as information as you can about the topic. Delete if needed. If it is just a general query (e.g a greeting) you can respond them directly.""",
Respond to the user with as much as information as you can about the topic. Delete if needed.
If it is just a general query (e.g a greeting) you can respond them directly.""",
query=chat_input.message_response,
)
manager_agent = CrewAIAgentComponent()

View file

@ -37,7 +37,8 @@ def hierarchical_tasks_agent_graph():
template="""User's query:
{query}
Respond to the user with as much as information as you can about the topic. Delete if needed. If it is just a general query (e.g a greeting) you can respond them directly.""",
Respond to the user with as much as information as you can about the topic. Delete if needed.
If it is just a general query (e.g a greeting) you can respond them directly.""",
query=chat_input.message_response,
)
manager_agent = CrewAIAgentComponent()

View file

@ -49,7 +49,8 @@ Revise this document.""",
editor_task_agent = SequentialTaskAgentComponent()
editor_task_agent.set(
role="Editor",
goal="You should edit the information provided by the Researcher to make it more palatable and to not contain misleading information.",
goal="You should edit the information provided by the Researcher to make it more palatable and to not contain "
"misleading information.",
backstory="You are the editor of the most reputable journal in the world.",
llm=llm.build_model,
task_description=revision_prompt_component.build_prompt,
@ -71,7 +72,8 @@ Build a fun blog post about this topic.""",
comedian_task_agent.set(
role="Comedian",
goal="You write comedic content based on the information provided by the editor.",
backstory="Your formal occupation is Comedian-in-Chief. You write jokes, do standup comedy, and write funny articles.",
backstory="Your formal occupation is Comedian-in-Chief. "
"You write jokes, do standup comedy, and write funny articles.",
llm=llm.build_model,
task_description=blog_prompt_component.build_prompt,
expected_output="A small blog about the topic.",

View file

@ -40,7 +40,8 @@ class TableInput(BaseInputMixin, MetadataTraceMixin, TableMixin, ListableInputMi
for item in v:
if not isinstance(item, dict | Data):
raise ValueError(
f"TableInput value must be a list of dictionaries or Data. Item '{item}' is not a dictionary or Data."
"TableInput value must be a list of dictionaries or Data. "
f"Item '{item}' is not a dictionary or Data."
)
return v
@ -104,7 +105,8 @@ class StrInput(BaseInputMixin, ListableInputMixin, DatabaseLoadMixin, MetadataTr
# Keep the warning for now, but we should change it to an error
if _info.data.get("input_types") and v.__class__.__name__ not in _info.data.get("input_types"):
warnings.warn(
f"Invalid value type {type(v)} for input {_info.data.get('name')}. Expected types: {_info.data.get('input_types')}"
f"Invalid value type {type(v)} for input {_info.data.get('name')}. "
f"Expected types: {_info.data.get('input_types')}"
)
else:
warnings.warn(f"Invalid value type {type(v)} for input {_info.data.get('name')}.")
@ -154,10 +156,12 @@ class MessageTextInput(StrInput, MetadataTraceMixin, InputTraceMixin):
"""
Represents a text input component for the Langflow system.
This component is used to handle text inputs in the Langflow system. It provides methods for validating and processing text values.
This component is used to handle text inputs in the Langflow system.
It provides methods for validating and processing text values.
Attributes:
input_types (list[str]): A list of input types that this component supports. In this case, it supports the "Message" input type.
input_types (list[str]): A list of input types that this component supports.
In this case, it supports the "Message" input type.
"""
input_types: list[str] = ["Message"]
@ -192,7 +196,8 @@ class MessageTextInput(StrInput, MetadataTraceMixin, InputTraceMixin):
input_name = _info.data["name"]
raise ValueError(
f"The input to '{input_name}' must contain the key '{v.text_key}'."
f"You can set `text_key` to one of the following keys: {keys} or set the value using another Component."
f"You can set `text_key` to one of the following keys: {keys} "
"or set the value using another Component."
)
elif isinstance(v, AsyncIterator | Iterator):
value = v
@ -274,7 +279,8 @@ class SecretStrInput(BaseInputMixin, DatabaseLoadMixin):
input_name = _info.data["name"]
raise ValueError(
f"The input to '{input_name}' must contain the key '{v.text_key}'."
f"You can set `text_key` to one of the following keys: {keys} or set the value using another Component."
f"You can set `text_key` to one of the following keys: {keys} "
"or set the value using another Component."
)
elif isinstance(v, AsyncIterator | Iterator):
value = v

View file

@ -98,7 +98,8 @@ def run_flow_from_json(
env_file (Optional[str], optional): The environment file to load. Defaults to None.
cache (Optional[str], optional): The cache directory to use. Defaults to None.
disable_logs (Optional[bool], optional): Whether to disable logs. Defaults to True.
fallback_to_env_vars (bool, optional): Whether Global Variables should fallback to environment variables if not found. Defaults to False.
fallback_to_env_vars (bool, optional): Whether Global Variables should fallback to environment variables if
not found. Defaults to False.
Returns:
List[RunOutputs]: A list of RunOutputs objects representing the results of running the flow.

View file

@ -69,7 +69,10 @@ class JavaScriptMIMETypeMiddleware(BaseHTTPMiddleware):
response = await call_next(request)
except Exception as exc:
if isinstance(exc, PydanticSerializationError):
message = "Something went wrong while serializing the response. Please share this error on our GitHub repository."
message = (
"Something went wrong while serializing the response. "
"Please share this error on our GitHub repository."
)
error_messages = json.dumps([message, str(exc)])
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=error_messages) from exc
raise exc

View file

@ -119,7 +119,8 @@ def store_message(
Args:
message (Message): The message to store.
flow_id (Optional[str]): The flow ID associated with the message. When running from the CustomComponent you can access this using `self.graph.flow_id`.
flow_id (Optional[str]): The flow ID associated with the message.
When running from the CustomComponent you can access this using `self.graph.flow_id`.
Returns:
List[Message]: A list of data containing the stored message.

View file

@ -162,7 +162,8 @@ def process_tweaks(
'nodes' as its child or directly contain 'nodes' key. Each node should have an 'id' and 'data'.
:param tweaks: The dictionary containing the tweaks. The keys can be the node id or the name of the tweak.
The values can be a dictionary containing the tweaks for the node or the value of the tweak.
:param stream: A boolean flag indicating whether streaming should be deactivated across all components or not. Default is False.
:param stream: A boolean flag indicating whether streaming should be deactivated across all components or not.
Default is False.
:return: The modified graph_data dictionary.
:raises ValueError: If the input is not in the expected format.
"""

View file

@ -4,7 +4,8 @@ class dotdict(dict):
It automatically converts nested dictionaries into dotdict instances, enabling dot notation on them as well.
Note:
- Only keys that are valid attribute names (e.g., strings that could be variable names) are accessible via dot notation.
- Only keys that are valid attribute names (e.g., strings that could be variable names) are accessible via dot
notation.
- Keys which are not valid Python attribute names or collide with the dict method names (like 'items', 'keys')
should be accessed using the traditional dict['key'] notation.
"""

View file

@ -10,13 +10,16 @@ class InputValue(BaseModel):
input_value: str | None = None
type: InputType | None = Field(
"any",
description="Defines on which components the input value should be applied. 'any' applies to all input components.",
description="Defines on which components the input value should be applied. "
"'any' applies to all input components.",
)
class Tweaks(RootModel):
root: dict[str, str | dict[str, Any]] = Field(
description="A dictionary of tweaks to adjust the flow's execution. Allows customizing flow behavior dynamically. All tweaks are overridden by the input values.",
description="A dictionary of tweaks to adjust the flow's execution. "
"Allows customizing flow behavior dynamically. "
"All tweaks are overridden by the input values.",
)
model_config = {
"json_schema_extra": {

View file

@ -44,7 +44,8 @@ class ChatService(Service):
Args:
operation (str): The type of cache operation to perform. Possible values are "upsert", "get", or "delete".
key (str): The key associated with the cache operation.
data (Any, optional): The data to be stored in the cache. Only applicable for "upsert" operation. Defaults to None.
data (Any, optional): The data to be stored in the cache. Only applicable for "upsert" operation.
Defaults to None.
lock (Optional[asyncio.Lock], optional): The lock to be used for the cache operation. Defaults to None.
Returns:

View file

@ -71,7 +71,8 @@ class DatabaseService(Service):
# https://stackoverflow.com/questions/62688256/sqlalchemy-exc-nosuchmoduleerror-cant-load-plugin-sqlalchemy-dialectspostgre
self.database_url = self.database_url.replace("postgres://", "postgresql://")
logger.warning(
"Fixed postgres dialect in database URL. Replacing postgres:// with postgresql://. To avoid this warning, update the database URL."
"Fixed postgres dialect in database URL. Replacing postgres:// with postgresql://. "
"To avoid this warning, update the database URL."
)
return self._create_engine()
raise RuntimeError("Error creating database engine") from exc

View file

@ -63,7 +63,8 @@ class Settings(BaseSettings):
# Define if langflow db should be saved in config dir or
# in the langflow directory
save_db_in_config_dir: bool = False
"""Define if langflow database should be saved in LANGFLOW_CONFIG_DIR or in the langflow directory (i.e. in the package directory)."""
"""Define if langflow database should be saved in LANGFLOW_CONFIG_DIR or in the langflow directory
(i.e. in the package directory)."""
dev: bool = False
"""If True, Langflow will run in development mode."""
@ -75,7 +76,8 @@ class Settings(BaseSettings):
"""The number of connections to allow that can be opened beyond the pool size.
If not provided, the default is 20."""
db_connect_timeout: int = 20
"""The number of seconds to wait before giving up on a lock to released or establishing a connection to the database."""
"""The number of seconds to wait before giving up on a lock to released or establishing a connection to the
database."""
# sqlite configuration
sqlite_pragmas: dict | None = {"synchronous": "NORMAL", "journal_mode": "WAL"}

View file

@ -39,7 +39,8 @@ class LangWatchTracer(BaseTracer):
name_without_id = " - ".join(trace_name.split(" - ")[0:-1])
self.trace.root_span.update(
span_id=f"{self.flow_id}-{nanoid.generate(size=6)}", # nanoid to make the span_id globally unique, which is required for LangWatch for now
# nanoid to make the span_id globally unique, which is required for LangWatch for now
span_id=f"{self.flow_id}-{nanoid.generate(size=6)}",
name=name_without_id,
type="workflow",
)
@ -86,7 +87,8 @@ class LangWatchTracer(BaseTracer):
)
span = self.trace.span(
span_id=f"{trace_id}-{nanoid.generate(size=6)}", # Add a nanoid to make the span_id globally unique, which is required for LangWatch for now
# Add a nanoid to make the span_id globally unique, which is required for LangWatch for now
span_id=f"{trace_id}-{nanoid.generate(size=6)}",
name=name_without_id,
type="component",
parent=(previous_nodes[-1] if len(previous_nodes) > 0 else self.trace.root_span),

View file

@ -129,8 +129,8 @@ class FrontendNode(BaseModel):
)
def validate_attributes(self) -> None:
# None of inputs, outputs, _artifacts, _results, logs, status, vertex, graph, display_name, description, documentation, icon
# should be present in outputs or input names
# None of inputs, outputs, _artifacts, _results, logs, status, vertex, graph, display_name, description,
# documentation, icon should be present in outputs or input names
output_names = [output.name for output in self.outputs]
input_names = [input_.name for input_ in self.template.fields]
attributes = [

View file

@ -148,7 +148,7 @@ exclude = ["langflow/alembic"]
line-length = 120
[tool.ruff.lint]
select = ["C4", "E4", "E7", "E9", "F", "I", "UP"]
select = ["C4", "E", "F", "I", "UP"]
[build-system]
requires = ["hatchling"]