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 componentimport statement. - The
@componentdecorator to indicate you're creating a component. - The
run()method that defines what the component does.- The
run()method must have the@component.output_typesdecorator 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 therun()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.
- The
Restrictions
The init() method must not have any parameters.
Prerequisites
- An understanding of components and their structure. For more information, see:
- You can also check the Code component documentation.
Add a Code Component
- Go to Pipelines and find the pipeline you want to add the
Codecomponent to. - Click More actions next to the pipeline and choose Edit.
- In Component Library, find the
Codecomponent and drag it onto the canvas. - Click the component card and type your code in the
codeparameter. Use the example as a starting point. Make sure your code has the@componentdecorator and therun()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
}
- Run the component to test it:
- On the component card, click Run.
- Enter the component inputs and click Run Component. You should see the component's outputs in the Results panel.
- Connect the component to the components it needs to work with.
- Save your pipeline.
Was this page helpful?