Passing Data between Components
There are two ways of passing data between components: through ports and by utilizing the Xircuits context (ctx). The guide below will walk you through a simple example using ports.
Passing Data via Ports
Passing data via ports is as simple as declaring the port variable as InArg
or OutArg
, which will then be rendered by the Xircuits canvas.
Start with a simple component definition that prints Hello.
Code Snippet
from xai_components.base import InArg, OutArg, InCompArg, Component, xai_component
@xai_component(color="red")
class HelloOutComponent(Component):
def execute(self, ctx) -> None:
username = "Xircuits"
print("Hello " + username + " from HelloOutComponent!")
Video
Declare an
outPort
with typeOutArg
that passes a string. Pass the data to the next components, explicitly set the port value in theexecute()
method, shown in#(2)
.Code Snippet
from xai_components.base import InArg, OutArg, InCompArg, Component, xai_component
@xai_component(color="red")
class HelloOutComponent(Component):
outport_example: OutArg[str] #(1)
def execute(self, ctx) -> None:
username = "Xircuits"
print("Hello " + username + " from HelloOutComponent!")
self.outport_example.value = username #(2)
self.done = TrueVideo
Create another Xircuits component has an
InPort
. As with the previous component, declare the type asInArg
which takes in astr
type. To access the data passed from the port, you can simply call it viaself.port_name.value
as shown in#(3)
.Code Snippet
@xai_component(color="red")
class HelloInComponent(Component):
inport_example: InArg[str]
def execute(self, ctx) -> None:
username = self.inport_example.value #(3)
print("Hello " + username + " from HelloInComponent!")
self.done = TrueVideo
Notes:
- An inPort can also be linked to a
Literal
or aArgument
component given the correct data type. - Declaring the port type as
any
will bypass the port type check.
Read More: