Give instruction parts a stable `InstructionPart.id`

Merged
DO
3mo ago
+2980-265

Instructions reach the model as a list of InstructionParts, but the parts carry no identity. A consumer reading ModelRequestParameters.instruction_parts sees opaque strings it can only address by index — unstable, since it depends on which toolsets are active and the parts get sorted — or by matching their text, which breaks the moment anyone rewords a toolset. Neither is something you can persist configuration against.

This adds a stable, framework-populated key.

Closes #7595.

The rule

A resolved id is an InstructionId: a source addressing everything that source contributes, plus an optional name addressing one part the author named within it.

InstructionId(ToolsetInstructionSource('weather'), name='limits')

The source is a closed union — AgentInstructionSource(), ToolsetInstructionSource(id), CapabilityInstructionSource(id) — so the class is the discriminator and a consumer compares values instead of parsing strings. Ids render and serialize to the flat form, which is what you persist configuration against:

str(id)Addresses
agentthe agent's own literal instructions
toolset:<id>everything that toolset contributes
capability:<id>everything that capability contributes
agent:<name>one @agent.instructions(name=...) part
capability:<id>:<name>one @capability.instructions(name=...) part

A name sits beneath a source, so it can never collide with a source's own key. And a source keeps its meaning permanently — giving more sources names later can only add keys, never change what an existing one matches.

You declare a name; the framework issues an id. InstructionPart.name is the string you wrote, InstructionPart.id is the InstructionId built from it and the identity of the source that contributed the part — so id is typed InstructionId | None and nothing has to guess at a flat string with startswith. A part whose source has no identity of its own keeps its name and gets no id, which says plainly that nothing addresses it. Names cannot contain :, and 'agent' is reserved, because those are the only two ways a name could spell a key by itself.

@agent.instructions and @capability.instructions take name=, with the same bare/parameterized overload shape as @agent.toolset.

What stays unidentified, deliberately

Visible, but not addressable:

  • Parts from callables passed to Agent(instructions=...) or run(instructions=...), and bare @agent.instructions functions. A bare function must not inherit agent: several can exist, and one shared key would make them individually unaddressable forever. Declare a name if you need one to be addressable.

  • Sources with no id of their own.

  • Parts a source doesn't name. They share their source key with their siblings, so addressing capability:budget reaches everything that capability says — parts computed per request included — and can't single one out.

    Naming is the way out of that, and it works from every source: return an InstructionPart carrying a name (name='limits' → toolset:weather:limits) from a toolset's or capability's get_instructions, or pass one to Agent(instructions=...) / Capability(instructions=...); a function is named where it's registered, with @agent.instructions(name=...) or @capability.instructions(name=...). You name the part relative to what you own and the framework qualifies it against your source, so you never repeat your own identity and can't claim someone else's key.

    A name on a source that has no id of its own has nothing to qualify against, so the part keeps its name and its id stays None. The same goes for a name on instructions passed to a single run.

These limits are documented next to the ids in docs/agent.md, and on the toolset and capability pages, rather than as footnotes.

Behaviour changes

Seven, all user-visible. None is covered by an existing bullet in the version policy, so the classification is worth an explicit look:

  1. Literal parts are separated by a blank line instead of a single newline — this is #7595. Every literal part was joined with '\n' while rendered parts were already joined with '\n\n', so as soon as more than one source contributed a literal, independently authored parts collapsed into one paragraph. Agent(instructions=['a', 'b']) rendered 'a\nb' and now renders 'a\n\nb', and the issue's own case — an agent prompt plus two capabilities — goes from 'Head prompt ends here.\nRule A applies.\nRule B applies.' to a blank line between each. Whitespace-only contributions are dropped rather than leaving a stray blank line.

    The fix is structural rather than a changed separator: literal = '\n'.join(literal_parts) is gone, because every literal source now contributes its own InstructionPart and InstructionPart.join applies uniformly. Capability authors working around this by opening each part with a leading '\n' (the workaround #7595 describes) should drop it — it now yields a double blank line.

    Anyone with more than one literal instruction source gets a one-time prompt change and a prompt-cache prefix bust on upgrade. There is no opt-in flag: the single-newline rendering is the reported bug, and a flag whose only purpose is to keep it would be permanent surface for no benefit.

  2. ModelRequest.instructions is recomputed from the parts after before_model_request. A capability rewriting the parts in that hook previously changed what the model received while message history and OTel kept the pre-rewrite text — the span attribute already read the parts, so history was the odd one out. Byte-identical when no hook touches them. Applies to the resume path too. Documented precedence: the parts are the source of truth; assigning to the message's instructions inside the hook is not propagated back and does not reach the model.

  3. Part boundaries shift. (Where the split falls between two literal sources this is what produces 1's blank line; elsewhere the rendered text is unchanged.) A capability's instructions are their own InstructionPart rather than folded into the agent's literal, and run(instructions=...) forms its own part. Parts are grouped into a part by their id, so an unidentified source contributes a part per part rather than one fused part — the same as two unidentified sources beside each other. All of these are static, so prompt-cache boundary placement is unchanged.

  4. Two toolsets sharing an id are rejected when they both contribute instructions. toolset:<id> addresses instruction parts on every agent now, so two toolsets contributing under one key leave an application unable to tell whose text it is addressing. Raised as the parts are keyed, not when the agent is built: a shared id costs nothing until both toolsets actually contribute a part, and most never do. Durable execution keeps its own stricter guard, which doesn't wait for instructions — an id names a toolset's activities whether or not it says anything to the model.

  5. ModelRequestContext.model_id and .streaming become ordinary defaulted fields, so they appear in the constructor signature where they previously did not. This is a bug fix, not a convenience — see below.

  6. A capability id containing a colon is rejected at construction. : is the delimiter a declared segment is appended with, so an id carrying one cannot be represented unambiguously in a key. main accepted anything, so an existing Capability(id='openai:remote') — plausible for an id mirroring provider naming — now raises a UserError from Agent(...). Toolset ids get the same rule, but only where the id is actually turned into an instruction key (see 4), so a colon in a toolset id that contributes no instructions still works.

  7. Capability id uniqueness now covers a container that overrides get_instructions. main validates the flattened capability leaves; a CombinedCapability subclass overriding get_instructions is retained as a contributor in its own right and never appears in that list, so its id went unchecked. It could therefore share one with a sibling — distinct leaves, colliding container — and capability:<id> would address parts from both owners at once. That configuration constructed fine on main and now raises. Checked at construction, after for_agent, and on the tree a run resolves to, since for_run can hand back an id construction never saw.

replace() on a request context silently dropped two fields

Found while building the first real consumer of these ids. Returning a modified ModelRequestContext is the documented way for a before_model_request hook to change a request, and dataclasses.replace is how you write that — but replace() re-initializes init=False fields to their defaults, and the agent graph sets model_id and streaming on the context immediately before calling the hook. So any hook that copied its context zeroed both, with no error. Reproduced on a streamed run:

return request_context           in  streaming=True   out streaming=True
replace(request_context, ...)    in  streaming=True   out streaming=False

Not hypothetical: tests/models/test_streamed_continuation.py has a capability doing exactly this, and _instrumentation.py does it in the framework itself (harmless there — it only reads .messages back). Elsewhere it isn't harmless: a lost streaming flag misreports the request mode to every later hook, and a lost model_id costs a durable-execution worker the selection token it re-resolves an aliased model from.

Both fields are now ordinary defaulted fields, so replace() carries them. They are still set by the graph rather than by a caller — passing either to a fresh context is not meaningful, and the docstring says so.

This is folded in here rather than split out because this PR already changes what a before_model_request hook can do with a request context: it made ModelRequest.instructions recompute from the parts after that hook, which is what makes rewriting them in a hook worth doing at all.

'name': None and 'id': None now appear in serialized InstructionParts, consistent with other optional fields on message parts (ToolDefinition.capability_id sits in the same dumped dict). Payloads without the fields still validate, and an id whose namespace a future version introduces reads back as None rather than failing the message it arrived on.

Notes

Instruction collection is one pass. Each toolset answers _collect_instruction_contributions for itself — a leaf normalizes its own get_instructions() result under its id, a wrapper delegates to what it wraps, and a combined toolset gathers its children concurrently — and one caller applies the duplicate-id rule over the result. A wrapper contributing under the toolset it wraps is what keeps a capability-contributed MCP server addressable rather than arriving anonymous through CapabilityOwnedToolset. A wrapper that overrides get_instructions usually hands back what it wraps, keys and all, so those keys have to survive the trip out — which ones qualify is read off the wrapped toolsets rather than off the shape of the id, so a wrapper relays only keys that are actually below it and can neither mint one for a toolset it doesn't wrap nor lose one by re-resolving it beneath its own. An id a toolset sets itself always wins. Declared return annotations stay at the base's wide type so third-party WrapperToolset subclasses don't break.

The same collapse happened on the authoring side: SourcedInstruction, DeclaredInstruction and SourcedInstructionRunner became one lazy SourcedInstruction, and the _collect_instructions / _collect_own_instructions / source_instructions / prepare_instructions stack went with them. Identity is assigned once where a part is authored and interpreted once at request assembly, instead of at each composition point.

Designed with @DouweM; #7595 was filed independently while this was open and reports behaviour change 1 as a bug, which is what settles the prompt-bytes question it raised.

Checklist

  • Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
  • No breaking changes in accordance with the version policy — left unticked on purpose: see the seven behaviour changes above.
  • PR title is fit for the release changelog.