> ## Documentation Index
> Fetch the complete documentation index at: https://docs.expectedparrot.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Derived values and economic settlement

> Compute deterministic aggregates, allocations, and payoffs within a serialized workflow.

This chapter continues the [workflow manual](https://docs.expectedparrot.com/en/latest/workflows.md).

## Deterministic derived values

Language models should interpret evidence, not perform authoritative
arithmetic. Derived values provide a serializable calculation layer modeled on
the shared-state expression DSL.

```python theme={null}
stats = builder.derive(
    "round-2-statistics",
    mean=round_2.outputs("estimate").mean(),
    median=round_2.outputs("estimate").median(),
    minimum=round_2.outputs("estimate").minimum(),
    maximum=round_2.outputs("estimate").maximum(),
    spread=round_2.outputs("estimate").range(),
)
```

Reference a field in a prompt:

```python theme={null}
QuestionFreeText(
    question_name="summary",
    question_text=(
        f"The authoritative mean is {stats.field('mean').template}; "
        f"the range is {stats.field('spread').template}. Interpret them."
    ),
)
```

Or use a derived field in a condition:

```python theme={null}
converged = stats.field("spread").at_most(10)
```

Derived fields may reference earlier derived fields:

```python theme={null}
outcome = builder.derive(
    "round-2-outcome",
    converged=stats.field("spread").expression.compare_at_most(10),
)
```

The resulting expression tree contains named, allowlisted operators. It has no
callable, module path, source code, `eval`, or lambda. This is invalid:

```python theme={null}
builder.derive("unsafe", mean=lambda values: sum(values) / len(values))
```

The builder rejects it because derived fields must be `WorkflowExpression`
objects.

### Expression serialization

A mean expression resembles:

```json theme={null}
{
  "type": "workflow_expression",
  "op": "mean",
  "args": [
    {
      "type": "workflow_expression",
      "op": "step_outputs",
      "options": {
        "step_name": "round-2",
        "question_name": "estimate"
      }
    }
  ],
  "options": {}
}
```

Deserialization rejects unknown operators. Dependencies are extracted from the
tree and checked against the workflow. Derived references must name an earlier
definition and an existing field.

### Supported expression operations

The current evaluator supports:

```text theme={null}
Sources:      step_outputs, step_answer, step_submissions, derived_ref,
              seeded_uniform
Aggregates:   mean, median, minimum, maximum, range, sum, count_value,
              order_statistic, all_equal
Arithmetic:   add, subtract, multiply, divide, absolute
Comparisons:  at_most, at_least, equals
```

Missing source outputs delay availability. Non-numeric values cause numeric
aggregates to fail rather than silently inventing coercions beyond `float()`.
`all_equal()` compares canonical serialized values, so it also works for lists
and mappings such as complete rankings.

`choose(condition, then, otherwise)` evaluates only the selected branch. This
short-circuit behavior permits settlement expressions to reference answers on
optional branches: outputs from correctly skipped branches are never requested.

## Economic settlement primitives

Workflow expressions can consume a single answer or identity-preserving
submissions. This supports authoritative arithmetic without asking a model to
calculate payoffs:

```python theme={null}
accepted = response.answer("accept").value.compare_equals("Yes")
payoffs = builder.derive(
    "payoffs",
    proposer=choose(accepted, 10 - offer.answer("offer").value, 0),
    responder=choose(accepted, offer.answer("offer").value, 0),
)
```

Two-player normal-form games use a serializable payoff matrix. Explicit action
codes avoid ambiguity when labels share an initial letter; matrix keys concatenate
the codes in stable participant-ID order:

```python theme={null}
payoffs = choices.submissions.payoff_matrix(
    "action",
    {"WW": (2, 2), "WT": (1, 3), "TW": (3, 1), "TT": (0, 0)},
    action_codes={"Swerve": "W", "Straight": "T"},
)
```

Codes must be unique one-character strings. Omitting `action_codes` retains the
legacy first-character convention for serialized workflows created before this
option was introduced.

`closest_to(question, target, ties="all")` performs identity-aware ranking.
`DerivedFieldRef.for_participant()` projects an identity-keyed mapping into a
private recipient prompt. `match(role("player"), size=2)` deterministically
partitions a roster and round-trips as data.

Collections also expose serializable reductions:

```python theme={null}
total = contributions.outputs("contribution").sum()
number_free_riding = contributions.outputs("contribution").count_value(0)
second_price = bids.outputs("bid").nth_largest(2)
lowest_cost = bids.outputs("bid").nth_smallest(1)
```

`nth_largest()` and `nth_smallest()` use one-based ranks. During fan-out, an
order statistic with too few responses is treated as not yet available, allowing
remaining participants to answer before dependent work is rendered.

Use a symbolic per-submission binding to apply one expression to every response
while retaining participant identity:

```python theme={null}
own = contributions.submissions.each("contribution")
payoffs = builder.derive(
    "payoffs",
    by_participant=own.map(2 * best_shot.expression - own.value),
)
```

The serialized expression contains `map_submissions` and `submission_value`
operators; it does not contain a Python function. Evaluation returns a mapping
from participant ID to result, which can be privately projected with
`payoffs.field("by_participant").for_participant()`. A free `own.value` outside
its map is rejected during authoring.

Mapped expressions support the same arithmetic and comparisons as other
workflow expressions, including symbolic absolute value:

```python theme={null}
own = actions.submissions.each("action")
median = actions.outputs("action").median()
payoffs = own.map(10 - (own.value - median).absolute())
```

This keeps distance-based scoring declarative and portable.

Answers from multiple stages can be joined by participant identity before
mapping a longitudinal payoff:

```python theme={null}
history = join_by_participant(
    contribution=contribute.submissions,
    punishment=punish.submissions,
)
payoffs = history.map(
    10
    - history.value("contribution", "contribution")
    + public_return
    - history.value("punishment", "punishment_points")
)
```

Every source must contain the same nonempty participant set. Incomplete joins
remain unavailable rather than silently dropping respondents. The serialized
tree uses `join_submissions`, `joined_value`, and `map_joined_submissions`.

Static tables can select values or expressions without raw Python:

```python theme={null}
implemented_transfer = lookup(
    {0: transfer_if_zero, 5: transfer_if_five, 10: transfer_if_ten},
    realized_endowment,
)
```

Keys are normalized to strings during serialization. A missing key raises an
error unless `default=` is supplied.

Named experimental constants belong in workflow metadata rather than being
repeated throughout settlement expressions:

```python theme={null}
endowment = builder.parameter("endowment", 10, unit="tokens")
multiplier = builder.parameter("mpcr", 0.4)
payoff = endowment - own_contribution + multiplier * total_contribution
```

Parameters round-trip with the workflow and evaluate as ordinary expressions.
Names must be unique and values must be JSON-serializable. Units are retained as
metadata; automatic unit checking and prompt formatting are intentionally not
yet implied.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.