fstring.py
1 # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> 2 # 3 # SPDX-License-Identifier: Apache-2.0 4 5 from typing import Any 6 7 from haystack.core.component import component 8 9 10 @component 11 class FString: 12 """ 13 Takes a template string and a list of variables in input and returns the formatted string in output. 14 """ 15 16 def __init__(self, template: str, variables: list[str] | None = None) -> None: 17 self.template = template 18 self.variables = variables or [] 19 if "template" in self.variables: 20 raise ValueError("The variable name 'template' is reserved and cannot be used.") 21 component.set_input_types(self, **dict.fromkeys(self.variables, Any)) 22 23 @component.output_types(string=str) 24 def run(self, template: str | None = None, **kwargs): 25 """ 26 Takes a template string and a list of variables in input and returns the formatted string in output. 27 28 If the template is not given, the component will use the one given at initialization. 29 """ 30 if not template: 31 template = self.template 32 return {"string": template.format(**kwargs)}