> ## 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.

# Adaptive price elicitation

> Narrow a respondent-specific price interval using integer arithmetic, bounded question slots, and ordinary skip rules.

This example adapts questions **within one interview**. Each Yes/No response
narrows the next offer; other respondents have independent state. The Machine
computes the next price and stopping condition. Survey continues to own navigation.

## Build and run the complete example

Everything needed for this example is defined on this page. Use an EDSL build
that includes the Machine and Runner APIs documented in this manual. Execute the
following four Python blocks in order in one session, or concatenate them into
one script. They require EDSL and the Python standard library; no repository
example modules or external data files are needed. The scripted run makes no
model API calls.

Four scripted respondents have integer thresholds 0, 37, 65, and 100. Starting
from the assumed range 0..100, their final intervals are respectively 0..0,
37..37, 65..65, and 100..100. The first three need six questions; the last needs
seven. This makes no live model calls.

### 1. Define the Machine

The Machine keeps an inclusive integer interval and an observation history.
Every accepted response narrows that interval and records the quoted price atomically.

```python theme={null}
from edsl.sharedstate import (
    Command,
    Machine,
    StateType,
    append,
    require,
    choose,
    constant,
    field,
    arg,
    record,
    round_ratio,
    assign,
    state_field,
    when,
)

def build_machine(lower=0, upper=100, max_questions=7, tolerance=0):
    for name, value in (("lower", lower), ("upper", upper), ("tolerance", tolerance)):
        if type(value) is not int or value < 0:
            raise ValueError(f"{name} must be a nonnegative integer")
    if upper < lower or type(max_questions) is not int or not 1 <= max_questions <= 32:
        raise ValueError("require lower <= upper and 1..32 questions")
    low, high, history = field("lower"), field("upper"), field("history")
    step, answer = arg("step"), arg("answer")
    price = round_ratio(low + high, 2, rounding="ceiling")
    done = (high - low <= constant("tolerance")) | (
        history.length() >= constant("max_questions")
    )
    replay = step < history.length()
    previous = choose(replay, history.at(step), {})
    return Machine(
        name="PriceElicitation",
        constants={"max_questions": max_questions, "tolerance": tolerance},
        fields={
            "lower": state_field(StateType.integer(minimum=lower, maximum=upper), lower),
            "upper": state_field(StateType.integer(minimum=lower, maximum=upper), upper),
            "history": state_field(
                StateType.sequence(
                    StateType.record(
                        {
                            "step": StateType.integer(minimum=0),
                            "price": StateType.integer(minimum=lower, maximum=upper),
                            "answer": StateType.choice(["Yes", "No"]),
                        }
                    )
                ),
                [],
            ),
            "closed": state_field(StateType.boolean(), False),
        },
        commands={
            "observe": Command(
                inputs={
                    "step": StateType.integer(minimum=0),
                    "answer": StateType.choice(["Yes", "No"]),
                },
                effects=(
                    require(
                        ~replay | (previous.get("answer") == answer),
                        code="answer_changed",
                    ),
                    when(
                        ~replay,
                        require(~done & ~field("closed"), code="elicitation_finished"),
                    ),
                    when(
                        ~replay,
                        require(step == history.length(), code="unexpected_step"),
                    ),
                    when(~replay, assign("lower", choose(answer == "Yes", price, low))),
                    when(
                        ~replay, assign("upper", choose(answer == "No", price - 1, high))
                    ),
                    when(
                        ~replay,
                        append(
                            "history", record(step=step, price=price, answer=answer)
                        ),
                    ),
                ),
            )
        },
        complete_when=done,
        close_effects=(assign("closed", True),),
        view={
            "lower": low,
            "upper": high,
            "price": price,
            "next_step": history.length(),
            "done": done | field("closed"),
            "precise": high - low <= constant("tolerance"),
        },
    )
```

### 2. Construct the Survey

Each respondent gets a separate state scope. The survey declares a bounded
number of question slots and skips those the Machine no longer needs.

```python theme={null}
from edsl import (
    Agent,
    AgentList,
    Model,
    QuestionCompute,
    QuestionMultipleChoice,
    Survey,
)

from edsl.sharedstate import SharedState, SharedStateMap, current

def build_survey(*, state_id=None, lower=0, upper=100, max_questions=7, tolerance=0):
    states = SharedStateMap(
        SharedState(pricing=build_machine(lower, upper, max_questions, tolerance)),
        state_id=state_id,
    )
    pricing = states.by([current.agent.study_id, current.agent.respondent_id]).pricing
    steps, choices = [], []
    for i in range(max_questions):
        quote = QuestionCompute(
            question_name=f"price_{i}",
            question_text="{{ shared_state.pricing.price if not shared_state.pricing.done and shared_state.pricing.next_step == "
            + str(i)
            + " else 'skip' }}",
        )
        answer = QuestionMultipleChoice(
            question_name=f"buy_{i}",
            question_text="Would you buy this product for {{ price_"
            + str(i)
            + ".answer }} price units?",
            question_options=["Yes", "No"],
        )
        steps.extend(
            [
                pricing.read(),
                quote,
                answer,
                pricing.observe(step=i, answer=answer.answer),
            ]
        )
        choices.append(answer)
    summary = QuestionCompute(
        question_name="price_interval",
        question_text="{{ shared_state.pricing.lower }}..{{ shared_state.pricing.upper }}",
    )
    survey = Survey([*steps, pricing.read(), summary])
    for i, question in enumerate(choices):
        survey.add_skip_rule(question, "{{ price_" + str(i) + ".answer }} == 'skip'")
    # Independent respondent scopes can proceed concurrently; no shared ranking.
    return survey, states, "concurrent"
```

### 3. Define the scripted respondents

These agents have known integer thresholds for checking the result. Only the
answering function reads that simulation trait; the Machine receives Yes/No responses.

```python theme={null}
def demo_answer(self, question, scenario):
    return (
        "Yes"
        if self.traits["value"] >= scenario["shared_state"]["pricing"]["price"]
        else "No"
    )

def demo_agents(values=(0, 37, 65, 100)):
    agents = AgentList()
    for i, value in enumerate(values):
        agent = Agent(
            traits={"respondent_id": f"R{i}", "study_id": "study", "value": value}
        )
        agent.add_direct_question_answering_method(demo_answer)
        agents.append(agent)
    return agents
```

### 4. Run and inspect the answers

`Model("test")` supplies the Jobs model dimension. The agents above answer locally,
and `QuestionCompute` evaluates the routing gates without a model call.

```python theme={null}
from edsl import Model
from edsl.runner import Runner

survey, states, schedule = build_survey(
    lower=0, upper=100, max_questions=7, tolerance=0
)
results = Runner(interview_schedule=schedule).submit(
    survey.by(demo_agents()).by(Model("test")), cache=False
).results()
assert not results.has_unfixed_exceptions
print(results.select("answer.price_interval").to_list())
```

## Watch one respondent's offers change

The follow-up Python blocks use the definitions and Results created above. The
`results` variable above contains four independent interviews. R1's scripted
threshold is 37: they answer Yes exactly when the offer is at most 37. The Machine
does not read that hidden simulation trait; it only receives the Yes/No answers.

| Question | Range before | Offer | Answer | Range after |
| - | - | - | - | - |
| 1 | 0..100 | 50 | No | 0..49 |
| 2 | 0..49 | 25 | Yes | 25..49 |
| 3 | 25..49 | 37 | Yes | 37..49 |
| 4 | 37..49 | 43 | No | 37..42 |
| 5 | 37..42 | 40 | No | 37..39 |
| 6 | 37..39 | 38 | No | 37..37 |

After the sixth response, the interval has one integer left. The seventh
multiple-choice question is skipped. Notice that a Yes at 37 alone did not end
the search: values 38 through 49 were still consistent until later No answers
ruled them out.

```python theme={null}
row = next(r for r in results if r.agent.traits["value"] == 37)
asked = [
    (int(row.answer[f"price_{i}"]), row.answer[f"buy_{i}"])
    for i in range(7)
    if row.answer.get(f"buy_{i}") is not None
]
assert asked == [(50, "No"), (25, "Yes"), (37, "Yes"),
                 (43, "No"), (40, "No"), (38, "No")]
assert row.answer["price_6"] == "skip"
assert row.answer["buy_6"] is None
assert row.answer["price_interval"] == "37..37"
```

### Compare precision with a smaller question budget

The same respondent can be surveyed with only two offers. This is a new study
state, not a continuation of the completed run above:

```python theme={null}
short_survey, _, short_schedule = build_survey(max_questions=2)
short_results = Runner(interview_schedule=short_schedule).submit(
    short_survey.by(demo_agents([37])).by(Model("test")), cache=False
).results()
assert short_results[0].answer["price_interval"] == "25..49"

last_write = [
    event for event in short_results.shared_state["bindings"][0]["events"]
    if event["kind"] == "write"
][-1]
assert len(last_write["state"]["pricing"]["history"]) == 2
```

| Configuration | Questions asked | Final interval | Why it stopped |
| - | - | - | - |
| Seven slots, tolerance zero | 6 | 37..37 | Exact integer threshold under the assumptions |
| Two slots, tolerance zero | 2 | 25..49 | Question budget exhausted |

An interval is the result. A limited budget does not justify replacing it with
an exact estimate or describing it as a statistical confidence interval.

## Integer search policy

The scope key is `[study_id, respondent_id]`. State holds inclusive integer
`lower` and `upper` bounds and an ordered observation history. At each step:

1. Compute `price = ceiling((lower + upper) / 2)` with `round_ratio`.
2. If the answer is Yes, set `lower = price`.
3. If the answer is No, set `upper = price - 1`.
4. Record the step, quoted price, and answer atomically.

Stop when the interval width is at most `tolerance` or `max_questions` have been
answered. `precise` distinguishes tolerance completion from budget exhaustion.
Defaults use exact integer units, no floating point or currency conversion.
The authoring helper permits at most 32 question slots.

The single command is `observe(step, answer)`, where answer is Yes or No. A fresh
step must equal the current history length. Earlier identical observations are
no-ops; changed answers and out-of-order observations reject without changing
bounds. A completed or explicitly closed search refuses new observations while
retaining valid historical retries.

## Fixed Survey slots, adaptive content

The adapter constructs a bounded sequence of computed price questions and
multiple-choice questions. Before each slot it reads the personal Machine view.
The computed question emits the price only when this slot is the next unfinished
step; otherwise it emits `skip`. An ordinary Survey skip rule suppresses that
question and its associated state write. A final read reports the interval.

This also supports partial resumption: a new job with the saved state map skips
old slots, keeps their original observations, and continues the remaining search.
The tests interrupt after two responses, restore the Survey, and finish without
counting either response twice. Fully completed searches ask no further choices.

Model-path tests inspect every quoted price in the actual prompts and saved
presentation metadata. Scripted respondents use the read view to make their
choice. The [presentation contract](https://docs.expectedparrot.com/en/latest/shared-state/scopes-and-surveys.md#which-options-did-this-respondent-see)
distinguishes the direct question object from a rendered model prompt.

## Interrupt after two answers, then resume

This intentionally interrupted survey has the full seven-slot definition but
ends after its second response. Restoring the original Survey preserves the state
map ID, so the next job continues that same personal search.

```python theme={null}
from edsl import Survey

full_survey, _, resume_schedule = build_survey()
people = demo_agents([37])
interrupted = Survey.from_dict(full_survey.to_dict())
interrupted.add_stop_rule("buy_1", "{{ buy_1.answer }} in ['Yes', 'No']")
first = Runner(interview_schedule=resume_schedule).submit(
    interrupted.by(people).by(Model("test")), cache=False
).results()
assert first[0].answer["buy_1"] == "Yes"
assert first[0].answer["buy_2"] is None

continued_survey = Survey.from_dict(full_survey.to_dict())
continued = Runner(interview_schedule=resume_schedule).submit(
    continued_survey.by(people).by(Model("test")), cache=False
).results()
assert continued[0].answer["buy_0"] is None
assert continued[0].answer["buy_1"] is None
assert continued[0].answer["price_interval"] == "37..37"
```

The two `None` answers in the second Results object mean those questions were not
asked **in that job**. Their earlier observations remain in the shared-state
history. Calling `build_survey()` again instead would create a fresh state map
and restart the search. Resuming also requires the same study and respondent IDs.

## Assumptions and design findings

The threshold must be an integer inside the **assumed** initial range, and the
respondent must buy at every price at or below it. An endpoint result does not
prove that the true value lies within the range: all-Yes responses also fit values
above the upper bound, and all-No responses can reflect values below the lower
bound. Interpret those cases as potentially censored. Noisy or changing preferences
need another elicitation policy; this deterministic search provides no confidence
interval or inconsistency diagnosis.

The [tests](https://github.com/expectedparrot/edsl/blob/feature/shared-state-v0/tests/sharedstate/test_survey_applications.py)
compare every transition with an independent integer-search reference, check
boundary values, early precision, limited budgets, stale steps, concurrent duplicate
observations, restart/replay, isolated scopes, and fresh-process execution.

This construction exposes the cost of fixed Survey slots: the authoring helper
must allocate a maximum number of slots and generate gates, even when the Machine
finishes early. It demonstrates current navigation without introducing a new
Machine-driven survey engine. Stable IDs and one logical search per respondent
scope remain host responsibilities; do not treat simultaneous differing responses
from two sessions as independent searches.

The default definition is 9,017 JSON bytes; its six-observation corpus replay
peaks at 4,642 host budget steps per transition. The corpus profiler reproduces
these host-specific measurements.


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