Skip to main content

Add a Code Component

Use the Code component to execute your own Python code in a pipeline. Code is a fast an easy way to add custom code that you don't need to share with the rest of the organization.


About This Task

Use the Code component if:

  • Your code is specific to a single pipeline and isn't reusable by other pipelines.
  • You want a fast and easy way to add custom code to a pipeline.

Otherwise, consider creating a custom component. For more information, see Custom Components.

Component's Structure

Each component is a Python class with the following required elements:

  • The from haystack import component import statement.
  • The @component decorator to indicate you're creating a component.
  • The run() method that defines what the component does.
    • The run() method must have the @component.output_types decorator to define the type of data the component outputs and the name of the outputting edge. The names and types you define as output types must match the keys and value types of the dictionary object the run() method returns. For details, see Examples below.
    • You can specify the input parameters for the run() method.
    • The run() method must return a dictionary with the keys and values you specify.

Restrictions

The init() method must not have any parameters.

Prerequisites

Add a Code Component

  1. Go to Pipelines and find the pipeline you want to add the Code component to.
  2. Click More actions next to the pipeline and choose Edit.
  3. In Component Library, find the Code component and drag it onto the canvas.
  4. Click the component card and type your code in the code parameter. Use the example as a starting point. Make sure your code has the @component decorator and the run() method. Define its inputs and outputs so that they match the inputs and outputs of the components it's connected to.
Example

This is an example of a Code component that counts words in a text. The component takes a string as input and returns the number of words in the string and the original string.

@component
class WordCounter:
"""
A component that counts words in a text.
"""

@component.output_types(count=int, original_text=str)
def run(self, text: str):
return {
"count": len(text.split()),
"original_text": text
}
  1. Run the component to test it:
    1. On the component card, click Run.
    2. Enter the component inputs and click Run Component. You should see the component's outputs in the Results panel.
  2. Connect the component to the components it needs to work with.
  3. Save your pipeline.