Skip to content

Answers

An answer is a one-click explanation of one thing in your app: "explain this event", "summarise this invoice". The user never types a prompt. The server owns the prompt, the tools and the context; the client names a skill and a subject id, and gets back either the answer already stored for it or a new run's AG-UI event stream.

AnswersServer is a separate mount, beside your chat endpoint, not a mode of it:

from django.urls import path
from django_spec_agents import ScopedConversationStore

from django_ag_ui import AnswersServer, AnswerSkill, AnswerSubject


def event_subject(request, subject_id):
    event = Event.objects.visible_to(request.user).filter(pk=subject_id).first()
    if event is None:
        return None
    return AnswerSubject(event.title, event.updated_at.isoformat(), context=event.notes)


answers = AnswersServer(
    read_only_registry,
    skills=[AnswerSkill("explain-event", "Explain event {label}.", event_subject)],
    conversation_store=ScopedConversationStore(store, scope="answers"),
    run_store=run_store,
    read_only_tools=["lookup_event"],
)

urlpatterns = [path("answers/", answers.urls)]

The skill and its subject

AnswerSkill(name, prompt, subject) serves answers/<name>/. subject(request, subject_id) runs off the event loop and returns an AnswerSubject(label, version, context=None), or None:

  • None answers 404, on GET and POST alike. It is your permission check: return None for anything the caller may not see.
  • label replaces {label} in the prompt. The prompt takes your canonical label, never the string the client sent.
  • version is resolved on the server, from your data. A changed version is a new answer; the client never sends one.
  • context, when given, reaches the model as fenced untrusted context, the channel a chat run's client context takes (RUN_CONTEXT), never as instructions.

The routes

The mount serves only these, and no free-form endpoint: there is no "" POST, resume/ or fork/, so a client never sends a RunAgentInput, and with it no tools, messages, state or context.

  • GET answers/<skill>/?subject=<id> answers 200 {"thread_id", "status", "text", "generated_at", "degraded", "can_regenerate"} for the current answer, or 404. status is "done" (the last assistant message is text; generated_at is when the run's last event was logged, null once the log is pruned) or "running". degraded is true for a shared answer a failed tool call shaped, and false otherwise. can_regenerate says whether this reader may send regenerate: true.
  • POST answers/<skill>/ with {"subject": "<id>", "regenerate": false} answers the stored answer, as the GET does, when it is current. Otherwise it streams a new run's AG-UI events. While the answer runs, a POST answers 409 with its thread_id.
  • GET answers/<skill>/events/?subject=<id>&after=<n> follows the subject's current run, replayed then tailed, as threads/<id>/events/ does. It runs the same subject check and key derivation as the GET, and answers 404 when there is no run. It serves per-principal and shared answers alike.
  • GET threads/<thread_id>/events/ follows a running per-principal answer, as on an AGUIServer (see Detached and headless runs). It never serves a shared answer.

regenerate: true deletes the stored answer and runs it again under the same key. A skill's can_regenerate(request) decides who may: when it returns false, the POST answers 403 and the stored answer stays. Without one, a per-principal skill allows it.

The key

An answer's thread id is derived on the server:

"ans-" + sha256(json([owner_id, skill, prompt revision, subject id, version]))[:40]
  • The owner keeps two users off one thread id in the run store, the step log and the events/ replay: answers are per user. Another user's GET is a 404, and their POST never waits on your run.
  • The prompt revision is a hash of the skill's prompt, so editing the prompt makes every stored answer of that skill stale.
  • JSON keeps the fields apart: subject 1 at version 23 never meets subject 12 at version 3.
  • It is 44 characters with no /, so it fits a 255-character thread id behind any scope prefix. Each version is its own thread; older ones stay until you prune them.

What a run can do

Every POST builds its run on the server: one user message from the prompt, no client tools. The run sees only read-only tools: those whose annotations.readOnlyHint is true, and the names in read_only_tools=. Anything that writes belongs in the full chat.

A selector carries the hint whether it is reached through service_specs= or mcp_server=, so it needs no naming. Name a tool in read_only_tools= only when it reads and its source declares nothing.

An answer run has no one to approve a call, so with TOOL_GUARD on:

  • Naming a tool the guard gates by name is refused at construction: a registry @tool(destructive=True), or a name in REQUIRE_APPROVAL, raises ImproperlyConfigured, unless EXEMPT names it.
  • Any other gated call fails at run time: a tool whose definition declares a mutation, such as a ServiceSpec through mcp_server= (listed per user, per request), is only known when the run lists it, so its call returns a denied tool result ("An answer run cannot ask for approval, so this call did not run.") and the run goes on to answer without it. An answer run never waits on an approval.

throttle= applies to every POST, since each one may be a paid run; a GET is never throttled.

What it refuses

  • run_store= and conversation_store= are required: the first gives one run per answer (the 409) and the events/ replay, the second holds the answer.
  • Requests must be authenticated: an answer belongs to its owner.
  • connectors=, step_store= and firing_queue= are refused at construction. Every connector call asks the user's approval, so the run would park on it, and this mount has no resume/ route to answer it. A step store exists to resume and fork runs, and this mount serves neither. A firing queue hands a run to a worker to start later, and an answer is started by its POST. The events/ replay needs only the run store.

Shared answers

A per-principal answer is paid for once per reader. A shared answer is stored once per skill, subject and version, and read by every reader your subject admits. A skill is shared when it has a shared_subject:

def public_event_subject(subject_id):
    event = Event.objects.filter(pk=subject_id).first()
    if event is None:
        return None
    return AnswerSubject(
        event.title, event.updated_at.isoformat(), context=event.agenda, id=f"event:{event.pk}"
    )


answers = AnswersServer(
    read_only_registry,
    id="answers",
    skills=[
        AnswerSkill(
            "explain-event",
            "Explain event {label}.",
            subject=event_subject,
            shared_subject=public_event_subject,
            can_regenerate=lambda request: request.user.has_perm("board.change_event"),
        )
    ],
    conversation_store=store,
    run_store=run_store,
)
  • subject(request, subject_id) is the gate. It runs under the reader on every GET, POST and answers/<skill>/events/ request. None answers 404, and nothing else of its result is used.
  • shared_subject(subject_id) is what everyone may be told. It takes no request, so one reader's view of the subject never reaches another. Its label, version and context build the prompt and the key, and its id, the subject's canonical id, takes the client's string's place in the key. It must set id: a shared AnswerSubject without one answers 500 (ImproperlyConfigured). None answers 404.
  • The mount needs id=, refused at construction without it (and with a : in it). The shared rows are owned by shared:<mount id>, or shared:<mount id>:<pk> with shared_user. Every store sees that owner: the answer, the run claim and the run log.
  • The conversation store must be scoped by owner. DjangoSessionConversationStore keeps rows in the first reader's session, where no other reader finds them, and is refused at construction. A store you wrap (ScopedConversationStore) is not inspected: scope it by owner, not by session.

What a shared run's tools see

The run's tools see a fresh request: no session, no cookies, no auth headers, only the host, scheme, path and method. Its user, and ctx.deps.user, is AnonymousUser. This holds for every tool the run keeps, the mcp_server= bridge and service_specs= included. Running as the reader is what would leak, so a tool that needs a user fails closed.

When your tools need one, pass shared_user=, a callable(request) -> User resolved per request, so it may vary by tenant. Its account replaces AnonymousUser for every tool. It answers 500 (ImproperlyConfigured) unless it is active, not staff, not a superuser and has no usable password, so no person can sign in as it.

A shared run keeps only tools whose annotations.readOnlyHint is true. read_only_tools= names do not reach it: that list is your assertion about per-principal runs only. So registry @tools, and toolset functions that declare no hint, never reach a shared run; selectors reached through service_specs= or mcp_server= carry the hint. The run's own get_client_context tool is kept by name, so a mount with a shared skill refuses a registry, MCP or spec tool of that name, or a function toolset in toolsets= that offers one, at construction. A wrapped toolset is not inspected: do not name a host tool get_client_context.

Spend follows ctx.deps.user: a per-user spend limit counts anonymous shared runs under its anonymous scope, and shared_user runs under that account. The throttle applies per reader on POST.

Degraded answers

Every shared run that finishes is stored, so each version of each subject costs one run, however many of its tool calls fail. A run that errors out, times out or is cancelled serves no answer: whatever it streamed before it stopped is never served as done. A tool call fails when it raised, the guard refused it, or it returned an error. Such an answer is kept, and every body for it carries degraded: true, so a page that cares can show a note.

There is no automatic retry, since every retry would be another paid run. A degraded answer stays until a new version or a changed prompt replaces it, or until a reader whom can_regenerate admits regenerates it after you fix the cause. Without can_regenerate, regenerate on a shared skill answers 403.

A degraded answer usually means a tool that fails under the shared identity. The audit entry names it: move that data into shared_subject's context, or turn on shared_user.

Accounting

Each shared run records one AuditEvent with tool_name="answers.shared_run". Its arguments_repr is JSON naming the skill, the canonical subject_id, the key, the reader whose request triggered the run, degraded and the failed_tools. A run that finished has success=True; one that errored, and so stored no answer, success=False. Older versions stay until a prune, as per-principal answers do.

The residual risk

A prompt injection in the subject's own content persists for every reader of that version. It is bounded:

  • the context reaches the model fenced as untrusted;
  • no tool writes;
  • reads are anonymous, or limited to the service account;
  • the web component's markdown renderer drops images, so an answer cannot beacon its readers, but links remain.

can_regenerate lets you clear a bad answer, and a new version replaces it.