Browse documentation
Domains
View Markdown
On this page

Education: a tutoring session

What you will learn: how a harness holds a conversation with a person over many turns, parks between their messages, grades each answer without a model, keeps a memory per learner that later lessons can recall from, and records a note only a teacher may sign off as mastery. You will run a short lesson to mastery over three in-memory ports.

Read first: Domains, for what every harness here is made of; Data, the previous domain page; and the concept pages Conversations (an actor that talks with a person and parks until they answer) and Errands (a stage that makes tool calls without a model). Workflows in depth explains loops between stages, and Memory explains a memory, its scope, and how a context budget hands it what a reduction drops.

Time: about 20 minutes.

education/tutoring_session (module gvn_domains.education.tutoring) teaches one learner one topic over a conversation.

Where this harness fits

Every harness in gvn-domains is made of the same parts (see What a domain harness is made of): a plan, which is a workflow whose states are stages; tools and a policy that check every call before it has an effect; ports, small abstract classes for the outside world that you implement; a brief, the data a run starts with; and the Launcher, which runs the harness on a Governor. For a tutoring session they look like this:

flowchart LR
    brief(["brief: learner, topic, streak, turns"])
    learner(["the learner"])
    teacher(["a teacher who signs off mastery"])
    subgraph harness ["tutoring_session"]
        plan["<b>TutoringSession</b> plan<br/>teach · grade · note"]
        policy["policy and tools<br/>check every call"]
        plan -- "tool calls" --> policy
    end
    ports[("your ports<br/>Curriculum · Records · Memory")]
    launcher["<b>Launcher</b>"]
    brief --> launcher
    launcher -- "drives" --> plan
    policy -- "cleared calls" --> ports
    launcher -- "the tutor's question" --> learner
    learner -- "an answer" --> launcher
    launcher -- "asks" --> teacher
    teacher -- "approve or deny" --> launcher

What sets this harness apart: a person takes part on every turn, not only to approve, and their text is untrusted. The learner is not a port: their messages arrive as answers to the run's requests, through the launcher. It is also the one harness in the package with a memory: text kept beyond the run, one scope per learner, so a later lesson with the same learner can find what an earlier one covered.

The problem

A tutor explains a step, asks a question, waits for the learner's reply, and judges it. A model is good at the explaining, but the learner's text is untrusted: it must not be able to change the topic, mark its own answer correct, or record its own mastery. The learner may also take minutes or days to reply, and the session must cost nothing while it waits. A long lesson outgrows what the model can be sent, so older turns are summarised; what the summary leaves out should not be lost to the learner's next lesson, and one learner's lessons must never be shown to another.

The plan

A run is a TutoringSession workflow. It moves through these states:

  • idle: the run exists but has not started;
  • teaching: one turn of a Conversation: the tutor gives feedback on the last answer, teaches a step and asks its question, then the run parks until the learner replies;
  • grading: an Errand has the reply graded against the curriculum, then the run goes back to teaching, or on to noting at mastery or at the session limit;
  • noting: an agent records a progress note for the learner;
  • mastered, practised or failed: the run is over.

The plan as gvn draws it from the code (a docs test checks that it still matches). Each box is a state, emits names the work it asks for, and each arrow is labelled with the input that moves the run along it; otherwise: stay means any input not drawn leaves the run where it is:

stateDiagram-v2
    failed : emits failed
    grading : emits grade
    idle : emits idle
    mastered : emits mastered
    noting : emits note
    practised : emits practised
    teaching : emits teach
    [*] --> idle
    grading --> teaching : carry_on
    grading --> failed : grading_failed
    grading --> noting : out_of_turns
    grading --> noting : reached_mastery
    idle --> teaching : started
    noting --> failed : not_noted
    noting --> mastered : noted_mastery
    noting --> practised : noted_practice
    noting --> failed : noting_failed
    teaching --> teaching : carry_on
    teaching --> grading : heard
    teaching --> noting : learner_left
    teaching --> noting : lesson_cut_short
    teaching --> noting : out_of_turns
    teaching --> failed : teaching_failed
    teaching --> noting : tutor_closed
    failed --> [*]
    mastered --> [*]
    practised --> [*]
    note right of idle
        otherwise: stay
    end note

teaching and grading form a real loop, bounded by the judges (a judge is a Decision that reads how a stage ended and picks the next symbol). In the table, thread is the conversation's history, carried from one round's conversation into the next, and memo.visits("teaching") counts how many times the run has been in teaching, read from the workflow's Memo (its record of every finished stage visit).

Stage Who How it ends
teaching a Conversation with turns=1, continuing the last round's thread: pose_question, recall heard; learner_left; tutor_closed when the tutor ends the lesson early; carry_on or out_of_turns when the tutor posed nothing; lesson_cut_short when the conversation outgrew its context budget; teaching_failed
grading an Errand: check_answer a judge: carry_on; reached_mastery after streak graded answers in a row marked correct; out_of_turns when memo.visits("teaching") reaches turns; grading_failed
noting a noter agent: record_progress noted_mastery, noted_practice, not_noted or noting_failed

The same plan as a table, also rendered from the code: > marks the initial state, * the final states, and each row lists the state's output and its transitions.

   state      output     transitions
*  failed     failed     -
   grading    grade      carry_on -> teaching, grading_failed -> failed, out_of_turns -> noting, reached_mastery -> noting
>  idle       idle       started -> teaching
*  mastered   mastered   -
   noting     note       not_noted -> failed, noted_mastery -> mastered, noted_practice -> practised, noting_failed -> failed
*  practised  practised  -
   teaching   teach      carry_on -> teaching, heard -> grading, learner_left -> noting, lesson_cut_short -> noting, out_of_turns -> noting, teaching_failed -> failed, tutor_closed -> noting
otherwise: stay

Walking through a run

The blocks below run in order as one program, as part of the docs tests.

1. The outside world: three ports

The harness needs a curriculum to teach from, a place to record notes, and a memory. You implement the first two, which are the harness's own; record takes a key, an idempotency key, and records once per key, so a repeat after a crash adds nothing. The third is gvn's own Memory port, so any implementation of it will do: SqliteMemory keeps it in a file, and a search index or vector store of your own fits behind the same port.

Port Methods
Curriculum (read only) lesson(topic), check(topic, step, answer)
Records record(learner, topic, session, note, mastered, key): once per key
Memory (gvn.harness.ports) remember(scope, text, key): once per key; recall(scope, query, limit)

The learner is not a port: their messages are answers to the run's requests. Here are a two-step lesson on fractions and a gradebook that keeps one note per key:

import typing

from gvn_domains.education.tutoring import Curriculum, Records


class FractionsLesson(Curriculum):
    STEPS = [
        {"teach": "A fraction is part of a whole.", "question": "What is half of 1?",
         "answer": "1/2"},
        {"teach": "Add fractions with like denominators.", "question": "What is 1/4 + 2/4?",
         "answer": "3/4"},
    ]

    async def lesson(self, topic: str) -> list[dict[str, str]]:
        if topic != "fractions":
            raise LookupError(f"no lesson on {topic!r}")
        return [{"teach": step["teach"], "question": step["question"]} for step in self.STEPS]

    async def check(self, topic: str, step: int, answer: str) -> dict[str, typing.Any]:
        key = self.STEPS[step - 1]["answer"]
        correct = key in answer.split()
        return {"correct": correct, "explanation": "right" if correct else f"the answer is {key}"}


class Gradebook(Records):
    def __init__(self) -> None:
        self._notes = {}  # key -> (note id, learner, topic, mastered)

    async def record(
        self, learner: str, topic: str, session: str, note: str, mastered: bool, key: str
    ) -> str:
        if key not in self._notes:
            self._notes[key] = (f"N-{len(self._notes) + 1}", learner, topic, mastered)
        return self._notes[key][0]

    def notes(self) -> list[tuple[str, str, str, bool]]:
        return list(self._notes.values())

2. The harness and its brief

A run starts with the brief {"learner": str, "topic": str, "streak": int, "turns": int}: streak correct answers in a row (1 to 10) count as mastery, and turns (1 to 60) bounds the session. The learner and the topic are ids: a letter or digit, then up to 63 letters, digits, _, . or -.

For the memory, this page uses ListMemory, the in-memory fake from gvn.testing.fakes (an entry matches a query when they share a word). Each learner has their own memory scope, the string learner_scope(learner) returns. To stand in for an earlier lesson, put one entry in Ada's scope and one in Grace's, as their earlier lessons' summaries could have left them:

import asyncio

from gvn.testing.fakes import ListMemory
from gvn_domains.education.tutoring import learner_scope

memory = ListMemory()
print(learner_scope("ada"))
asyncio.run(memory.remember(
    learner_scope("ada"), "Lesson 6 on fractions: Ada mixed up numerator and denominator.", key="lesson-6"
))
asyncio.run(memory.remember(
    learner_scope("grace"), "Lesson 2 on fractions: Grace mastered halves.", key="lesson-2"
))
tutoring_session/learner/ada

The catalog builds the harness by its path from your ports (see The catalog); without a Memory among them it refuses with MissingPort. Its toolbox holds every tool its agents may call:

from gvn_domains.catalog import Ports
from gvn_domains.directory import catalog

gradebook = Gradebook()
tutor = catalog().harness(
    path="education/tutoring_session", ports=Ports.of(FractionsLesson(), gradebook, memory)
)
lesson_brief = {"learner": "ada", "topic": "fractions", "streak": 2, "turns": 4}
for identity in tutor.toolbox().identities():
    print(identity)
print(list(tutor.fulfillers()))
gvn.runtime.memory.recall
gvn_domains.education.tutoring.check_answer
gvn_domains.education.tutoring.pose_question
gvn_domains.education.tutoring.record_progress
['remember']

The toolbox lists its tools by identity: a namespace, a dot and the short name the model sees. recall is gvn's own RecallTool, so its namespace is gvn's memory module; the other three are defined in the tutoring module. The module names each tool with a constant (POSE_QUESTION, RECALL, CHECK_ANSWER, RECORD_PROGRESS, together TOOLS) that the plan declares, so the Governor checks this toolbox against them before the run starts (see how a harness names its tools).

The memory is reached two ways, as the Memory page describes. The tutor may call recall, a RecallTool, to search it; and fulfillers() gives the launcher a MemoryFulfiller for the remember request, through which the tutor's context budget hands the memory what a summary is about to drop.

3. A model to play the tutor and the noter

No real model is used: the function below plays both agents. A fake model, FunctionModel, calls it with the exchange, everything the model would be shown (instructions and messages so far), and it returns a Reply, the model's answer; a ToolCall in it asks for a tool, a message with role TOOL carries results back, and one with role USER is the learner's.

Each round, the tutor calls pose_question with a step number and gets back what to teach and the question to ask; then it speaks, ending with the question. The step it should teach is suggested in its instructions, which the run writes (more on that in step 5). In the first round it also calls recall with the query "fractions", and keeps what came back in recalled so that this page can print it. The noter calls record_progress with a short note.

import re

from gvn.harness.messages import TOOL, USER, Message, ToolCall
from gvn.harness.ports import Exchange, Reply
from gvn.testing.fakes import FunctionModel
from gvn_domains.education.tutoring import TUTOR


recalled = []


def tutoring_model(exchange: Exchange) -> Reply:
    messages = exchange.messages()
    if exchange.instructions().startswith(TUTOR):
        last_heard = max(i for i, message in enumerate(messages) if message.role() == USER)
        results = {
            r.call_id(): r.content()
            for m in messages[last_heard + 1:] if m.role() == TOOL for r in m.results()
        }
        if not results:
            step = int(re.search(r"Suggested step: (\d+)", exchange.instructions()).group(1))
            calls = [ToolCall(call_id="c1", name="pose_question", arguments={"step": step})]
            if step == 1:  # the first round: look up earlier lessons with this learner
                calls.append(ToolCall(call_id="r1", name="recall", arguments={"query": "fractions"}))
            return Reply(message=Message.assistant(text="", calls=calls))
        if "r1" in results:
            recalled.extend(entry["text"] for entry in results["r1"]["entries"])
        posed = results["c1"]
        return Reply(message=Message.assistant(text=f"{posed['teach']} Question: {posed['question']}"))
    if not any(message.role() == TOOL for message in messages):  # the noter
        call = ToolCall(call_id="c1", name="record_progress", arguments={"note": "Covered fractions."})
        return Reply(message=Message.assistant(text="", calls=[call]))
    return Reply(message=Message.assistant(text="Well done today."))

4. The first turn: the run parks on the learner

The Launcher takes the harness, the model and three more test fakes from gvn.testing.fakes (Testing your harness): MemoryJournal keeps the journal in memory, RecordingOutput keeps what would be shown, and ManualClock moves only when moved. start drives the run until it has to wait. The conversation asks the learner with a request_input request, which every Launcher treats as external (answered from outside the process), so the run parks: it is saved in the journal, costing no process, until the learner's message arrives. pending() lists the requests the run waits on; origin() names the actor that asked (lesson-7/teaching.1: the first visit of stage teaching).

from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput
from gvn_domains.launcher import Launcher

launcher = Launcher(
    harness=tutor,
    model=FunctionModel(respond=tutoring_model),
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
waiting = asyncio.run(launcher.start(run_id="lesson-7", brief=lesson_brief))
turn = waiting.pending()[0]
print(waiting.status(), turn.kind().name(), turn.origin())
print(turn.payload()["text"])
print(recalled)
waiting request_input lesson-7/teaching.1
A fraction is part of a whole. Question: What is half of 1?
['Lesson 6 on fractions: Ada mixed up numerator and denominator.']

The tutor's recall found Ada's earlier lesson and not Grace's, although both entries match the query. The tool takes only a query; the scope it searches is the run context's "learner_memory", which the harness sets to learner_scope(brief["learner"]) when it builds each round's conversation (see What is enforced).

5. The learner answers, and an errand grades it

The learner's message is delivered with Launcher.reply, as an answered event. The answer is checked against the request it answers, and a message longer than 2,000 characters (MAX_UTTERANCE) is refused with a ValueError that changes nothing:

from gvn.harness.events import Event

try:
    asyncio.run(launcher.reply(
        run_id="lesson-7", request=turn, event=Event(name="answered", payload={"text": "1/2 " * 600})
    ))
except ValueError:
    print("refused; still", launcher.actor("lesson-7").state())
refused; still State('teaching')

A reply of a normal length is taken. The conversation's one turn is over, so the stage ends heard, the grading errand (a small actor that makes a fixed tool call with no model) calls check_answer with the learner's words as the answer, and the run goes back to teaching for the next round:

waiting = asyncio.run(launcher.reply(
    run_id="lesson-7", request=turn, event=Event(name="answered", payload={"text": "It is 1/2"})
))
turn = waiting.pending()[0]
print(turn.origin())
print(turn.payload()["text"])
lesson-7/teaching.2
Add fractions with like denominators. Question: What is 1/4 + 2/4?

The tutor moved on to step 2 because the run told it to. Each round's conversation ends after one turn, so the grading errand runs between two turns where the model cannot skip it, and the next round starts a new conversation with thread= the last round's thread. What the run knows and the learner must not touch (the round, the mark of the last answer, the suggested step) reaches the tutor in that round's instructions. A context budget whose one step summarises keeps what the tutor sees bounded: past 24 messages (about six rounds), all but the last 8 are replaced with a model-written summary (ContextBudget(reduce_over=24, steps=[Summarise(8, ...)], remember_dropped=True); see Context management). Both looping stages keep full records of only their latest visits (Host(retain=...)), so the run's stored state stays small too.

remember_dropped=True is what keeps a long lesson from losing what it summarises. Before the summary replaces the older messages, the tutor's conversation asks for them to be remembered (a remember request), and the harness's MemoryFulfiller writes them, as text, into the learner's scope, keyed by the request so that a repeat after a crash keeps nothing new (how the handover works). A memory that fails does not stop the lesson: the summary is made anyway, and the conversation's "reductions" counts it as "unremembered". This short lesson never reaches 24 messages, so nothing is handed over here:

print(len(memory.held(learner_scope("ada"))))
1

A chat server would run this loop until the run stops waiting. This shape is not run here because it needs a real channel to the learner:

# not runnable: the shape of a chat server's loop.
launcher = Launcher(
    harness=tutor, model=model, journal=journal, output=output, clock=clock,
    entitlement=lesson_entitlement,  # the application's rule for learners and teachers
)
result = await launcher.start(run_id="lesson-7", brief=brief)
while result.status() == "waiting":
    request = result.pending()[0]
    if request.kind().name() == "request_input":  # the tutor has spoken
        text, learner = await authenticated_learner_message(brief["learner"])
        answer = Event(name="answered", payload={"text": text})
        result = await launcher.reply(run_id="lesson-7", request=request, event=answer, by=learner)
    elif request.kind().name() == "request_approval":
        approved, teacher = await authenticated_teacher_decision(request)
        if approved:
            result = await launcher.approve(run_id="lesson-7", request=request, by=teacher)
        else:
            result = await launcher.deny(run_id="lesson-7", request=request, by=teacher)
    else:
        raise ValueError(f"Unexpected request: {request.kind().name()}")

The channel helpers return a Principal from the authenticated session. The application's entitlement rule checks whether that learner or teacher may answer the particular request.

6. Mastery, and a teacher signs it off

Mastery is the run's decision, not the model's: it is not one of the conversation's closings. The grading judge decides it from the marks. When the learner answers the second question right, two answers in a row are correct, the loop ends reached_mastery, and the noter is built with mastered: True in its run context. Recording mastery needs a teacher's approval, so the run waits again, this time on a person (Humans and interruption):

waiting = asyncio.run(launcher.reply(
    run_id="lesson-7", request=turn, event=Event(name="answered", payload={"text": "3/4"})
))
sign_off = waiting.pending()[0]
print(sign_off.kind().name(), sign_off.origin())
request_approval lesson-7/noting.1

The teacher approves, the note is recorded, and the run ends mastered. grade checks the finished run against the harness's evaluation, its statement of what a good run looks like (Replay and evaluation):

finished = asyncio.run(launcher.approve(run_id="lesson-7", request=sign_off))
print(finished.outcome().state(), gradebook.notes())
print(asyncio.run(launcher.grade(run_id="lesson-7")).passed())
State('mastered') [('N-1', 'ada', 'fractions', True)]
True

A practice note (no mastery) is cleared without a person. The tutor may close only to end the lesson early, which leads to a practice note, like a learner who left.

A lesson can also be cut short: the tutor's conversation ends overflowed when it no longer fits its model and nothing is left to summarise (see context management). The rounds before that still happened, so the run goes to a practice note (lesson_cut_short). The noter is told the lesson was cut short and to say so, and such a note never records mastery.

The grade is the harness's evaluation: finishes mastered or practised, nothing rejected, a mastery note ran only with a person's approval (Gated([RECORD_PROGRESS], when=claims_mastery), a check on the recorded run, see checking a safety rule; its when limits it to notes whose context says mastered), and the run took at most 9 events per allowed turn plus 8. A last check, ModelAsked, reads every model call the run recorded (the tutor's, the summariser's, the noter's) and fails the run if any model was given instructions that contain something the learner wrote.

What is enforced before any effect

The policy gives every call one of three verdicts: cleared (it runs), needs_approval (a person is asked first) or forbidden (it never runs). permitted(tool, origin, context, arguments=None), one rule set in the module, ties each tool, by identity, to one stage, and the policy and every tool use it: pose_question and recall only from teaching, check_answer only from grading, record_progress only from noting.

from gvn_domains.education.tutoring import RECORD_PROGRESS, permitted

context = {"learner": "ada", "topic": "fractions"}
noting = permitted(RECORD_PROGRESS, origin="lesson-7/noting.1", context=context)
teaching = permitted(RECORD_PROGRESS, origin="lesson-7/teaching.3", context=context)
print(noting)
print(teaching)
None
record_progress may be called only in the noting stage, not by 'lesson-7/teaching.3'

None means allowed; anything else is the reason for a refusal.

Learner text is untrusted. It reaches a model only as the learner's own messages in the conversation, in the summaries made of them, which are as untrusted as the text they summarise, and, from earlier lessons, in what recall returns to the tutor as a tool result. It never routes (the judges read only final states, tool results and marks), never enters a run context or a model's instructions, and never reaches the noter. It cannot:

  • change the lesson's scope: no tool takes a topic; the topic comes from the run context, and pose_question takes only a step number;
  • grade its own answers: marks come only from check_answer, made by an errand with the posed step in its context and the learner's words as the answer to check. Mastery is decided by the grading judge from those marks and handed to the noter as context;
  • trigger tools: each tool is tied to one stage, so even a manipulated tutor cannot grade or record;
  • reach another learner's memory: recall takes only a query. The scope it searches, and the one the summaries' losses go to, is the run context's "learner_memory" (LEARNER_MEMORY = MemoryScope.from_context("learner_memory")), which harness code sets to learner_scope(brief["learner"]), that is "tutoring_session/learner/<learner>".

That scope is trusted because nothing the model or the learner says can reach it. The learner id comes from the brief, given by whoever starts the run and checked by the brief's schema (an id cannot contain /, so it cannot name a wider or another learner's scope), and the run context is written only by harness code (Why the scope is trusted). So one learner's lessons recall each other and never another learner's. What is recalled is still untrusted: it is mostly the learner's own words, it reaches the tutor as a tool result, never as an instruction, and the tutor's instructions say to treat it as notes.

The one side effect, record_progress, is keyed "<session>#progress": one note per session, across crashes and interrupts.

What this harness uses from gvn

The tutoring session is the package's example of a long conversation with a person. Each round of teaching is one turn of a Conversation actor, which carries the thread from round to round under a context budget, and the learner's answer arrives through Launcher.reply, as the answer to an Inquiry (an actor that asks a person a question and parks until they answer) does. retain bounds the stored history of the looping stages. Measured on a 50-turn conversation, the stored snapshots take 73 KB. The domains overview lists these parts of gvn across all the harnesses.

Memory and the stored session

This harness uses the context budget and the memory. It keeps its one-turn rounds, because the grading errand must run between two turns where the model cannot skip it, and so it passes what the run knows through each round's instructions.

  • Recall. A later lesson gets what earlier lessons' summaries dropped when the tutor calls recall. What is kept is what a reduction dropped, as text; the progress note goes to Records. The summary that bounds a long session is model-written content, as untrusted as the text it summarises.
  • Storage. retain shrinks the stored history of the looping stages: each trimmed visit keeps its state and name.

Its own tests are in packages/gvn-domains/tests/test_dom_education_tutoring.py.

Recap

  • Each round is one turn of a conversation; the run parks on the learner between turns.
  • An errand grades between turns, so the model cannot skip or fake the grading.
  • Mastery is decided by the run from the marks, and a teacher approves recording it.
  • Learner text never routes, never reaches a run context, and cannot call a tool outside its stage.
  • What a summary drops goes to the learner's memory; a later lesson's tutor can recall it, from that learner's scope only, which harness code sets from the brief.

Next: Finance, where deadlines race people and outside systems.