Langflow components allow to itterate actions on long data list using an llm, one data point at a time.
I am using prompt structure to instruct the llm what actions to take on the incoming data point.
Langflow uses curly brackets for creating variables, when prompting and templating prompts. so for example, if I want to add tags to each data point, I provide context variable {context} with constant context, and I provide constant list of tags in variable {tags} to choose from.
However, the component I am using to iterate over the data list, does't not provide a way to identify additional text input variables.
for example I would like to add another variable as context {context}.
for example I would like to add another variable as tags {tags}.
Please review the current code, and add an inputs, when I add variable in the prompt using curly brackets {}, where I can easily attach text input, or write an input.
Provided is a code that need to be fixed, and a referance document
The following is a prompt component, that add inputs based on variables, defined with curly brackets within the prompt.
code
Assistant
from langflow.base.prompts.api_utils import process_prompt_template
from langflow.custom import Component
from langflow.inputs.inputs import DefaultPromptField
from langflow.io import Output, PromptInput
from langflow.schema.message import Message
from langflow.template.utils import update_template_values
class PromptComponent(Component):
display_name: str = "Prompt"
description: str = "Create a prompt template with dynamic variables."
icon = "prompts"
trace_type = "prompt"
name = "Prompt"
inputs = [
PromptInput(name="template", display_name="Template"),
]
outputs = [
Output(display_name="Prompt Message", name="prompt", method="build_prompt"),
]
async def build_prompt(self) -> Message:
prompt = Message.from_template(**self._attributes)
self.status = prompt.text
return prompt
def _update_template(self, frontend_node: dict):
prompt_template = frontend_node["template"]["template"]["value"]
custom_fields = frontend_node["custom_fields"]
frontend_node_template = frontend_node["template"]
_ = process_prompt_template(
template=prompt_template,
name="template",
custom_fields=custom_fields,
frontend_node_template=frontend_node_template,
)
return frontend_node
def post_code_processing(self, new_frontend_node: dict, current_frontend_node: dict):
"""This function is called after the code validation is done."""
frontend_node = super().post_code_processing(new_frontend_node, current_frontend_node)
template = frontend_node["template"]["template"]["value"]
# Kept it duplicated for backwards compatibility
_ = process_prompt_template(
template=template,
name="template",
custom_fields=frontend_node["custom_fields"],
frontend_node_template=frontend_node["template"],
)
# Now that template is updated, we need to grab any values that were set in the current_frontend_node
# and update the frontend_node with those values
update_template_values(new_template=frontend_node, previous_template=current_frontend_node["template"])
return frontend_node
def _get_fallback_input(self, **kwargs):
return DefaultPromptField(**kwargs)
Issue:
no intuitive way to add a variable input for the prompt,
Request:
think how to, and add text input when I define them in the prompt using curly brackets.
code to be fixed:
code
import csv
import os
from typing import List
from loguru import logger
import json
from langflow.custom import Component
from langflow.helpers.data import data_to_text
from langflow.io import (
MessageTextInput,
IntInput,
DataInput,
Output,
MultilineInput,
HandleInput,
StrInput,
)
from langflow.schema import Data
from langflow.schema.message import Message
class DynamicLLMDataIteratorComponent(Component):
display_name = "Dynamic LLM Data Iterator"
description = (
"Iterate over a list of data, process each item using a specified LLM with a dynamically constructed prompt, "
"store the result, and optionally save the results to a CSV file.\n\n"
"You can use the Data Variable Name to reference the current data point in your prompt template."
)
icon = "🔁"
base_type = "component"
inputs = [
DataInput(name="data_list", display_name="Data List", info="The list of data to iterate over.", is_list=True),
IntInput(name="start_index", display_name="Start Index", info="The index to start processing from.", value=0),
IntInput(name="iteration_count", display_name="Iteration Count", info="Number of items to process. Set to 0 to process all remaining items.", value=0),
StrInput(
name="data_variable",
display_name="Data Variable Name",
info="The variable name to use for referencing the current data point in the prompt template. Example: If set to 'data', use {data} in your prompt.",
value="data",
),
MultilineInput(
name="prompt_template",
display_name="Prompt Template",
info="The prompt template to use for each item. Use {data} to refer to the entire current data point, or {key} to refer to specific values.",
value="Process this data point: {data}",
),
MessageTextInput(name="output_key", display_name="Output Key", info="The key to store the LLM output in the data."),
HandleInput(
name="llm",
display_name="LLM",
input_types=["LanguageModel"],
info="The language model to use for processing.",
),
MessageTextInput(
name="file_path",
display_name="CSV File Path",
info="The path to save the CSV file. If not provided, no CSV will be saved.",
advanced=True,
),
]
outputs = [
Output(display_name="Processed Data", name="processed_data", method="process_data"),
]
def format_data_for_prompt(self, data: dict) -> str:
"""Format the data dictionary in a clear, readable way for the LLM."""
try:
# If the data is a simple string or number, return it directly
if isinstance(data, (str, int, float)):
return str(data)
# For dictionaries and other complex types, format them clearly
formatted_items = []
for key, value in data.items():
if isinstance(value, dict):
# For nested dictionaries, convert to JSON string with indentation
formatted_value = json.dumps(value, indent=2)
else:
formatted_value = str(value)
formatted_items.append(f"{key}: {formatted_value}")
return "\n".join(formatted_items)
except Exception as e:
logger.error(f"Error formatting data: {str(e)}")
return str(data)
def append_to_csv(self, file_path: str, data: dict):
file_exists = os.path.isfile(file_path)
with open(file_path, 'a', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=data.keys())
if not file_exists:
writer.writeheader()
writer.writerow(data)
def construct_prompt(self, template: str, data: dict, data_variable: str) -> str:
# Create a context dictionary with both the entire data point and individual fields
context = data.copy()
# Format the entire data point in a clear, structured way
formatted_data = self.format_data_for_prompt(data)
context[data_variable] = formatted_data
try:
return template.format(**context)
except KeyError as e:
logger.error(f"Error in prompt template: Missing key {str(e)}")
# Fallback to basic template if there's an error
return f"Process this data:\n{formatted_data}"
except Exception as e:
logger.error(f"Error constructing prompt: {str(e)}")
return f"Process this data:\n{formatted_data}"
def process_data(self) -> List[Data]:
logger.info("Starting data processing")
data_list: List[Data] = self.data_list
start_index: int = max(0, self.start_index)
iteration_count: int = self.iteration_count
prompt_template: str = self.prompt_template
output_key: str = self.output_key
file_path: str = self.file_path
data_variable: str = self.data_variable
logger.debug(f"Number of data items: {len(data_list)}")
logger.debug(f"Start index: {start_index}")
logger.debug(f"Iteration count: {iteration_count}")
logger.debug(f"Prompt template: {prompt_template}")
logger.debug(f"Output key: {output_key}")
logger.debug(f"CSV file path: {file_path}")
logger.debug(f"Data variable name: {data_variable}")
llm = self.llm
if iteration_count <= 0 or (start_index + iteration_count) > len(data_list):
iteration_count = len(data_list) - start_index
end_index = start_index + iteration_count
logger.info(f"Will process items from index {start_index} to {end_index - 1}")
processed_data = []
for index, item in enumerate(data_list[start_index:end_index], start=start_index):
logger.debug(f"Processing item {index}/{end_index - 1}")
if not isinstance(item.data, dict):
logger.error(f"Data item {index} is not a dictionary")
raise ValueError(f"Data item {index} is not a dictionary")
# Log the raw data for debugging
logger.debug(f"Raw data for item {index}: {item.data}")
prompt = self.construct_prompt(prompt_template, item.data, data_variable)
logger.debug(f"Generated prompt: {prompt}")
try:
logger.debug("Invoking LLM")
llm_output = llm.invoke(prompt).content
logger.debug(f"LLM output: {llm_output}")
new_item = item.data.copy()
new_item[output_key] = llm_output
processed_data.append(Data(data=new_item))
logger.info(f"Successfully processed item {index}")
if file_path:
self.append_to_csv(file_path, new_item)
logger.info(f"Appended item {index} to CSV")
except Exception as e:
logger.error(f"Error processing item {index}: {str(e)}")
self.status = f"Error processing item {index}: {str(e)}"
return processed_data
self.status = processed_data
logger.info(f"Finished processing. {len(processed_data)} items processed successfully.")
return processed_data
To inject dynamic variables from curly-bracket notations (like {variable}) into your prompt template in a more intuitive way, you can enhance the DynamicLLMDataIteratorComponent by dynamically adding inputs based on detected variables in the prompt_template. This will allow you to easily define variable inputs in the prompt template and bind specific text inputs to those variables.
Here's a modified version of your DynamicLLMDataIteratorComponent that automatically detects variables in the prompt_template and adds corresponding inputs for them:
python
import re
from langflow.custom import Component
from langflow.helpers.data import data_to_text
from langflow.io import (
MessageTextInput,
IntInput,
DataInput,
Output,
MultilineInput,
HandleInput,
StrInput,
)
from langflow.schema import Data
from langflow.schema.message import Message
class DynamicLLMDataIteratorComponent(Component):
display_name = "Dynamic LLM Data Iterator"
description = (
"Iterate over a list of data, process each item using a specified LLM with a dynamically constructed prompt, "
"store the result, and optionally save the results to a CSV file.\n\n"
"You can use the Data Variable Name to reference the current data point in your prompt template."
)
icon = "🔁"
base_type = "component"
inputs = [
DataInput(name="data_list", display_name="Data List", info="The list of data to iterate over.", is_list=True),
IntInput(name="start_index", display_name="Start Index", info="The index to start processing from.", value=0),
IntInput(name="iteration_count", display_name="Iteration Count", info="Number of items to process. Set to 0 to process all remaining items.", value=0),
StrInput(
name="data_variable",
display_name="Data Variable Name",
info="The variable name to use for referencing the current data point in the prompt template. Example: If set to 'data', use {data} in your prompt.",
value="data",
),
MultilineInput(
name="prompt_template",
display_name="Prompt Template",
info="The prompt template to use for each item. Use {data} to refer to the entire current data point, or {key} to refer to specific values.",
value="Process this data point: {data}",
),
MessageTextInput(name="output_key", display_name="Output Key", info="The key to store the LLM output in the data."),
HandleInput(
name="llm",
display_name="LLM",
input_types=["LanguageModel"],
info="The language model to use for processing.",
),
MessageTextInput(
name="file_path",
display_name="CSV File Path",
info="The path to save the CSV file. If not provided, no CSV will be saved.",
advanced=True,
),
]
outputs = [
Output(display_name="Processed Data", name="processed_data", method="process_data"),
]
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._dynamic_inputs = {}
self._update_dynamic_inputs()
def _update_dynamic_inputs(self):
prompt_template = self.prompt_template
variable_pattern = r'{(\w+)}'
found_variables = set(re.findall(variable_pattern, prompt_template))
# Remove the existing dynamic inputs
for input_name in self._dynamic_inputs.keys():
self.inputs = [i for i in self.inputs if i.name != input_name]
self._dynamic_inputs.clear()
# Add new dynamic inputs based on the detected variables
for var in found_variables:
if var not in self._static_input_names():
new_input = StrInput(name=var, display_name=f"Variable: {var}", info=f"Input for variable {var}.")
self.inputs.append(new_input)
self._dynamic_inputs[var] = new_input
def _static_input_names(self):
return {input.name for input in self.inputs if not isinstance(input, StrInput)}
def append_to_csv(self, file_path: str, data: dict):
file_exists = os.path.isfile(file_path)
with open(file_path, 'a', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=data.keys())
if not file_exists:
writer.writeheader()
writer.writerow(data)
def construct_prompt(self, template: str, data: dict, data_variable: str) -> str:
# Create a context dictionary with both the entire data point and individual fields
context = data.copy()
context.update({k: self.__dict__[k] for k in self._dynamic_inputs.keys()})
formatted_data = self.format_data_for_prompt(data)
context[data_variable] = formatted_data
try:
return template.format(**context)
except KeyError as e:
logger.error(f"Error in prompt template: Missing key {str(e)}")
return f"Process this data:\n{formatted_data}"
except Exception as e:
logger.error(f"Error constructing prompt: {str(e)}")
return f"Process this data:\n{formatted_data}"
def process_data(self) -> List[Data]:
self._update_dynamic_inputs()
logger.info("Starting data processing")
data_list: List[Data] = self.data_list
start_index: int = max(0, self.start_index)
iteration_count: int = self.iteration_count
prompt_template: str = self.prompt_template
output_key: str = self.output_key
file_path: str = self.file_path
data_variable: str = self.data_variable
logger.debug(f"Number of data items: {len(data_list)}")
logger.debug(f"Start index: {start_index}")
logger.debug(f"Iteration count: {iteration_count}")
logger.debug(f"Prompt template: {prompt_template}")
logger.debug(f"Output key: {output_key}")
logger.debug(f"CSV file path: {file_path}")
logger.debug(f"Data variable name: {data_variable}")
llm = self.llm
if iteration_count <= 0 or (start_index + iteration_count) > len(data_list):
iteration_count = len(data_list) - start_index
end_index = start_index + iteration_count
logger.info(f"Will process items from index {start_index} to {end_index - 1}")
processed_data = []
for index, item in enumerate(data_list[start_index:end_index], start=start_index):
logger.debug(f"Processing item {index}/{end_index - 1}")
if not isinstance(item.data, dict):
logger.error(f"Data item {index} is not a dictionary")
raise ValueError(f"Data item {index} is not a dictionary")
logger.debug(f"Raw data for item {index}: {item.data}")
prompt = self.construct_prompt(prompt_template, item.data, data_variable)
logger.debug(f"Generated prompt: {prompt}")
try:
logger.debug("Invoking LLM")
llm_output = llm.invoke(prompt).content
logger.debug(f"LLM output: {llm_output}")
new_item = item.data.copy()
new_item[output_key] = llm_output
processed_data.append(Data(data=new_item))
logger.info(f"Successfully processed item {index}")
if file_path:
self.append_to_csv(file_path, new_item)
logger.info(f"Appended item {index} to CSV")
except Exception as e:
logger.error(f"Error processing item {index}: {str(e)}")
self.status = f"Error processing item {index}: {str(e)}"
return processed_data
self.status = processed_data
logger.info(f"Finished processing. {len(processed_data)} items processed successfully.")
return processed_data
Explanation:
Dynamic Input Detection: The _update_dynamic_inputs method scans the prompt_template for variables denoted by curly brackets and creates corresponding StrInput fields dynamically. These fields become available inputs for the component.
Dynamic Input Integration: When constructing the prompt, the component checks the dynamic inputs stored in self._dynamic_inputs and merges them with the current data point's context.
Automatic Input Updates: Upon initialization and during data processing, the component updates its inputs to ensure all variable references in the prompt template have corresponding input fields.
This approach should provide a more intuitive way to specify additional text inputs as variables directly within the prompt and allows for easy modification of your data processing workflow.