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

# Run the examples

> Exercise forecast revision, numeric transport, and one- and two-step planning with Python 3.

These Adapt-1 templates cover how to set up a Domain, what to log, and which part of the response to use. Use the Python smoke tests below to exercise the same request sequence against a deployment before sending live observations.

## Run a template

1. Choose a fresh Domain ID. Send `POST /domains` with the template object under `learning.transition`. In `schema`, declare the signal names from the template's input and target paths without the `values.` prefix, and declare `"outcome"` in `event_types`.
2. Send completed observations to `POST /domains/{id}/events`, with `event_type: "outcome"` and the input and target values under `values`. Keep the same authentication and session for every request. Check `learner_eligibility` to confirm admission and count the applicable observations before running a query.
3. Send `POST /domains/{id}/query` with the pre-outcome inputs under `context.values`. Request `decision_id` and `transition_prediction` for a forecast or `decision_id` and `transition_plan` for a plan. Put the outcome's identifier in `context.metadata.future_id` if you intend to revise or resolve it.
4. When the outcome becomes available, post one event with the pre-outcome inputs, the measured targets, and the returned `decision_id` and `future_id` in `metadata`. For a plan, also record the executed action in `values`. [Inspect learning and troubleshoot](https://docs.reilabs.org/docs/neuroadapt/futures/diagnostics.md).

For example, wrap the transition object for the first template in this Domain body. Fill in `learning.transition` with that object before sending the request.

```json theme={null}
{
  "domain_id": "site-power-futures",
  "session_id": "my-stable-session",
  "schema": {
    "signals": [
      "lag_load_mw", "wind_speed_mps", "air_temperature_c",
      "hour_sin", "hour_cos", "next_load_mw", "next_wind_mw"
    ],
    "event_types": ["outcome"]
  },
  "learning": {"transition": {}}
}
```

## Forecast joint demand and generation

Forecast site load and wind generation for the next hour. The numeric levels can move with weather and time of day. Use `linear_residual` to transport the numeric levels and keep the residual outcomes joint.

```json theme={null}
{
  "enabled": true,
  "event_types": ["outcome"],
  "input_paths": [
    "values.lag_load_mw", "values.wind_speed_mps", "values.air_temperature_c",
    "values.hour_sin", "values.hour_cos"
  ],
  "targets": [
    {"path": "values.next_load_mw", "type": "number"},
    {"path": "values.next_wind_mw", "type": "number"}
  ],
  "required_support": 6,
  "max_samples": 512,
  "max_distance": 1.0,
  "numeric_min_skill": 0.0,
  "numeric_ridge": 1.0,
  "futures": {
    "enabled": true,
    "conditioning": "kernel",
    "numeric_transport": "linear_residual",
    "bandwidth": 0.25,
    "max_support": 256,
    "max_branches": 128,
    "max_pending_forecasts": 128,
    "max_scores": 1024
  }
}
```

For each observed hour, record the earlier readings and calendar features along with load and generation measured at the next hour. This event's `values` contain the earlier readings and both measured outcomes.

```json theme={null}
{
  "lag_load_mw": 38.1,
  "wind_speed_mps": 6.8,
  "air_temperature_c": 12.2,
  "hour_sin": 0.5,
  "hour_cos": 0.866,
  "next_load_mw": 40.2,
  "next_wind_mw": 9.6
}
```

Query with the same five input fields. Check which targets appear in `numeric_transport.target_paths`, then read joint atoms to estimate events such as high load with low generation. If the cost of reserving capacity is already known, compute the expected cost of each permitted capacity in your application using the forecast probabilities. [Read the joint atoms](https://docs.reilabs.org/docs/neuroadapt/futures/distribution.md#read-the-joint-atoms).

### Pool sites for cold-start forecasts

Reuse this declaration for sites with compatible dynamics. Divide load and generation by an available site-specific scale, such as rated capacity, and name the resulting paths according to their units. Apply the same transform to past inputs and outcome records. Keep site IDs in your application trace and give each outcome a unique `future_id`. Leave site identity out of the learner's inputs and grouping. Hold out one site when checking how well shared history serves a first forecast there, then restore its physical units when applying capacity rules.

## Forecast near-zero joint deviations

For regional generation forecast errors, compute deviations from the baseline forecast issued at the same time. If those deviations have little conditional mean structure, start with `numeric_transport: "none"`. The distribution can still change shape as weather conditions change.

```json theme={null}
{
  "enabled": true,
  "event_types": ["outcome"],
  "input_paths": ["values.wind_speed_mps", "values.pressure_change_hpa", "values.wind_spread_mps"],
  "targets": [
    {"path": "values.area_a_error", "type": "number"},
    {"path": "values.area_b_error", "type": "number"},
    {"path": "values.area_c_error", "type": "number"}
  ],
  "required_support": 6,
  "max_samples": 1024,
  "max_distance": 1.0,
  "futures": {
    "enabled": true,
    "conditioning": "kernel",
    "numeric_transport": "none",
    "bandwidth": 0.25,
    "max_support": 512,
    "max_branches": 128,
    "max_pending_forecasts": 128,
    "max_scores": 1024
  }
}
```

Log the three errors at their common target horizon and on comparable scales. To get the probability that all three regions underproduce together, sum `probability` over joint atoms where all three observed-minus-baseline errors are below your chosen thresholds. Compare `prior` and `conditional` on the same realized errors to check whether evidence improves the joint forecast.

## Revise when a feed arrives late

Reuse the [joint demand and generation template](#forecast-joint-demand-and-generation). Start with `conditioning: "kernel"`. For a wider deployment with many observed masks, size `max_calibration_groups` for the mask, group, and action combinations you want to track. For example, `1024` is the supported upper bound. Size `max_pending_forecasts` for the maximum number of unresolved revisions across open outcomes.

The first query can use only the load and calendar fields. If the weather feed arrives later, include the new fields alongside the earlier ones. Send these as the `context` in separate queries, preserving the `future_id`.

```json theme={null}
{
  "values": {"lag_load_mw": 38.1, "hour_sin": 0.5, "hour_cos": 0.866},
  "metadata": {"future_id": "site-power-hour-001"}
}
```

```json theme={null}
{
  "values": {
    "lag_load_mw": 38.1,
    "hour_sin": 0.5,
    "hour_cos": 0.866,
    "wind_speed_mps": 6.8,
    "air_temperature_c": 12.2
  },
  "metadata": {"future_id": "site-power-hour-001"}
}
```

When both measured targets are available, send the completed observation with one returned `decision_id` and the same `future_id`. Inspect the observed paths at each issue time and the number of revisions resolved. [Issue and revise a forecast](https://docs.reilabs.org/docs/neuroadapt/futures/forecast.md).

## Plan one dispatch step under a reserve limit

Choose among three storage commands using current reserve and expected demand. Set the modeled risk limit for leaving the interval below 20% reserve to 10%. Use the objective scale in percentage points.

```json theme={null}
{
  "enabled": true,
  "event_types": ["outcome"],
  "input_paths": ["values.reserve_pct", "values.demand_mw", "values.action"],
  "action_path": "values.action",
  "targets": [{"path": "values.next_reserve_pct", "type": "number"}],
  "required_support": 6,
  "max_samples": 2048,
  "max_distance": 1.0,
  "numeric_min_skill": 0.0,
  "numeric_ridge": 1.0,
  "futures": {
    "enabled": true,
    "conditioning": "kernel",
    "numeric_transport": "linear_residual",
    "bandwidth": 0.25,
    "max_support": 128,
    "max_branches": 128,
    "max_pending_forecasts": 128,
    "max_scores": 1024
  },
  "planning": {
    "enabled": true,
    "probabilistic": true,
    "actions": ["hold", "charge", "discharge"],
    "horizon": 1,
    "beam_width": 8,
    "state_bindings": [
      {"target_path": "values.next_reserve_pct", "state_path": "values.reserve_pct"}
    ],
    "objectives": [
      {"path": "values.reserve_pct", "direction": "target", "target": 55, "weight": 1, "scale": 20}
    ],
    "constraints": [{"path": "values.reserve_pct", "operator": "gte", "value": 20}],
    "risk_weight": 0.0,
    "tail_probability": 0.10,
    "max_failure_probability": 0.10,
    "max_unresolved_probability": 0.05
  }
}
```

Each completed observation pairs `reserve_pct` and `demand_mw` with the executed `action` and measured `next_reserve_pct`. Collect observations for all three actions across the states you expect to query. For a plan, send only the current reserve and demand. Read `transition_plan.selected_action` after confirming `status: "planned"` and `failure_probability_upper` within the configured limit. Use your application's fallback during warmup and abstention.

## Plan two storage intervals

Use this template when current dispatch changes the reserve you can draw on next interval. Here the state is a reserve band. The observed step payoff is a relative utility score between `-2` and `2`, so a scale of `4` covers any difference between successive rewards without clipping.

```json theme={null}
{
  "enabled": true,
  "event_types": ["outcome"],
  "input_paths": ["values.reserve_band", "values.step_reward", "values.action"],
  "group_by_paths": ["values.reserve_band"],
  "action_path": "values.action",
  "targets": [
    {"path": "values.next_reserve_band", "type": "categorical"},
    {"path": "values.next_step_reward", "type": "number"}
  ],
  "required_support": 6,
  "max_samples": 2048,
  "max_distance": 1.0,
  "futures": {
    "enabled": true,
    "conditioning": "kernel",
    "numeric_transport": "none",
    "max_support": 128,
    "max_branches": 128
  },
  "planning": {
    "enabled": true,
    "probabilistic": true,
    "actions": ["hold", "charge", "discharge"],
    "horizon": 2,
    "beam_width": 16,
    "max_rollouts": 32768,
    "discount": 0.5,
    "state_bindings": [
      {"target_path": "values.next_reserve_band", "state_path": "values.reserve_band"},
      {"target_path": "values.next_step_reward", "state_path": "values.step_reward"}
    ],
    "objectives": [
      {"path": "values.step_reward", "direction": "maximize", "weight": 1, "scale": 4}
    ],
    "constraints": [{"path": "values.reserve_band", "operator": "ne", "value": "below_floor"}],
    "risk_weight": 0.0,
    "max_failure_probability": 0.10,
    "max_unresolved_probability": 0.05
  }
}
```

These rows illustrate the fields to send from a recorded or simulated transition. Collect enough actual or simulated observations per reachable state and action, including projected reward input values.

| `reserve_band` | `step_reward` | `action` | `next_reserve_band` | `next_step_reward` |
| - | -: | - | - | -: |
| `ready` | 0 | `discharge` | `low` | 2 |
| `low` | 2 | `charge` | `ready` | -1 |
| `low` | 2 | `hold` | `below_floor` | -2 |
| `below_floor` | -2 | `hold` | `below_floor` | 0 |

Start a new plan at the measured reserve band with `step_reward: 0.0`. With this two-step objective, a plan earning rewards `2` and `-1` scores better on the objective term than one earning `0` and `-1`, before constraints. Inspect `candidate_sequences` to verify that ordering on known transitions. Include and refresh valid transitions for the absorbing `below_floor` state if it can appear in projected rollouts. Execute the first selected action only, then query again with the actual state. [Plan across multiple steps](https://docs.reilabs.org/docs/neuroadapt/futures/planning.md#plan-across-multiple-steps).

## Run the Python smoke tests

Set the API base to your authorized deployment and supply its key. The base must include `/api/v1`.

```bash theme={null}
export ADAPT_API_BASE='https://rei-neuroadapt-api.reilabs.org/api/v1'
read -rsp 'API key: ' ADAPT_API_KEY
export ADAPT_API_KEY
```

Save the Python code below as `futures_example.py`. It uses the standard library. Choose a case and run it from a writable directory.

```bash theme={null}
python3 futures_example.py --case forecast
python3 futures_example.py --case numeric
python3 futures_example.py --case planning
python3 futures_example.py --case multistep
# Or run all four:
python3 futures_example.py --case all
```

Each case creates a fresh Domain, sends synthetic observations and prints a `PASS` line for each successful check. The multi-step case sends 72 transitions and queries between observations. Requests, responses and checks are saved under `futures-...` in the working directory. The trace excludes authentication headers. After inspecting the results, [delete and verify the disposable Domains](https://docs.reilabs.org/docs/neuroadapt/futures/diagnostics.md#operate-the-stream) using their IDs in the requests trace.

```python theme={null}
import argparse
import json
import os
import time
import uuid
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen


def run(case):
    base = os.environ["ADAPT_API_BASE"].rstrip("/")
    key = os.environ["ADAPT_API_KEY"]
    session = "futures-" + uuid.uuid4().hex
    out = Path(session)
    out.mkdir(exist_ok=False)

    def api(method, path, body=None):
        headers = {"Authorization": "Bearer " + key}
        data = None
        if body is not None:
            headers["Content-Type"] = "application/json"
            data = json.dumps(body, allow_nan=False).encode()
        request = Request(base + path, data=data, headers=headers, method=method)
        started = time.monotonic()
        try:
            with urlopen(request, timeout=180) as response:
                status, raw = response.status, response.read().decode()
        except HTTPError as exc:
            status, raw = exc.code, exc.read().decode()
        try:
            result = json.loads(raw)
        except json.JSONDecodeError:
            result = {"raw_response": raw}
        record = {"method": method, "path": path, "request": body,
                  "status": status, "seconds": time.monotonic() - started,
                  "response": result}
        with (out / "requests.jsonl").open("a") as handle:
            handle.write(json.dumps(record) + "\n")
        if status >= 400:
            raise RuntimeError(f"{method} {path}: HTTP {status}: {raw}")
        return result

    def create(name, signals, transition):
        domain = session + "-" + name
        body = {"domain_id": domain, "session_id": session,
                "schema": {"signals": signals, "event_types": ["outcome"]},
                "learning": {"transition": transition}}
        (out / (name + "-domain.json")).write_text(json.dumps(body, indent=2))
        api("POST", "/domains", body)
        return domain

    def query(domain, values, future=None):
        context = {"values": values}
        if future is not None:
            context["metadata"] = {"future_id": future}
        return api("POST", f"/domains/{domain}/query", {
            "session_id": session, "question": "Forecast and plan",
            "context": context,
            "return_fields": ["decision_id", "transition_prediction", "transition_plan"],
        })

    def observe(domain, values, decision=None, future=None):
        metadata = {}
        if decision is not None:
            metadata["decision_id"] = decision
        if future is not None:
            metadata["future_id"] = future
        return api("POST", f"/domains/{domain}/events", {
            "session_id": session, "event_type": "outcome",
            "values": values, "metadata": metadata,
        })

    def state(domain):
        result = api("POST", f"/domains/{domain}/explain", {
            "session_id": session, "question": "Inspect learning state",
            "context": {"values": {}}, "update_memory_state": False,
        })
        return result["learning_state"]["subsystems"]["structured_transition"]

    def check(name, condition, detail):
        if not condition:
            raise AssertionError(name + ": " + json.dumps(detail))
        print("PASS", name)
        with (out / "checks.jsonl").open("a") as handle:
            handle.write(json.dumps({"check": name, "passed": True, "detail": detail}) + "\n")

    def distribution(reply):
        return reply["transition_prediction"]["futures"]

    def basic_transition():
        return {"enabled": True, "event_types": ["outcome"],
                "input_paths": ["values.cue"],
                "targets": [{"path": "values.result", "type": "boolean"}],
                "required_support": 4, "max_samples": 512,
                "futures": {"enabled": True}}

    if case in ("forecast", "all"):
        domain = create("forecast", ["cue", "result"], basic_transition())
        cold = distribution(query(domain, {"cue": 1}))
        check("empty Domain abstains", cold["status"] == "abstained", cold)
        for i in range(12):
            observe(domain, {"cue": i % 2, "result": bool(i % 2)})
        for i in range(24):
            cue = i % 2
            future = "calibration-" + str(i)
            issued = query(domain, {"cue": cue}, future)
            completed = observe(domain, {"cue": cue, "result": bool(cue)},
                                issued["decision_id"], future)
            update = completed["learner_eligibility"]["futures_update"]
            if not update["accepted"]:
                raise AssertionError(update)
        early_reply = query(domain, {}, "revised-target")
        late_reply = query(domain, {"cue": 1}, "revised-target")
        early, late = distribution(early_reply), distribution(late_reply)
        early_p = early["marginals"]["values.result"]["probabilities"]["true"]
        late_p = late["marginals"]["values.result"]["probabilities"]["true"]
        check("new evidence changes probabilities", late_p > early_p,
              {"before_evidence": early_p, "after_evidence": late_p})
        completed = observe(domain, {"cue": 1, "result": True},
                            late_reply["decision_id"], "revised-target")
        update = completed["learner_eligibility"]["futures_update"]
        check("one outcome resolves both revisions",
              update["accepted"] and update["resolved_revisions"] == 2, update)
        learning = state(domain)["futures"]
        check("issued forecasts outperform their prior on this mock stream",
              learning["mean_energy_score"] < learning["mean_prior_energy_score"], learning)
        check("all predicted receipts resolved", learning["pending_forecasts"] == 0, learning)

    if case in ("numeric", "all"):
        cfg = basic_transition()
        cfg["targets"] = [{"path": "values.result", "type": "number"}]
        cfg["numeric_min_skill"] = 0.0
        cfg["futures"]["numeric_transport"] = "linear_residual"
        domain = create("numeric", ["cue", "result"], cfg)
        for i in range(80):
            cue = ((i * 17) % 80) / 80
            observed = 10 * cue + (0.1 if i % 2 else -0.1)
            observe(domain, {"cue": cue, "result": observed})
        issued = query(domain, {"cue": 0.55}, "numeric-target")
        forecast = distribution(issued)
        check("numeric transport is active",
              forecast["numeric_transport"]["status"] == "active", forecast)
        mean = forecast["marginals"]["values.result"]["mean"]
        check("numeric center follows this mock relationship", abs(mean - 5.5) < 0.3,
              forecast["marginals"])
        observe(domain, {"cue": 0.55, "result": 5.6}, issued["decision_id"], "numeric-target")

    if case in ("planning", "all"):
        cfg = {"enabled": True, "event_types": ["outcome"],
               "input_paths": ["values.x", "values.action"], "action_path": "values.action",
               "targets": [{"path": "values.next_x", "type": "number"}],
               "required_support": 4, "max_samples": 512,
               "futures": {"enabled": True},
               "planning": {"enabled": True, "probabilistic": True,
                   "actions": ["wide", "steady"], "horizon": 1,
                   "state_bindings": [{"target_path": "values.next_x", "state_path": "values.x"}],
                   "goals": [{"path": "values.x", "operator": "between", "value": [0.8, 1.2]}],
                   "objectives": [{"path": "values.x", "direction": "target", "target": 1.0}],
                   "constraints": [{"path": "values.x", "operator": "lte", "value": 1.2}],
                   "risk_weight": 0.25, "tail_probability": 0.1,
                   "max_failure_probability": 0.0, "max_unresolved_probability": 0.05}}
        domain = create("planning", ["x", "action", "next_x"], cfg)
        for i in range(12):
            action = "wide" if i < 6 else "steady"
            next_x = (2.0 if i % 2 else 0.0) if action == "wide" else 0.9
            observe(domain, {"x": 0.0, "action": action, "next_x": next_x})
        issued = query(domain, {"x": 0.0}, "planned-execution")
        plan = issued["transition_plan"]
        check("planner selects the observed lower-risk action",
              plan["status"] == "planned" and plan["selected_action"] == "steady", plan)
        completed = observe(domain, {"x": 0.0, "action": plan["selected_action"], "next_x": 0.9},
                            issued["decision_id"], "planned-execution")
        update = completed["learner_eligibility"]["futures_update"]
        check("execution resolves the selected action's forecast", update["accepted"], update)

    if case in ("multistep", "all"):
        cfg = {"enabled": True, "event_types": ["outcome"],
               "input_paths": ["values.phase", "values.action"], "action_path": "values.action",
               "targets": [{"path": "values.after", "type": "categorical"}],
               "required_support": 2, "max_samples": 512, "max_distance": 1.0,
               "futures": {"enabled": True, "prior_strength": 0.1},
               "planning": {"enabled": True, "probabilistic": True,
                   "actions": ["move", "finish"], "horizon": 2, "beam_width": 8,
                   "state_bindings": [{"target_path": "values.after", "state_path": "values.phase"}],
                   "goals": [{"path": "values.phase", "value": "done"}],
                   "max_unresolved_probability": 0.1}}
        domain = create("multistep", ["phase", "action", "after"], cfg)
        executions = [("start", "move", "middle"), ("start", "finish", "dead"),
                      ("middle", "finish", "done"), ("middle", "move", "dead"),
                      ("dead", "move", "dead"), ("dead", "finish", "dead")]
        for i in range(72):
            phase, action, after = executions[i % len(executions)]
            future = "step-" + str(i)
            issued = query(domain, {"phase": phase, "action": action}, future)
            predicted = distribution(issued)["status"] == "predicted"
            observe(domain, {"phase": phase, "action": action, "after": after},
                    issued["decision_id"] if predicted else None, future if predicted else None)
        issued = query(domain, {"phase": "start"}, "two-step-plan")
        plan = issued["transition_plan"]
        check("two-step route learned from transitions",
              plan["status"] == "planned" and plan["action_sequence"] == ["move", "finish"], plan)
        # Execute only the first action and report its real result; replan afterwards.
        observe(domain, {"phase": "start", "action": plan["selected_action"], "after": "middle"},
                issued["decision_id"], "two-step-plan")

    print("Session:", session)
    print("Evidence directory:", out.resolve())
    return out


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--case", choices=["forecast", "numeric", "planning", "multistep", "all"],
                        default="forecast")
    run(parser.parse_args().case)
```


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