Tutorial

Working with State

Declare variables, inject them into prompts, and let the agent read and write them back — all within a single .mgx script.

Margarita
1
Declare a variable with @state
@state declares a variable that lives for the lifetime of the run. Set it to a string, number, or leave it empty — it's available to everything below the line it's declared on.
state.mgx
@state name = "Alice"
@state count = 0
@state notes = ""

<< Hello! >>

@effect run
2
Inject variables into prompts with ${var}
Use ${variableName} anywhere inside a << >> block. Margarita substitutes the current value before the prompt is sent to the LLM.
state.mgx
@state name = "Alice"
@state language = "Python"

// ${name} and ${language} are replaced before the LLM sees the prompt
<<
Write a short bio for a developer named ${name}
who specialises in ${language}.
>>

@effect run
3
Let the agent read and write state
State variables are visible to the LLM through the prompt. You can instruct the agent to update a variable — Margarita reads the response and writes the new value back into state, where it's available for the rest of the script.
state.mgx
@state score = 0
@state feedback = ""

// Give the agent the current state and ask it to update both variables
<<
The current score is ${score}.

Review this code snippet and set `score` to a number from 0–100
and `feedback` to a one-sentence summary of the quality.

```python
def add(a, b): return a+b
```
>>

@effect run

// score and feedback now hold whatever the agent set them to
<< Explain the score of ${score} in more detail. >>

@effect run

What's next?

Next up: collecting input from the user mid-run.