custom-components.mdx
  1  ---
  2  title: "Creating Custom Components"
  3  id: custom-components
  4  slug: "/custom-components"
  5  description: "Create your own components and use them standalone or in pipelines."
  6  ---
  7  
  8  # Creating Custom Components
  9  
 10  Create your own components and use them standalone or in pipelines.
 11  
 12  With Haystack, you can easily create any custom components for various tasks, from filtering results to integrating with external software. You can then insert, reuse, and share these components within Haystack or even with an external audience by packaging them and submitting them to [Haystack Integrations](../integrations.mdx)!
 13  
 14  ## Requirements
 15  
 16  Here are the requirements for all custom components:
 17  
 18  - `@component`: This decorator marks a class as a component, allowing it to be used in a pipeline.
 19  - `run()`: This is a required method in every component. It accepts input arguments and returns a `dict`. The inputs can either come from the pipeline when it’s executed, or from the output of another component when connected using `connect()`. The `run()` method should be compatible with the input/output definitions declared for the component. See an [Extended Example](#extended-example) below to check how it works.
 20  
 21  ### Inputs and Outputs
 22  
 23  Next, define the inputs and outputs for your component.
 24  
 25  #### Inputs
 26  
 27  You can choose between three input options:
 28  
 29  - `set_input_type`: This method defines or updates a single input socket for a component instance. It’s ideal for adding or modifying a specific input at runtime without affecting others. Use this when you need to dynamically set or modify a single input based on specific conditions.
 30  - `set_input_types`: This method allows you to define multiple input sockets at once, replacing any existing inputs. It’s useful when you know all the inputs the component will need and want to configure them in bulk. Use this when you want to define multiple inputs during initialization.
 31  - Declaring arguments directly in the `run()` method. Use this method when the component’s inputs are static and known at the time of class definition.
 32  
 33  #### Outputs
 34  
 35  You can choose between two output options:
 36  
 37  - `@component.output_types`: This decorator defines the output types and names at the time of class definition. The output names and types must match the `dict` returned by the `run()` method. Use this when the output types are static and known in advance. This decorator is cleaner and more readable for static components.
 38  - `set_output_types`: This method defines or updates multiple output sockets for a component instance at runtime. It’s useful when you need flexibility in configuring outputs dynamically. Use this when the output types need to be set at runtime for greater flexibility.
 39  
 40  ## Short Example
 41  
 42  Here is an example of a simple minimal component setup:
 43  
 44  ```python
 45  from haystack import component
 46  
 47  
 48  @component
 49  class WelcomeTextGenerator:
 50      """
 51      A component generating personal welcome message and making it upper case
 52      """
 53  
 54      @component.output_types(welcome_text=str, note=str)
 55      def run(self, name: str):
 56          return {
 57              "welcome_text": f"Hello {name}, welcome to Haystack!".upper(),
 58              "note": "welcome message is ready",
 59          }
 60  ```
 61  
 62  Here, the custom component `WelcomeTextGenerator` accepts one input: `name` string and returns two outputs: `welcome_text` and `note`.
 63  
 64  ## Extended Example
 65  
 66  Check out an example below on how to create two custom components and connect them in a Haystack pipeline.
 67  
 68  ```python
 69  # import necessary dependencies
 70  from typing import List
 71  from haystack import component, Pipeline
 72  
 73  
 74  # Create two custom components. Note the mandatory @component decorator and @component.output_types, as well as the mandatory run method.
 75  @component
 76  class WelcomeTextGenerator:
 77      """
 78      A component generating personal welcome message and making it upper case
 79      """
 80  
 81      @component.output_types(welcome_text=str, note=str)
 82      def run(self, name: str):
 83          return {
 84              "welcome_text": (
 85                  "Hello {name}, welcome to Haystack!".format(name=name)
 86              ).upper(),
 87              "note": "welcome message is ready",
 88          }
 89  
 90  
 91  @component
 92  class WhitespaceSplitter:
 93      """
 94      A component for splitting the text by whitespace
 95      """
 96  
 97      @component.output_types(split_text=List[str])
 98      def run(self, text: str):
 99          return {"split_text": text.split()}
100  
101  
102  # create a pipeline and add the custom components to it
103  text_pipeline = Pipeline()
104  text_pipeline.add_component(
105      name="welcome_text_generator",
106      instance=WelcomeTextGenerator(),
107  )
108  text_pipeline.add_component(name="splitter", instance=WhitespaceSplitter())
109  
110  # connect the components
111  text_pipeline.connect(
112      sender="welcome_text_generator.welcome_text",
113      receiver="splitter.text",
114  )
115  
116  # define the result and run the pipeline
117  result = text_pipeline.run({"welcome_text_generator": {"name": "Bilge"}})
118  
119  print(result["splitter"]["split_text"])
120  ```
121  
122  ## Extending the Existing Components
123  
124  To extend already existing components in Haystack, subclass an existing component and use the `@component` decorator to mark it. Override or extend the `run()` method to process inputs and outputs. Call `super()` with the derived class name from the init of the derived class to avoid initialization issues:
125  
126  ```python
127  class DerivedComponent(BaseComponent):
128      def __init__(self):
129          super(DerivedComponent, self).__init__()
130  
131  
132  ## ...
133  
134  dc = DerivedComponent()  # ok
135  ```
136  
137  An example of an extended component is Haystack's [FaithfulnessEvaluator](https://github.com/deepset-ai/haystack/blob/e5a80722c22c59eb99416bf0cd712f6de7cd581a/haystack/components/evaluators/faithfulness.py) derived from LLMEvaluator.
138  
139  ## Additional References
140  
141  🧑‍🍳 Cookbooks:
142  
143  - [Build quizzes and adventures with Character Codex and llamafile](https://haystack.deepset.ai/cookbook/charactercodex_llamafile/)
144  - [Run tasks concurrently within a custom component](https://haystack.deepset.ai/cookbook/concurrent_tasks/)
145  - [Chat With Your SQL Database](https://haystack.deepset.ai/cookbook/chat_with_sql_3_ways/)
146  - [Hacker News Summaries with Custom Components](https://haystack.deepset.ai/cookbook/hackernews-custom-component-rag/)