TypeSafeClassifier exposes these decisions as a LangChain Runnable, so you can invoke, batch, or compose them with other runnables. It accepts strings, structured JSON, and LangChain message objects, and records traces and token usage in LangSmith. Use it for focused decisions such as routing a request, choosing a model, or checking whether a tool call is safe to run.
Use TypeSafe decisions in LangChain middleware to control create_agent behavior at specific lifecycle points, including with custom middleware that classifies agent state. See Agent middleware for examples.
Setup
Optional: Set
TYPESAFE_BASE_URL to use a compatible gateway, test server, or private deployment. The default is https://api.typesafe.ai.Quickstart
ConfigureTypeSafeClassifier with a fixed set of named questions. Questions that share state are evaluated independently and in parallel in one request:
nouls, choices, and scores. The response also carries the model that answered, token usage, and the TypeSafe request_id.
State can be a string, a JSON object or array, or LangChain messages. A BaseMessage or a sequence of messages is converted to role/content JSON, including when nested inside a larger object.
Decision types
Each question is one of three primitives:Noul is the only one without a confidence, since the probability is the answer. Use Score rather than a Noul for a spectrum: a Noul of 0.5 means an even split between yes and no, not “medium”.
Agent middleware
The package includes two experimental middleware that put the classifier on an agent’s decision points. Import them fromlangchain_typesafe.experimental.middleware.
The middleware are experimental and require
langchain-typesafe[experimental]. Their APIs may change without notice.Model routing
Classifies the latest human message across your named models and uses the selected one for every model call in the run. EachModelChoice pairs a model with the criterion for picking it:
Tool-risk gating
Asks for the probability that a tool call is risky or insufficiently authorized. Calls that are determined risky return an errorToolMessage instead of running the tool. Only the tools you list are classified. Pass their names or tool objects:
instructions, or pass criteria=NoulCriteria(true=..., false=...), to describe risk for your own tools.
Custom middleware
TypeSafeClassifier accepts LangChain message objects directly, so a custom middleware hook can classify an agent’s conversation state without converting it first. This example classifies the conversation once at the start of each run and stores the complete ChoiceAnswer in agent state:
before_model to reclassify after each tool result, or wrap_tool_call to classify a proposed action. See Custom middleware for all hooks and state patterns.
Tracing
TypeSafe classifications are traced in LangSmith, so you can inspect decisions, token usage, and spend alongside the rest of your agent.See also
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

