Creating Custom Components (original) (raw)

Create your own components and use them standalone or in pipelines.

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!

Here are the requirements for all custom components:

Next, define the inputs and outputs for your component.

You can choose between three input options:

You can choose between two output options:

Here is an example of a simple minimal component setup:

from haystack import component

@component
class WelcomeTextGenerator:
  """
  A component generating personal welcome message and making it upper case
  """
  @component.output_types(welcome_text=str, note=str)
  def run(self, name:str):
    return {"welcome_text": f'Hello {name}, welcome to Haystack!'.upper(), "note": "welcome message is ready"}

Here, the custom component WelcomeTextGenerator accepts one input: name string and returns two outputs: welcome_text and note.

Click on the Recipe below to see how to create two custom components and connect them in a Haystack pipeline.

🔨

Custom Components in a Pipeline

Open Recipe

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:

class DerivedComponent(BaseComponent):
    def __init__(self):
        super(DerivedComponent, self).__init__()

# ...

dc = DerivedComponent()  # ok

An example of an extended component is Haystack's FaithfulnessEvaluator derived from LLMEvaluator.

🧑‍🍳 Cookbooks:

Updated about 2 months ago