Using temporary scratch states#
To create temporary states (called scratch states) for generation sessions, you can use a with block and pass the result of the scratch_state method of the session as the value. This will save the state of the session, allowing us to perform operations within a scratch state. After the with block is done executing, the original state of the session will be automatically restored.
session = ld.session_for_model("model")
color_choices = ld.chain(
returns={"color": str},
nodes=[
"My favorite color is ",
ld.choice("color", ["red", "green", "blue"])
]
)
with session.scratch_state():
session.inject("I like red. Red is my favorite color. ")
print(color_choices.call(session)) # => "red"
session.inject("I like blue. Blue is my favorite color. ")
print(color_choices.call(session)) # => "blue"