ref: Add ruff rules RUF (#4001)

Add ruff rules RUF
This commit is contained in:
Christophe Bornet 2024-10-04 17:01:56 +02:00 committed by GitHub
commit 63beae1833
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
86 changed files with 196 additions and 228 deletions

View file

@ -67,7 +67,7 @@ class AsyncStreamingLLMCallbackHandleSIO(AsyncCallbackHandler):
)
for word in rest_of_output
]
resps = [resp] + rest_of_resps
resps = [resp, *rest_of_resps]
# Try to send the response, handle potential errors.
try:

View file

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

View file

@ -382,9 +382,9 @@ async def experimental_run_flow(
flow_id: UUID,
inputs: list[InputValueRequest] | None = None,
outputs: list[str] | None = None,
tweaks: Annotated[Tweaks | None, Body(embed=True)] = None, # noqa: F821
stream: Annotated[bool, Body(embed=True)] = False, # noqa: F821
session_id: Annotated[None | str, Body(embed=True)] = None, # noqa: F821
tweaks: Annotated[Tweaks | None, Body(embed=True)] = None,
stream: Annotated[bool, Body(embed=True)] = False,
session_id: Annotated[None | str, Body(embed=True)] = None,
api_key_user: UserRead = Depends(api_key_security),
session_service: SessionService = Depends(get_session_service),
):
@ -509,11 +509,11 @@ async def process(
flow_id: str,
inputs: list[dict] | dict | None = None,
tweaks: dict | None = None,
clear_cache: Annotated[bool, Body(embed=True)] = False, # noqa: F821
session_id: Annotated[None | str, Body(embed=True)] = None, # noqa: F821
clear_cache: Annotated[bool, Body(embed=True)] = False,
session_id: Annotated[None | str, Body(embed=True)] = None,
task_service: TaskService = Depends(get_task_service),
api_key_user: UserRead = Depends(api_key_security),
sync: Annotated[bool, Body(embed=True)] = True, # noqa: F821
sync: Annotated[bool, Body(embed=True)] = True,
session_service: SessionService = Depends(get_session_service),
):
"""

View file

@ -196,7 +196,7 @@ def read_flow(
# so write an OR
stmt = stmt.where(
(Flow.user_id == current_user.id) | (Flow.user_id == None) # noqa
) # noqa
)
if user_flow := session.exec(stmt).first():
return user_flow
raise HTTPException(status_code=404, detail="Flow not found")

View file

@ -102,7 +102,7 @@ class LCAgentComponent(Component):
if self.chat_history:
input_dict["chat_history"] = data_to_messages(self.chat_history)
result = agent.invoke(
input_dict, config={"callbacks": [AgentAsyncHandler(self.log)] + self.get_langchain_callbacks()}
input_dict, config={"callbacks": [AgentAsyncHandler(self.log), *self.get_langchain_callbacks()]}
)
self.status = result
if "output" not in result:
@ -113,13 +113,9 @@ class LCAgentComponent(Component):
class LCToolsAgentComponent(LCAgentComponent):
_base_inputs = LCAgentComponent._base_inputs + [
HandleInput(
name="tools",
display_name="Tools",
input_types=["Tool", "BaseTool"],
is_list=True,
),
_base_inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="tools", display_name="Tools", input_types=["Tool", "BaseTool"], is_list=True),
]
def build_agent(self) -> AgentExecutor:
@ -149,7 +145,7 @@ class LCToolsAgentComponent(LCAgentComponent):
input_dict["chat_history"] = data_to_messages(self.chat_history)
result = runnable.invoke(
input_dict, config={"callbacks": [AgentAsyncHandler(self.log)] + self.get_langchain_callbacks()}
input_dict, config={"callbacks": [AgentAsyncHandler(self.log), *self.get_langchain_callbacks()]}
)
self.status = result
if "output" not in result:

View file

@ -56,7 +56,7 @@ def build_data_from_result_data(result_data: ResultData, get_final_results_only:
data.append(artifact)
else:
# Warn about unknown output type
logger.warning(f"Unable to build record output from unknown ResultData.artifact: {str(artifact)}")
logger.warning(f"Unable to build record output from unknown ResultData.artifact: {artifact}")
# Chat or text output
elif result_data.results:
data.append(Data(data={"result": result_data.results}, text_key="result"))

View file

@ -157,7 +157,10 @@ class LCModelComponent(Component):
if "prompt" in input_value:
prompt = input_value.load_lc_prompt()
if system_message:
prompt.messages = [SystemMessage(content=system_message)] + prompt.messages
prompt.messages = [
SystemMessage(content=system_message),
*prompt.messages, # type: ignore[has-type]
]
system_message_added = True
runnable = prompt | runnable
else:

View file

@ -62,7 +62,7 @@ def _fix_variable(var, invalid_chars, wrong_variables):
new_var, invalid_chars, wrong_variables = _fix_variable(var[1:], invalid_chars, wrong_variables)
# Temporarily replace {{ and }} to avoid treating them as invalid
new_var = new_var.replace("{{", "ᴛᴇᴍᴘᴏᴘᴇɴ").replace("}}", "ᴛᴇᴍᴘʟsᴇ")
new_var = new_var.replace("{{", "ᴛᴇᴍᴘᴏᴘᴇɴ").replace("}}", "ᴛᴇᴍᴘʟsᴇ") # noqa: RUF001
# Remove invalid characters
for char in new_var:
@ -73,7 +73,7 @@ def _fix_variable(var, invalid_chars, wrong_variables):
wrong_variables.append(var)
# Restore {{ and }}
new_var = new_var.replace("ᴛᴇᴍᴘᴏᴘᴇɴ", "{{").replace("ᴛᴇᴍᴘʟsᴇ", "}}")
new_var = new_var.replace("ᴛᴇᴍᴘᴏᴘᴇɴ", "{{").replace("ᴛᴇᴍᴘʟsᴇ", "}}") # noqa: RUF001
return new_var, invalid_chars, wrong_variables
@ -146,7 +146,7 @@ def get_old_custom_fields(custom_fields, name):
if len(custom_fields) == 1 and name == "":
# If there is only one custom field and the name is empty string
# then we are dealing with the first prompt request after the node was created
name = list(custom_fields.keys())[0]
name = next(iter(custom_fields.keys()))
old_custom_fields = custom_fields[name]
if not old_custom_fields:

View file

@ -76,12 +76,12 @@ class AddContentToPage(LCToolComponent):
return response.json()
except requests.exceptions.RequestException as e:
error_message = f"Error: Failed to add content to Notion page. {str(e)}"
error_message = f"Error: Failed to add content to Notion page. {e}"
if hasattr(e, "response") and e.response is not None:
error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}"
return error_message
except Exception as e:
return f"Error: An unexpected error occurred while adding content to Notion page. {str(e)}"
return f"Error: An unexpected error occurred while adding content to Notion page. {e}"
def process_node(self, node):
blocks = []

View file

@ -67,7 +67,7 @@ class NotionPageCreator(LCToolComponent):
try:
properties = json.loads(properties_json)
except json.JSONDecodeError as e:
return f"Invalid properties format. Please provide a valid JSON string. Error: {str(e)}"
return f"Invalid properties format. Please provide a valid JSON string. Error: {e}"
headers = {
"Authorization": f"Bearer {self.notion_secret}",
@ -85,7 +85,7 @@ class NotionPageCreator(LCToolComponent):
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
error_message = f"Failed to create Notion page. Error: {str(e)}"
error_message = f"Failed to create Notion page. Error: {e}"
if hasattr(e, "response") and e.response is not None:
error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}"
return error_message

View file

@ -59,8 +59,8 @@ class NotionDatabaseProperties(LCToolComponent):
data = response.json()
return data.get("properties", {})
except requests.exceptions.RequestException as e:
return f"Error fetching Notion database properties: {str(e)}"
return f"Error fetching Notion database properties: {e}"
except ValueError as e:
return f"Error parsing Notion API response: {str(e)}"
return f"Error parsing Notion API response: {e}"
except Exception as e:
return f"An unexpected error occurred: {str(e)}"
return f"An unexpected error occurred: {e}"

View file

@ -105,7 +105,7 @@ class NotionListPages(LCToolComponent):
try:
query_payload = json.loads(query_json)
except json.JSONDecodeError as e:
return f"Invalid JSON format for query: {str(e)}"
return f"Invalid JSON format for query: {e}"
try:
response = requests.post(url, headers=headers, json=query_payload)
@ -113,8 +113,8 @@ class NotionListPages(LCToolComponent):
results = response.json()
return results["results"]
except requests.exceptions.RequestException as e:
return f"Error querying Notion database: {str(e)}"
return f"Error querying Notion database: {e}"
except KeyError:
return "Unexpected response format from Notion API"
except Exception as e:
return f"An unexpected error occurred: {str(e)}"
return f"An unexpected error occurred: {e}"

View file

@ -59,12 +59,12 @@ class NotionPageContent(LCToolComponent):
blocks_data = blocks_response.json()
return self.parse_blocks(blocks_data.get("results", []))
except requests.exceptions.RequestException as e:
error_message = f"Error: Failed to retrieve Notion page content. {str(e)}"
error_message = f"Error: Failed to retrieve Notion page content. {e}"
if hasattr(e, "response") and e.response is not None:
error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}"
return error_message
except Exception as e:
return f"Error: An unexpected error occurred while retrieving Notion page content. {str(e)}"
return f"Error: An unexpected error occurred while retrieving Notion page content. {e}"
def parse_blocks(self, blocks: list) -> str:
content = ""

View file

@ -76,7 +76,7 @@ class NotionPageUpdate(LCToolComponent):
try:
parsed_properties = json.loads(properties)
except json.JSONDecodeError as e:
error_message = f"Invalid JSON format for properties: {str(e)}"
error_message = f"Invalid JSON format for properties: {e}"
logger.error(error_message)
return error_message
@ -94,18 +94,18 @@ class NotionPageUpdate(LCToolComponent):
logger.info(f"Successfully updated Notion page. Response: {json.dumps(updated_page)}")
return updated_page
except requests.exceptions.HTTPError as e:
error_message = f"HTTP Error occurred: {str(e)}"
error_message = f"HTTP Error occurred: {e}"
if e.response is not None:
error_message += f"\nStatus code: {e.response.status_code}"
error_message += f"\nResponse body: {e.response.text}"
logger.error(error_message)
return error_message
except requests.exceptions.RequestException as e:
error_message = f"An error occurred while making the request: {str(e)}"
error_message = f"An error occurred while making the request: {e}"
logger.error(error_message)
return error_message
except Exception as e:
error_message = f"An unexpected error occurred: {str(e)}"
error_message = f"An unexpected error occurred: {e}"
logger.error(error_message)
return error_message

View file

@ -14,7 +14,8 @@ class CSVAgentComponent(LCAgentComponent):
documentation = "https://python.langchain.com/docs/modules/agents/toolkits/csv"
name = "CSVAgent"
inputs = LCAgentComponent._base_inputs + [
inputs = [
*LCAgentComponent._base_inputs,
HandleInput(
name="llm",
display_name="Language Model",

View file

@ -12,7 +12,8 @@ class HierarchicalCrewComponent(BaseCrewComponent):
documentation: str = "https://docs.crewai.com/how-to/Hierarchical/"
icon = "CrewAI"
inputs = BaseCrewComponent._base_inputs + [
inputs = [
*BaseCrewComponent._base_inputs,
HandleInput(name="agents", display_name="Agents", input_types=["Agent"], is_list=True),
HandleInput(name="tasks", display_name="Tasks", input_types=["HierarchicalTask"], is_list=True),
HandleInput(name="manager_llm", display_name="Manager LLM", input_types=["LanguageModel"], required=False),

View file

@ -15,7 +15,8 @@ class JsonAgentComponent(LCAgentComponent):
description = "Construct a json agent from an LLM and tools."
name = "JsonAgent"
inputs = LCAgentComponent._base_inputs + [
inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
FileInput(name="path", display_name="File Path", file_types=["json", "yaml", "yml"], required=True),
]

View file

@ -14,7 +14,8 @@ class OpenAIToolsAgentComponent(LCToolsAgentComponent):
beta = True
name = "OpenAIToolsAgent"
inputs = LCToolsAgentComponent._base_inputs + [
inputs = [
*LCToolsAgentComponent._base_inputs,
HandleInput(
name="llm",
display_name="Language Model",

View file

@ -16,7 +16,8 @@ class OpenAPIAgentComponent(LCAgentComponent):
description = "Agent to interact with OpenAPI API."
name = "OpenAPIAgent"
inputs = LCAgentComponent._base_inputs + [
inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
FileInput(name="path", display_name="File Path", file_types=["json", "yaml", "yml"], required=True),
BoolInput(name="allow_dangerous_requests", display_name="Allow Dangerous Requests", value=False, required=True),

View file

@ -12,7 +12,8 @@ class SQLAgentComponent(LCAgentComponent):
description = "Construct an SQL agent from an LLM and tools."
name = "SQLAgent"
inputs = LCAgentComponent._base_inputs + [
inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
MessageTextInput(name="database_uri", display_name="Database URI", required=True),
HandleInput(

View file

@ -11,7 +11,8 @@ class SequentialCrewComponent(BaseCrewComponent):
documentation: str = "https://docs.crewai.com/how-to/Sequential/"
icon = "CrewAI"
inputs = BaseCrewComponent._base_inputs + [
inputs = [
*BaseCrewComponent._base_inputs,
HandleInput(name="tasks", display_name="Tasks", input_types=["SequentialTask"], is_list=True),
]

View file

@ -130,9 +130,9 @@ class SequentialTaskAgentComponent(Component):
# If there's a previous task, create a list of tasks
if self.previous_task:
tasks = self.previous_task + [task] if isinstance(self.previous_task, list) else [self.previous_task, task]
tasks = [*self.previous_task, task] if isinstance(self.previous_task, list) else [self.previous_task, task]
else:
tasks = [task]
self.status = f"Agent: {repr(agent)}\nTask: {repr(task)}"
self.status = f"Agent: {agent!r}\nTask: {task!r}"
return tasks

View file

@ -14,7 +14,8 @@ class ToolCallingAgentComponent(LCToolsAgentComponent):
beta = True
name = "ToolCallingAgent"
inputs = LCToolsAgentComponent._base_inputs + [
inputs = [
*LCToolsAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
MultilineInput(
name="system_prompt",

View file

@ -10,7 +10,8 @@ class VectorStoreAgentComponent(LCAgentComponent):
description = "Construct an agent from a Vector Store."
name = "VectorStoreAgent"
inputs = LCAgentComponent._base_inputs + [
inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
HandleInput(name="vectorstore", display_name="Vector Store", input_types=["VectorStoreInfo"], required=True),
]

View file

@ -10,7 +10,8 @@ class VectorStoreRouterAgentComponent(LCAgentComponent):
description = "Construct an agent from a Vector Store Router."
name = "VectorStoreRouterAgent"
inputs = LCAgentComponent._base_inputs + [
inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
HandleInput(
name="vectorstores",

View file

@ -13,7 +13,8 @@ class XMLAgentComponent(LCToolsAgentComponent):
icon = "LangChain"
beta = True
name = "XMLAgent"
inputs = LCToolsAgentComponent._base_inputs + [
inputs = [
*LCToolsAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
DataInput(name="chat_history", display_name="Chat History", is_list=True, advanced=True),
MultilineInput(

View file

@ -54,7 +54,7 @@ class AssemblyAIGetSubtitles(Component):
transcript_id = self.transcription_result.data["id"]
transcript = aai.Transcript.get_by_id(transcript_id)
except Exception as e:
error = f"Getting transcription failed: {str(e)}"
error = f"Getting transcription failed: {e}"
self.status = error
return Data(data={"error": error})

View file

@ -135,7 +135,7 @@ class AssemblyAILeMUR(Component):
self.status = result
return result
except Exception as e:
error = f"An Error happened: {str(e)}"
error = f"An Error happened: {e}"
self.status = error
return Data(data={"error": error})

View file

@ -86,6 +86,6 @@ class AssemblyAIListTranscripts(Component):
self.status = transcripts
return transcripts
except Exception as e:
error_data = Data(data={"error": f"An error occurred: {str(e)}"})
error_data = Data(data={"error": f"An error occurred: {e}"})
self.status = [error_data]
return [error_data]

View file

@ -48,7 +48,7 @@ class AssemblyAITranscriptionJobPoller(Component):
try:
transcript = aai.Transcript.get_by_id(self.transcript_id.data["transcript_id"])
except Exception as e:
error = f"Getting transcription failed: {str(e)}"
error = f"Getting transcription failed: {e}"
self.status = error
return Data(data={"error": error})

View file

@ -181,5 +181,5 @@ class AssemblyAITranscriptionJobCreator(Component):
self.status = result
return result
except Exception as e:
self.status = f"An error occurred: {str(e)}"
return Data(data={"error": f"An error occurred: {str(e)}"})
self.status = f"An error occurred: {e}"
return Data(data={"error": f"An error occurred: {e}"})

View file

@ -41,7 +41,7 @@ class SubFlowComponent(CustomComponent):
build_config["flow_name"]["options"] = self.get_flow_names()
# Clean up the build config
for key in list(build_config.keys()):
if key not in self.field_order + ["code", "_type", "get_final_results_only"]:
if key not in [*self.field_order, "code", "_type", "get_final_results_only"]:
del build_config[key]
if field_value is not None and field_name == "flow_name":
try:
@ -55,7 +55,7 @@ class SubFlowComponent(CustomComponent):
# Add inputs to the build config
build_config = self.add_inputs_to_build_config(inputs, build_config)
except Exception as e:
logger.error(f"Error getting flow {field_value}: {str(e)}")
logger.error(f"Error getting flow {field_value}: {e}")
return build_config

View file

@ -77,7 +77,7 @@ class AzureOpenAIEmbeddingsComponent(LCModelComponent):
dimensions=self.dimensions or None,
)
except Exception as e:
msg = f"Could not connect to AzureOpenAIEmbeddings API: {str(e)}"
msg = f"Could not connect to AzureOpenAIEmbeddings API: {e}"
raise ValueError(msg) from e
return embeddings

View file

@ -82,11 +82,11 @@ class CSVToDataComponent(Component):
return result
except csv.Error as e:
error_message = f"CSV parsing error: {str(e)}"
error_message = f"CSV parsing error: {e}"
self.status = error_message
raise ValueError(error_message) from e
except Exception as e:
error_message = f"An error occurred: {str(e)}"
error_message = f"An error occurred: {e}"
self.status = error_message
raise ValueError(error_message) from e

View file

@ -68,6 +68,6 @@ class CurrentDateComponent(Component):
self.status = result
return Message(text=result)
except Exception as e:
error_message = f"Error: {str(e)}"
error_message = f"Error: {e}"
self.status = error_message
return Message(text=error_message)

View file

@ -90,11 +90,11 @@ class JSONToDataComponent(Component):
return result
except (json.JSONDecodeError, SyntaxError, ValueError) as e:
error_message = f"Invalid JSON or Python literal: {str(e)}"
error_message = f"Invalid JSON or Python literal: {e}"
self.status = error_message
raise ValueError(error_message) from e
except Exception as e:
error_message = f"An error occurred: {str(e)}"
error_message = f"An error occurred: {e}"
self.status = error_message
raise ValueError(error_message) from e

View file

@ -35,6 +35,6 @@ class MessageToDataComponent(Component):
self.status = "Successfully converted Message to Data"
return data
except Exception as e:
error_message = f"Error converting Message to Data: {str(e)}"
error_message = f"Error converting Message to Data: {e}"
self.status = error_message
return Data(data={"error": error_message})

View file

@ -68,5 +68,5 @@ class SequentialTaskComponent(Component):
if isinstance(self.task, list) and all(isinstance(task, SequentialTask) for task in self.task):
tasks = self.task + tasks
elif isinstance(self.task, SequentialTask):
tasks = [self.task] + tasks
tasks = [self.task, *tasks]
return tasks

View file

@ -113,7 +113,7 @@ class SpiderTool(Component):
msg = f"Invalid mode: {self.mode}. Must be 'scrape' or 'crawl'."
raise ValueError(msg)
except Exception as e:
msg = f"Error: {str(e)}"
msg = f"Error: {e}"
raise Exception(msg) from e
records = []

View file

@ -23,7 +23,8 @@ class AIMLModelComponent(LCModelComponent):
name = "AIMLModel"
documentation = "https://docs.aimlapi.com/api-reference"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
IntInput(
name="max_tokens",
display_name="Max Tokens",

View file

@ -11,7 +11,8 @@ class AmazonBedrockComponent(LCModelComponent):
icon = "Amazon"
name = "AmazonBedrockModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
DropdownInput(
name="model_id",
display_name="Model ID",

View file

@ -12,7 +12,8 @@ class AnthropicModelComponent(LCModelComponent):
icon = "Anthropic"
name = "AnthropicModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
IntInput(
name="max_tokens",
display_name="Max Tokens",
@ -32,11 +33,7 @@ class AnthropicModelComponent(LCModelComponent):
info="https://python.langchain.com/docs/integrations/chat/anthropic",
value="claude-3-5-sonnet-20240620",
),
SecretStrInput(
name="anthropic_api_key",
display_name="Anthropic API Key",
info="Your Anthropic API key.",
),
SecretStrInput(name="anthropic_api_key", display_name="Anthropic API Key", info="Your Anthropic API key."),
FloatInput(name="temperature", display_name="Temperature", value=0.1),
MessageTextInput(
name="anthropic_api_url",
@ -45,10 +42,7 @@ class AnthropicModelComponent(LCModelComponent):
info="Endpoint of the Anthropic API. Defaults to 'https://api.anthropic.com' if not specified.",
),
MessageTextInput(
name="prefill",
display_name="Prefill",
info="Prefill text to guide the model's response.",
advanced=True,
name="prefill", display_name="Prefill", info="Prefill text to guide the model's response.", advanced=True
),
HandleInput(
name="output_parser",

View file

@ -27,7 +27,8 @@ class AzureChatOpenAIComponent(LCModelComponent):
"2024-05-13",
]
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
MessageTextInput(
name="azure_endpoint",
display_name="Azure Endpoint",
@ -78,7 +79,7 @@ class AzureChatOpenAIComponent(LCModelComponent):
streaming=stream,
)
except Exception as e:
msg = f"Could not connect to AzureOpenAI API: {str(e)}"
msg = f"Could not connect to AzureOpenAI API: {e}"
raise ValueError(msg) from e
return output # type: ignore

View file

@ -14,7 +14,8 @@ class QianfanChatEndpointComponent(LCModelComponent):
icon = "BaiduQianfan"
name = "BaiduQianfanChatModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
DropdownInput(
name="model",
display_name="Model Name",
@ -64,9 +65,7 @@ class QianfanChatEndpointComponent(LCModelComponent):
advanced=True,
),
MessageTextInput(
name="endpoint",
display_name="Endpoint",
info="Endpoint of the Qianfan LLM, required if custom model used.",
name="endpoint", display_name="Endpoint", info="Endpoint of the Qianfan LLM, required if custom model used."
),
HandleInput(
name="output_parser",

View file

@ -14,7 +14,8 @@ class CohereComponent(LCModelComponent):
icon = "Cohere"
name = "CohereModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
SecretStrInput(
name="cohere_api_key",
display_name="Cohere API Key",

View file

@ -12,11 +12,10 @@ class GoogleGenerativeAIComponent(LCModelComponent):
icon = "GoogleGenerativeAI"
name = "GoogleGenerativeAIModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
IntInput(
name="max_output_tokens",
display_name="Max Output Tokens",
info="The maximum number of tokens to generate.",
name="max_output_tokens", display_name="Max Output Tokens", info="The maximum number of tokens to generate."
),
DropdownInput(
name="model",

View file

@ -14,12 +14,9 @@ class GroqModel(LCModelComponent):
icon = "Groq"
name = "GroqModel"
inputs = LCModelComponent._base_inputs + [
SecretStrInput(
name="groq_api_key",
display_name="Groq API Key",
info="API key for the Groq API.",
),
inputs = [
*LCModelComponent._base_inputs,
SecretStrInput(name="groq_api_key", display_name="Groq API Key", info="API key for the Groq API."),
MessageTextInput(
name="groq_api_base",
display_name="Groq API Base",
@ -75,7 +72,7 @@ class GroqModel(LCModelComponent):
model_list = response.json()
return [model["id"] for model in model_list.get("data", [])]
except requests.RequestException as e:
self.status = f"Error fetching models: {str(e)}"
self.status = f"Error fetching models: {e}"
return []
def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None):

View file

@ -17,12 +17,9 @@ class HuggingFaceEndpointsComponent(LCModelComponent):
icon = "HuggingFace"
name = "HuggingFaceModel"
inputs = LCModelComponent._base_inputs + [
StrInput(
name="model_id",
display_name="Model ID",
value="openai-community/gpt2",
),
inputs = [
*LCModelComponent._base_inputs,
StrInput(name="model_id", display_name="Model ID", value="openai-community/gpt2"),
StrInput(
name="inference_endpoint",
display_name="Inference Endpoint",

View file

@ -12,7 +12,8 @@ class MaritalkModelComponent(LCModelComponent):
description = "Generates text using Maritalk LLMs."
icon = "Maritalk"
name = "Maritalk"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
IntInput(
name="max_tokens",
display_name="Max Tokens",

View file

@ -13,7 +13,8 @@ class MistralAIModelComponent(LCModelComponent):
icon = "MistralAI"
name = "MistralModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
IntInput(
name="max_tokens",
display_name="Max Tokens",
@ -38,10 +39,8 @@ class MistralAIModelComponent(LCModelComponent):
name="mistral_api_base",
display_name="Mistral API Base",
advanced=True,
info=(
"The base URL of the Mistral API. Defaults to https://api.mistral.ai/v1. "
"You can change this to use other APIs like JinaChat, LocalAI and Prem."
),
info="The base URL of the Mistral API. Defaults to https://api.mistral.ai/v1. "
"You can change this to use other APIs like JinaChat, LocalAI and Prem.",
),
SecretStrInput(
name="api_key",

View file

@ -12,7 +12,8 @@ class NVIDIAModelComponent(LCModelComponent):
description = "Generates text using NVIDIA LLMs."
icon = "NVIDIA"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
IntInput(
name="max_tokens",
display_name="Max Tokens",

View file

@ -69,7 +69,8 @@ class ChatOllamaComponent(LCModelComponent):
msg = "Could not retrieve models. Please, make sure Ollama is running."
raise ValueError(msg) from e
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
StrInput(
name="base_url",
display_name="Base URL",
@ -90,17 +91,9 @@ class ChatOllamaComponent(LCModelComponent):
info="Controls the creativity of model responses.",
),
StrInput(
name="format",
display_name="Format",
info="Specify the format of the output (e.g., json).",
advanced=True,
),
DictInput(
name="metadata",
display_name="Metadata",
info="Metadata to add to the run trace.",
advanced=True,
name="format", display_name="Format", info="Specify the format of the output (e.g., json).", advanced=True
),
DictInput(name="metadata", display_name="Metadata", info="Metadata to add to the run trace.", advanced=True),
DropdownInput(
name="mirostat",
display_name="Mirostat",
@ -152,35 +145,13 @@ class ChatOllamaComponent(LCModelComponent):
info="Penalty for repetitions in generated text. (Default: 1.1)",
advanced=True,
),
FloatInput(
name="tfs_z",
display_name="TFS Z",
info="Tail free sampling value. (Default: 1)",
advanced=True,
),
FloatInput(name="tfs_z", display_name="TFS Z", info="Tail free sampling value. (Default: 1)", advanced=True),
IntInput(name="timeout", display_name="Timeout", info="Timeout for the request stream.", advanced=True),
IntInput(
name="timeout",
display_name="Timeout",
info="Timeout for the request stream.",
advanced=True,
),
IntInput(
name="top_k",
display_name="Top K",
info="Limits token selection to top K. (Default: 40)",
advanced=True,
),
FloatInput(
name="top_p",
display_name="Top P",
info="Works together with top-k. (Default: 0.9)",
advanced=True,
),
BoolInput(
name="verbose",
display_name="Verbose",
info="Whether to print out response text.",
name="top_k", display_name="Top K", info="Limits token selection to top K. (Default: 40)", advanced=True
),
FloatInput(name="top_p", display_name="Top P", info="Works together with top-k. (Default: 0.9)", advanced=True),
BoolInput(name="verbose", display_name="Verbose", info="Whether to print out response text."),
StrInput(
name="tags",
display_name="Tags",
@ -193,18 +164,8 @@ class ChatOllamaComponent(LCModelComponent):
info="Comma-separated list of tokens to signal the model to stop generating text.",
advanced=True,
),
StrInput(
name="system",
display_name="System",
info="System to use for generating text.",
advanced=True,
),
StrInput(
name="template",
display_name="Template",
info="Template to use for generating text.",
advanced=True,
),
StrInput(name="system", display_name="System", info="System to use for generating text.", advanced=True),
StrInput(name="template", display_name="Template", info="Template to use for generating text.", advanced=True),
HandleInput(
name="output_parser",
display_name="Output Parser",

View file

@ -26,7 +26,8 @@ class OpenAIModelComponent(LCModelComponent):
icon = "OpenAI"
name = "OpenAIModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
IntInput(
name="max_tokens",
display_name="Max Tokens",

View file

@ -14,7 +14,8 @@ class PerplexityComponent(LCModelComponent):
icon = "Perplexity"
name = "PerplexityModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
DropdownInput(
name="model_name",
display_name="Model Name",
@ -31,9 +32,7 @@ class PerplexityComponent(LCModelComponent):
value="llama-3.1-sonar-small-128k-online",
),
IntInput(
name="max_output_tokens",
display_name="Max Output Tokens",
info="The maximum number of tokens to generate.",
name="max_output_tokens", display_name="Max Output Tokens", info="The maximum number of tokens to generate."
),
SecretStrInput(
name="api_key",

View file

@ -13,7 +13,8 @@ class ChatVertexAIComponent(LCModelComponent):
icon = "VertexAI"
name = "VertexAiModel"
inputs = LCModelComponent._base_inputs + [
inputs = [
*LCModelComponent._base_inputs,
FileInput(
name="credentials",
display_name="Credentials",

View file

@ -78,7 +78,7 @@ class JSONCleaner(Component):
self.status = result
return Message(text=result)
except Exception as e:
msg = f"Error cleaning JSON string: {str(e)}"
msg = f"Error cleaning JSON string: {e}"
raise ValueError(msg) from e
def _remove_control_characters(self, s: str) -> str:
@ -95,5 +95,5 @@ class JSONCleaner(Component):
json.loads(s)
return s
except json.JSONDecodeError as e:
msg = f"Invalid JSON string: {str(e)}"
msg = f"Invalid JSON string: {e}"
raise ValueError(msg) from e

View file

@ -55,7 +55,7 @@ class PythonFunctionComponent(Component):
func = get_function(function_code)
return func()
except Exception as e:
return f"Error executing function: {str(e)}"
return f"Error executing function: {e}"
def execute_function_data(self) -> list[Data]:
results = self.execute_function()

View file

@ -68,14 +68,14 @@ class RunnableExecComponent(Component):
result_value = result.get(output_key)
elif len(result) == 2 and input_key in result:
# get the other key from the result dict
other_key = [k for k in result if k != input_key][0]
other_key = next(k for k in result if k != input_key)
if other_key == output_key:
result_value = result.get(output_key)
else:
status += f"Warning: The output key is not '{output_key}'. The output key is '{other_key}'."
result_value = result.get(other_key)
elif len(result) == 1:
result_value = list(result.values())[0]
result_value = next(iter(result.values()))
elif any(k in result for k in possible_output_keys):
for key in possible_output_keys:
if key in result:

View file

@ -47,7 +47,7 @@ class SubFlowComponent(Component):
# Add inputs to the build config
build_config = self.add_inputs_to_build_config(inputs, build_config)
except Exception as e:
logger.error(f"Error getting flow {field_value}: {str(e)}")
logger.error(f"Error getting flow {field_value}: {e}")
return build_config

View file

@ -86,7 +86,7 @@ class ComposioAPIComponent(LCToolComponent):
return self._process_api_key_auth(entity, app)
return self._initiate_default_connection(entity, app)
except Exception as exc:
logger.error(f"Authorization error: {str(exc)}")
logger.error(f"Authorization error: {exc}")
return "Error"
def _process_api_key_auth(self, entity: Any, app: str) -> str:

View file

@ -69,7 +69,7 @@ class CalculatorToolComponent(LCToolComponent):
return [Data(data={"result": formatted_result})]
except (SyntaxError, TypeError, KeyError) as e:
error_message = f"Invalid expression: {str(e)}"
error_message = f"Invalid expression: {e}"
self.status = error_message
return [Data(data={"error": error_message})]
except ZeroDivisionError:
@ -77,6 +77,6 @@ class CalculatorToolComponent(LCToolComponent):
self.status = error_message
return [Data(data={"error": error_message})]
except Exception as e:
error_message = f"Error: {str(e)}"
error_message = f"Error: {e}"
self.status = error_message
return [Data(data={"error": error_message})]

View file

@ -120,7 +120,7 @@ class PythonCodeStructuredTool(LCToolComponent):
build_config["_classes"]["value"] = json.dumps(classes)
build_config["tool_function"]["options"] = names
except Exception as e:
self.status = f"Failed to extract names: {str(e)}"
self.status = f"Failed to extract names: {e}"
build_config["tool_function"]["options"] = ["Failed to parse", str(e)]
return build_config

View file

@ -74,7 +74,7 @@ class PythonREPLToolComponent(LCToolComponent):
try:
return python_repl.run(code)
except Exception as e:
return f"Error: {str(e)}"
return f"Error: {e}"
tool = StructuredTool.from_function(
name=self.name,

View file

@ -75,7 +75,7 @@ class SearXNGToolComponent(LCToolComponent):
languages.append(language)
build_config["language"]["options"] = languages.copy()
except Exception as e:
self.status = f"Failed to extract names: {str(e)}"
self.status = f"Failed to extract names: {e}"
build_config["categories"]["options"] = ["Failed to parse", str(e)]
return build_config
@ -113,7 +113,7 @@ class SearXNGToolComponent(LCToolComponent):
results.append(response["results"][i])
return results
except Exception as e:
return [f"Failed to search: {str(e)}"]
return [f"Failed to search: {e}"]
SearxSearch._url = self.url
SearxSearch._categories = self.categories.copy()

View file

@ -88,5 +88,5 @@ class SerpAPIComponent(LCToolComponent):
self.status = data_list
return data_list
except Exception as e:
self.status = f"Error: {str(e)}"
self.status = f"Error: {e}"
return [Data(data={"error": str(e)}, text=str(e))]

View file

@ -155,6 +155,6 @@ Note: Check 'Advanced' for all options.
self.status = error_message
return [Data(data={"error": error_message})]
except Exception as e:
error_message = f"Unexpected error: {str(e)}"
error_message = f"Unexpected error: {e}"
self.status = error_message
return [Data(data={"error": error_message})]

View file

@ -96,6 +96,6 @@ class YfinanceToolComponent(LCToolComponent):
return data_list
except Exception as e:
error_message = f"Error retrieving data: {str(e)}"
error_message = f"Error retrieving data: {e}"
self.status = error_message
return [Data(data={"error": error_message})]

View file

@ -427,7 +427,7 @@ class AstraVectorStoreComponent(LCVectorStoreComponent):
try:
vector_store = AstraDBVectorStore(**vector_store_kwargs)
except Exception as e:
msg = f"Error initializing AstraDBVectorStore: {str(e)}"
msg = f"Error initializing AstraDBVectorStore: {e}"
raise ValueError(msg) from e
self._add_documents_to_vector_store(vector_store)
@ -448,7 +448,7 @@ class AstraVectorStoreComponent(LCVectorStoreComponent):
try:
vector_store.add_documents(documents)
except Exception as e:
msg = f"Error adding documents to AstraDBVectorStore: {str(e)}"
msg = f"Error adding documents to AstraDBVectorStore: {e}"
raise ValueError(msg) from e
else:
logger.debug("No documents to add to the Vector Store.")
@ -487,7 +487,7 @@ class AstraVectorStoreComponent(LCVectorStoreComponent):
docs = vector_store.search(query=self.search_input, search_type=search_type, **search_args)
except Exception as e:
msg = f"Error performing search in AstraDBVectorStore: {str(e)}"
msg = f"Error performing search in AstraDBVectorStore: {e}"
raise ValueError(msg) from e
logger.debug(f"Retrieved documents: {len(docs)}")

View file

@ -225,7 +225,7 @@ class CassandraVectorStoreComponent(LCVectorStoreComponent):
search_type = self._map_search_type()
search_args = self._build_search_args()
logger.debug(f"Search args: {str(search_args)}")
logger.debug(f"Search args: {search_args}")
docs = vector_store.search(query=self.search_query, search_type=search_type, **search_args)
except KeyError as e:

View file

@ -204,7 +204,7 @@ class CassandraGraphVectorStoreComponent(LCVectorStoreComponent):
search_type = self._map_search_type()
search_args = self._build_search_args()
logger.debug(f"Search args: {str(search_args)}")
logger.debug(f"Search args: {search_args}")
docs = vector_store.search(query=self.search_query, search_type=search_type, **search_args)
except KeyError as e:

View file

@ -198,7 +198,7 @@ class ElasticsearchVectorStoreComponent(LCVectorStoreComponent):
msg = f"Invalid search type: {self.search_type}"
raise ValueError(msg)
except Exception as e:
logger.error(f"Search query failed: {str(e)}")
logger.error(f"Search query failed: {e}")
msg = (
"Error occurred while querying the Elasticsearch VectorStore,"
" there is no Data into the VectorStore."

View file

@ -247,7 +247,7 @@ class HCDVectorStoreComponent(LCVectorStoreComponent):
try:
vector_store = AstraDBVectorStore(**vector_store_kwargs)
except Exception as e:
msg = f"Error initializing AstraDBVectorStore: {str(e)}"
msg = f"Error initializing AstraDBVectorStore: {e}"
raise ValueError(msg) from e
self._add_documents_to_vector_store(vector_store)
@ -267,7 +267,7 @@ class HCDVectorStoreComponent(LCVectorStoreComponent):
try:
vector_store.add_documents(documents)
except Exception as e:
msg = f"Error adding documents to AstraDBVectorStore: {str(e)}"
msg = f"Error adding documents to AstraDBVectorStore: {e}"
raise ValueError(msg) from e
else:
logger.debug("No documents to add to the Vector Store.")
@ -305,7 +305,7 @@ class HCDVectorStoreComponent(LCVectorStoreComponent):
docs = vector_store.search(query=self.search_input, search_type=search_type, **search_args)
except Exception as e:
msg = f"Error performing search in AstraDBVectorStore: {str(e)}"
msg = f"Error performing search in AstraDBVectorStore: {e}"
raise ValueError(msg) from e
logger.debug(f"Retrieved documents: {len(docs)}")

View file

@ -124,7 +124,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
try:
from langchain_community.vectorstores import OpenSearchVectorSearch
except ImportError as e:
error_message = f"Failed to import required modules: {str(e)}"
error_message = f"Failed to import required modules: {e}"
logger.error(error_message)
raise ImportError(error_message) from e
@ -140,7 +140,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
ssl_show_warn=False,
)
except Exception as e:
error_message = f"Failed to create OpenSearchVectorSearch instance: {str(e)}"
error_message = f"Failed to create OpenSearchVectorSearch instance: {e}"
logger.error(error_message)
raise RuntimeError(error_message) from e
@ -167,7 +167,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
try:
vector_store.add_documents(documents)
except Exception as e:
error_message = f"Error adding documents to Vector Store: {str(e)}"
error_message = f"Error adding documents to Vector Store: {e}"
logger.error(error_message)
logger.error(f"Traceback: {traceback.format_exc()}")
raise RuntimeError(error_message) from e
@ -187,7 +187,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
try:
hybrid_query = json.loads(self.hybrid_search_query)
except json.JSONDecodeError as e:
error_message = f"Invalid hybrid search query JSON: {str(e)}"
error_message = f"Invalid hybrid search query JSON: {e}"
logger.error(error_message)
raise ValueError(error_message) from e
@ -236,7 +236,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
raise ValueError(error_message)
except Exception as e:
error_message = f"Error during search: {str(e)}"
error_message = f"Error during search: {e}"
logger.error(error_message)
logger.error(f"Traceback: {traceback.format_exc()}")
raise RuntimeError(error_message) from e
@ -259,7 +259,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
self.status = retrieved_data
return retrieved_data
except Exception as e:
error_message = f"Error during document search: {str(e)}"
error_message = f"Error during document search: {e}"
logger.error(error_message)
logger.error(f"Traceback: {traceback.format_exc()}")
raise RuntimeError(error_message) from e

View file

@ -217,7 +217,7 @@ class DirectoryReader:
file_content = self.read_file_content(file_path)
except Exception as exc:
logger.exception(exc)
logger.error(f"Error while reading file {file_path}: {str(exc)}")
logger.error(f"Error while reading file {file_path}: {exc}")
return False, f"Could not read {file_path}"
if file_content is None:
@ -294,7 +294,7 @@ class DirectoryReader:
file_content = self.read_file_content(file_path)
except Exception as exc:
logger.exception(exc)
logger.error(f"Error while reading file {file_path}: {str(exc)}")
logger.error(f"Error while reading file {file_path}: {exc}")
return False, f"Could not read {file_path}"
if file_content is None:
@ -347,7 +347,7 @@ class DirectoryReader:
try:
output_types = await self.get_output_types_from_code_async(result_content)
except Exception as exc:
logger.error(f"Error while getting output types from code: {str(exc)}")
logger.error(f"Error while getting output types from code: {exc}")
output_types = [component_name_camelcase]
else:
output_types = [component_name_camelcase]

View file

@ -133,7 +133,7 @@ def build_invalid_menu_items(menu_item):
menu_items[component_name] = component_template
logger.debug(f"Added {component_name} to invalid menu.")
except Exception as exc:
logger.exception(f"Error while creating custom component [{component_name}]: {str(exc)}")
logger.exception(f"Error while creating custom component [{component_name}]: {exc}")
return menu_items

View file

@ -273,7 +273,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI
msg = "Invalid code type"
raise ValueError(msg)
except Exception as exc:
logger.error(f"Error while evaluating custom component code: {str(exc)}")
logger.error(f"Error while evaluating custom component code: {exc}")
raise HTTPException(
status_code=400,
detail={
@ -285,7 +285,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI
try:
return custom_class(_user_id=user_id, _code=custom_component._code)
except Exception as exc:
logger.error(f"Error while instantiating custom component: {str(exc)}")
logger.error(f"Error while instantiating custom component: {exc}")
if hasattr(exc, "detail") and "traceback" in exc.detail:
logger.error(exc.detail["traceback"])
@ -308,7 +308,7 @@ def run_build_config(
msg = "Invalid code type"
raise ValueError(msg)
except Exception as exc:
logger.error(f"Error while evaluating custom component code: {str(exc)}")
logger.error(f"Error while evaluating custom component code: {exc}")
raise HTTPException(
status_code=400,
detail={
@ -333,7 +333,7 @@ def run_build_config(
return build_config, custom_instance
except Exception as exc:
logger.error(f"Error while building field config: {str(exc)}")
logger.error(f"Error while building field config: {exc}")
if hasattr(exc, "detail") and "traceback" in exc.detail:
logger.error(exc.detail["traceback"])
@ -423,7 +423,7 @@ def build_custom_component_template(
raise HTTPException(
status_code=400,
detail={
"error": (f"Error building Component: {str(exc)}"),
"error": (f"Error building Component: {exc}"),
"traceback": traceback.format_exc(),
},
) from exc
@ -521,8 +521,8 @@ def update_field_dict(
)
build_config = dd_build_config
except Exception as exc:
logger.error(f"Error while running update_build_config: {str(exc)}")
msg = f"Error while running update_build_config: {str(exc)}"
logger.error(f"Error while running update_build_config: {exc}")
msg = f"Error while running update_build_config: {exc}"
raise UpdateBuildConfigError(msg) from exc
return build_config

View file

@ -452,7 +452,7 @@ class Graph:
# and run self.build_adjacency_maps(edges) to get the new predecessor map
# that is not complete but we can use to update the run_predecessors
edges_set = set()
for _vertex in [vertex] + successors:
for _vertex in [vertex, *successors]:
edges_set.update(_vertex.edges)
if _vertex.state == VertexStates.INACTIVE:
_vertex.set_state("ACTIVE")
@ -1013,7 +1013,7 @@ class Graph:
Creates a graph from a payload.
Args:
payload (Dict): The payload to create the graph from.˜`
payload (Dict): The payload to create the graph from.`
Returns:
Graph: The created graph.
@ -1617,7 +1617,7 @@ class Graph:
successors_result.append([successor])
if not flat and successors_result:
return [successors] + successors_result
return [successors, *successors_result]
return successors_result
@ -1893,7 +1893,7 @@ class Graph:
if not chat_inputs_first:
return vertices_layers
return [chat_inputs_first] + vertices_layers
return [chat_inputs_first, *vertices_layers]
def sort_layer_by_dependency(self, vertices_layers: list[list[str]]) -> list[list[str]]:
"""Sorts the vertices in each layer by dependency, ensuring no vertex depends on a subsequent vertex."""

View file

@ -682,7 +682,7 @@ class Vertex:
logger.exception(e)
msg = (
f"Params {key} ({self.params[key]}) is not a list and cannot be extended with {result}"
f"Error building Component {self.display_name}: \n\n{str(e)}"
f"Error building Component {self.display_name}: \n\n{e}"
)
raise ValueError(msg) from e

View file

@ -161,7 +161,7 @@ def update_new_output(data):
new_source_handle["output_types"] = new_source_handle["baseClasses"]
del new_source_handle["baseClasses"]
if "inputTypes" in new_target_handle and new_target_handle["inputTypes"]:
if new_target_handle.get("inputTypes"):
intersection = [
type_ for type_ in new_source_handle["output_types"] if type_ in new_target_handle["inputTypes"]
]

View file

@ -24,17 +24,17 @@ def update_memory_keys(langchain_object, possible_new_mem_key):
object's memory attribute to exclude the current memory key and the possible new key. It then sets the memory key
to the possible new key.
"""
input_key = [
input_key = next(
key
for key in langchain_object.input_keys
if key not in [langchain_object.memory.memory_key, possible_new_mem_key]
][0]
)
output_key = [
output_key = next(
key
for key in langchain_object.output_keys
if key not in [langchain_object.memory.memory_key, possible_new_mem_key]
][0]
)
for key, attr in [(input_key, "input_key"), (output_key, "output_key"), (possible_new_mem_key, "memory_key")]:
try:

View file

@ -1,3 +1,5 @@
from __future__ import annotations
import asyncio
import json
from collections.abc import AsyncIterator, Iterator
@ -119,7 +121,7 @@ class Message(Data):
return AIMessage(content=text) # type: ignore
@classmethod
def from_lc_message(cls, lc_message: BaseMessage) -> "Message":
def from_lc_message(cls, lc_message: BaseMessage) -> Message:
if lc_message.type == "human":
sender = MESSAGE_SENDER_USER
sender_name = MESSAGE_SENDER_NAME_USER
@ -136,7 +138,7 @@ class Message(Data):
return cls(text=lc_message.content, sender=sender, sender_name=sender_name)
@classmethod
def from_data(cls, data: "Data") -> "Message":
def from_data(cls, data: Data) -> Message:
"""
Converts a BaseMessage to a Data.
@ -231,7 +233,7 @@ class Message(Data):
content_dicts = await value.get_file_content_dicts()
contents.extend(content_dicts)
if contents:
message = HumanMessage(content=[{"type": "text", "text": text}] + contents)
message = HumanMessage(content=[{"type": "text", "text": text}, *contents])
prompt_template = ChatPromptTemplate.from_messages([message]) # type: ignore

View file

@ -16,7 +16,7 @@ from sqlalchemy.exc import OperationalError
from sqlmodel import Session, SQLModel, create_engine, select, text
from langflow.services.base import Service
from langflow.services.database import models # noqa
from langflow.services.database import models
from langflow.services.database.models.user.crud import get_user_by_username
from langflow.services.database.utils import (
Result,
@ -87,7 +87,7 @@ class DatabaseService(Service):
pragmas_list = []
for key, val in pragmas.items() or {}:
pragmas_list.append(f"PRAGMA {key} = {val}")
logger.info(f"sqlite connection, setting pragmas: {str(pragmas_list)}")
logger.info(f"sqlite connection, setting pragmas: {pragmas_list}")
if pragmas_list:
cursor = dbapi_connection.cursor()
try:

View file

@ -1,6 +1,6 @@
from collections.abc import Callable # noqa: I001
from enum import Enum
from typing import Any # noqa
from typing import Any
from typing import GenericAlias # type: ignore
from typing import _GenericAlias # type: ignore
from typing import _UnionGenericAlias # type: ignore

View file

@ -41,7 +41,7 @@ def update_template_field(new_template, key, previous_value_dict):
template_field["load_from_db"] = previous_value_dict.get("load_from_db", False)
template_field["value"] = previous_value_dict["value"]
if "file_path" in previous_value_dict and previous_value_dict["file_path"]:
if previous_value_dict.get("file_path"):
file_path_value = get_file_path_value(previous_value_dict["file_path"])
if not file_path_value:
# If the file does not exist, remove the value from the template_field["value"]

View file

@ -155,7 +155,7 @@ def get_base_classes(cls):
result = [cls.__name__]
if not result:
result = [cls.__name__]
return list(set(result + [cls.__name__]))
return list({*result, cls.__name__})
def get_default_factory(module: str, function: str):

View file

@ -190,6 +190,7 @@ select = [
"Q",
"RET",
"RSE",
"RUF",
"SIM",
"SLOT",
"T10",
@ -202,6 +203,8 @@ select = [
ignore = [
"COM812", # Messes with the formatter
"ISC001", # Messes with the formatter
"RUF006", # TODO (Store a reference to the return value of `asyncio.create_task`)
"RUF012", # TODO (Mutable class attributes should be annotated with `typing.ClassVar`)
]
[tool.ruff.lint.per-file-ignores]