langchain-agent-hints
English | 简体中文
Per-request serving-intent hints for LangChain agents, as middleware.
langchain-agent-hints makes your agent announce how it is running to the
downstream inference layer. On every main-line model request it attaches an
AgentHint object — session identity, lifecycle state, priority, cache
control — as the base64url-encoded X-Agent-Hint HTTP header, and reports
state transitions (running / pause / resume / finalize) through an
out-of-band event sink. The serving side (gateway, router, inference engine)
consumes these signals for scheduling: session-aware KV-cache placement,
priority scheduling, approval-pending demotion, and so on.
The agent signals; the engine decides. The middleware is read-only with
respect to the model-visible request: it never touches messages or the system
prompt — it only extends ModelRequest.model_settings with the transport
header, which reaches OpenAI-compatible chat models as per-request
extra_headers.
How it fits LangChain
Both middlewares subclass the public
AgentMiddleware
base class, so they work anywhere user middleware is accepted: LangChain's
create_agent, and deepagents' create_deep_agent (where user middleware is
placed after the core stack). No harness is modified and no private APIs are
imported.
AgentHintsMiddleware— builds one hint perwrap_model_calland injects theX-Agent-Hintheader (async:awrap_model_call).AgentStatusEventsMiddleware— reports lifecycle transitions to a pluggable sink viawrap_model_call/after_model/wrap_tool_call/after_agentand their async counterparts.
Session identity comes from the LangGraph runtime config:
configurable.thread_id is the session id; deepagents subagent runs
(ls_agent_type == "subagent") self-identify as
{thread_id}:{agent_name} with a parent_session_id back-reference and
derivation: {relation: spawn, join: sync} (deepagents task subagents are
foreground-blocking).
Install
pip install langchain-agent-hints
Requires Python ≥ 3.11 and langchain>=1.4,<2.0. Source install also works:
pip install git+https://github.com/evan7ang/langchain-agent-hints.git.
Quickstart
Plain create_agent
from pathlib import Path
from langchain.agents import create_agent
from langchain_agent_hints import (
AgentHintsMiddleware,
AgentStatusEventsMiddleware,
JsonlStatusEventSink,
)
agent = create_agent(
model="openai:gpt-4o-mini",
tools=[...],
middleware=[
AgentHintsMiddleware(agent_type="my-agent"),
AgentStatusEventsMiddleware(
sink=JsonlStatusEventSink(Path("status-events.jsonl")),
),
],
)
result = agent.invoke(
{"messages": [("user", "Summarize this quarter.")]},
config={"configurable": {"thread_id": "session-42"}}, # identity is mandatory
)
Requests then carry a header such as (base64url-decoded for readability):
{
"session": {"session_id": "session-42", "parent_session_id": null,
"agent_type": "my-agent", "call_index": 3, "epoch": 0,
"state": "append"},
"agent_status": {"state": "running", "state_since_ms": 1730000000000},
"priority": {"level": 3, "reason": "user_waiting"},
"priority_control": {"priority": {"level": 3, "reason": "user_waiting"}},
"cache_control": {"type": "ephemeral", "ttl_s": 240, "msg_offset": 2,
"range": {"end": 2, "unit": "message"}}
}
Lifecycle verbs do not ride on ordinary requests. Pass a
HttpManageRequestClient to emit separate manage requests (session +
context_management{manage_request: true, edits: [...]} with a placeholder
body); the middleware sends resume for adopted/restored sessions and
compact after a rewrite, and compositions call send_manage("pause"|"stop", ...) from their own leave/archive hooks.
deepagents
from deepagents import create_deep_agent
from langchain_agent_hints import AgentHintsMiddleware, AgentStatusEventsMiddleware
agent = create_deep_agent(
model="openai:gpt-4o-mini",
tools=[...],
middleware=[
AgentHintsMiddleware(agent_type="my-agent"),
AgentStatusEventsMiddleware(sink=my_sink, interrupt_tools=INTERRUPT_ON.keys()),
],
)
A runnable version lives in examples/deepagents_quickstart.py —
it accepts AGENT_HINTS_EXAMPLE_MODEL (model string override) and
AGENT_HINTS_STATUS_SINK (event file), and works against any OpenAI-compatible
gateway via OPENAI_BASE_URL.
What gets sent
| Block | Content | Source |
|---|---|---|
session |
session_id, parent_session_id (explicit null on roots), agent_type, call_index, epoch, state (start/append), optional derivation |
thread_id, constructor options, persistent message history |
context_management |
manage requests only: manage_request: true + exactly one edit (pause → offload, resume → prefetch, stop/compact → evict); absent from every ordinary request |
build_manage_hint via HttpManageRequestClient |
agent_status |
wire snapshot: running by default, pause while parked (including a tool wait), resume on the first request after a release |
middleware observation + shared RunSignals |
priority / priority_control |
level + audit reason in both the legacy top-level block and the canonical priority_control.priority. Only user_waiting is 3; critical_path/background are 1. Auto: human message / approval resume → 3/user_waiting; tool continuation/subagent → 1/critical_path; run_mode="batch" → 1/background |
request trigger + shared RunSignals; explicit/service values normalized by reason |
cache_control |
one ephemeral object with an explicit TTL (clamp(gap*2, 60, 3600)); msg_offset = range.end = logical input count ([system?] + messages) |
per-request derivation from the cache-control guide (next-tool p90 → last interval → 300 s fallback; omitted below 128 tokens, on prefix rewrite, or on a model/tool-set change) |
prediction |
measured serving estimates: latency_ms, output_tokens, interval_ms, remaining_calls, remaining_time_ms, next_action |
in-plugin observation engine (rolling p90); omitted until enough samples |
strict_priority |
reserved for a trusted control plane | constructor injection only; ordinary agents never set it |
Full wire contract: docs/PROTOCOL.md.
Key emission rules:
- No
thread_id→ no hint, no status events (identity is mandatory). call_indexis a session high-water counter seeded from the checkpointer-persisted message history (1 + count(AIMessage)); a compaction rewrite does not rewind it.epochbumps when the message prefix is rewritten (summarization signal); the next ordinary request carriesepoch + 1and suppressescache_controlfor that round.session.stateon an ordinary request is onlystart(a root session's first call) orappend(everything else). Lifecycle verbs (pause/resume/stop/compact) are emitted as separate manage requests, never inlined.- Only requests flowing through
wrap_model_callare hinted; auxiliary model calls that bypass the middleware chain are not. For an auxiliary call that does flow through the chain (e.g. a compaction summary), wrap it insuppress_hints(): no header and no status transition. priorityandcache_controlare derived from real run facts by default ("auto"); pass an explicitPriorityHint/ tuple to pin them, orNoneto omit the field.cache_controlis re-declared on every request (the consumer never renews TTL).
Status events
AgentStatusEventsMiddleware reports transitions as they happen, in protocol
shape {"seq": N, "session": {...}, "agent_status": {...}}:
Wire states follow AGENT_STATUS_STATE_DESIGN.md v1.0: four values
(running / pause / resume / finalize). Internal tool and suspend
fold into pause; resume is the one-shot release edge after a pause
(approval or tool result).
| Hook | Event (wire state) | Dedup |
|---|---|---|
wrap_model_call entry |
running |
only if last state ≠ running |
| model response with gated tools | pause (human_approval, gated tools listed) |
every gated response |
| approval/tool release | resume (one-shot; the next header also reports resume) |
once per release |
wrap_tool_call entry |
pause (reason: await_tool/join_barrier, tools listed) |
every tool call |
wrap_tool_call exit |
resume |
only when the last outstanding tool finishes |
suspend threshold (suspend_after_s) |
pause (reason: checkpoint) |
once while parked |
after_agent |
finalize |
fires only on real completion (an approval pause suspends without finalize) |
With subagent_tools={"task"} (the default) a delegation call is reported as
tool with reason="join_barrier", the child agent name (agent:<type>) and
child_session_id ({thread_id}:{type}). Pass suspend_after_s=N to report
suspend (reason="checkpoint") when an approval pause outlives N seconds,
and expected_resume_s=N to attach the wait estimate to the pause event.
Sinks implement the one-method StatusEventSink protocol; JsonlStatusEventSink
persists to a JSONL file and HttpStatusEventSink posts to a gateway endpoint,
both with per-session sequence numbers and retry-then-drop semantics. The sink
interface is synchronous — async hooks call it inline, so use a buffered sink
for slow transports.
Serving estimates (prediction)
Unlike Dify (where platform boundaries force an out-of-band hint service), the LangChain hooks expose everything needed to measure in-process. The observation engine records, per agent type, a bounded rolling window of:
- model-call latency (measured around the handler) and output tokens
(
usage_metadata), - the inter-call interval (from the previous call's end to this call's start),
- calls per session and session duration (closed in
after_agent), - tool durations, and the model→tool / model→finalize transition counts (including which tool follows a model call).
When a hint is built, one value per metric is selected (nearest-rank quantile,
default p90) and emitted as a partial prediction object. A metric is omitted
until it has min_samples observations (default 3), so a fresh process sends
no estimates rather than invented ones.
from langchain_agent_hints import AgentHintsMiddleware, ObservationOptions
AgentHintsMiddleware(
agent_type="my-agent",
observation=ObservationOptions(min_samples=5, quantile=0.9),
# Optional static overrides (per field, explicit values win):
# prediction=PredictionHint(output_tokens=512),
)
Measurement is advisory and in-process: ObservationOptions(enabled=False)
turns it off, and stats reset on restart unless persist_path points at a JSON
file for aggregate carry-over.
Disabling
Drop the middlewares from the composition — hints and events are advisory signals and are never required for the agent to function. A common composition-level pattern is an environment kill switch:
import os
from langchain_agent_hints import AgentHintsMiddleware, AgentStatusEventsMiddleware
if os.environ.get("AGENT_HINTS_DISABLE", "").strip().lower() not in {"1", "true", "yes"}:
middleware = [
AgentHintsMiddleware(agent_type="my-agent"),
AgentStatusEventsMiddleware(
sink=JsonlStatusEventSink(
os.environ.get("AGENT_HINTS_STATUS_SINK", "status-events.jsonl")
),
),
]
else:
middleware = []
Compatibility
Verified against langchain 1.4.1 / langchain-core 1.6.4 /
deepagents 0.7.15 / langgraph memory checkpointing. Known limitations and
measured hook-timing facts: docs/COMPATIBILITY.md.
Development
python -m venv .venv && source .venv/bin/activate
pip install -e '.[test,lint]'
pytest # keyless: fake models + a local capture stub
ruff check .
ruff format --check .
mypy # strict, src only
CI runs the same suite on Python 3.11–3.13.
Roadmap
- Publish to PyPI and list under the LangChain middleware integrations.
- Async-friendly (buffered / async) sink interface.
- Cross-process/cross-replica observation aggregation (the in-plugin engine is
process-local today;
persist_pathcarries aggregates across restarts).
License
Metadata
Release files for langchain-agent-hints 0.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| langchain_agent_hints-0.5.0.tar.gz | 76.3 kB | With provenance | Details for langchain_agent_hints-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| langchain_agent_hints-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for langchain_agent_hints-0.5.0-py3-none-any.whl |
Total release size: 120.5 kB
Release files / langchain_agent_hints-0.5.0.tar.gz
| Download URL | langchain_agent_hints-0.5.0.tar.gz |
|---|---|
| Size | 76.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
cddf4e3688b889694ec1514e8154af57a1ba60dcb9f94de5fa50bd1ecd4c73e4
|
|
BLAKE2b-256 checksum How to use checksums |
c23b7c185014c5c3df29cd3d5d94b256e6de45655ef14279a990646003b019bb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.
Transparency logRelease files / langchain_agent_hints-0.5.0-py3-none-any.whl
| Download URL | langchain_agent_hints-0.5.0-py3-none-any.whl |
|---|---|
| Size | 44.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
6e0ad8b86240a0e4532861948e16fca9b83cca746cffe687582c1a739182766a
|
|
BLAKE2b-256 checksum How to use checksums |
b6392e91b1ff67059fe362e4d57128a9d7a83f2ff668e7b2a208182c50d0e8e0
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.
Transparency logSecurity for langchain-agent-hints 0.5.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for langchain_agent_hints-0.5.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.