/ haystack / components / joiners / string_joiner.py
string_joiner.py
 1  # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
 2  #
 3  # SPDX-License-Identifier: Apache-2.0
 4  
 5  
 6  from haystack import component
 7  from haystack.core.component.types import Variadic
 8  
 9  
10  @component
11  class StringJoiner:
12      """
13      Component to join strings from different components to a list of strings.
14  
15      ### Usage example
16  
17      ```python
18      from haystack.components.joiners import StringJoiner
19      from haystack.components.builders import PromptBuilder
20      from haystack.core.pipeline import Pipeline
21  
22      from haystack.components.generators.chat import OpenAIChatGenerator
23      from haystack.dataclasses import ChatMessage
24  
25      string_1 = "What's Natural Language Processing?"
26      string_2 = "What is life?"
27  
28      pipeline = Pipeline()
29      pipeline.add_component("prompt_builder_1", PromptBuilder("Builder 1: {{query}}"))
30      pipeline.add_component("prompt_builder_2", PromptBuilder("Builder 2: {{query}}"))
31      pipeline.add_component("string_joiner", StringJoiner())
32  
33      pipeline.connect("prompt_builder_1.prompt", "string_joiner.strings")
34      pipeline.connect("prompt_builder_2.prompt", "string_joiner.strings")
35  
36      print(pipeline.run(data={"prompt_builder_1": {"query": string_1}, "prompt_builder_2": {"query": string_2}}))
37  
38      # >> {"string_joiner": {"strings": ["Builder 1: What's Natural Language Processing?", "Builder 2: What is life?"]}}
39      ```
40      """
41  
42      @component.output_types(strings=list[str])
43      def run(self, strings: Variadic[str]) -> dict[str, list[str]]:
44          """
45          Joins strings into a list of strings
46  
47          :param strings:
48              strings from different components
49  
50          :returns:
51              A dictionary with the following keys:
52              - `strings`: Merged list of strings
53          """
54  
55          out_strings = list(strings)
56          return {"strings": out_strings}