This release is a pre-release and may not be stable for production use.
langchain-typesafe
Installation
uv add langchain-typesafe
Set the TYPESAFE_API_KEY environment variable before making requests.
Usage
TypeSafeClassifier is a LangChain Runnable for probabilistic classification and scoring with TypeSafe.
from langchain_typesafe import Choice, Noul, Score, TypeSafeClassifier
classifier = TypeSafeClassifier()
result = classifier.invoke(
{
"state": "Stripe has failed to connect for three days. Help ASAP.",
"questions": {
"department": Choice(
instructions="Which team should handle this?",
criteria={
"billing": "Payment or subscription issues",
"technical": "Product or integration issues",
},
),
"urgent": Noul(instructions="Does this message express urgency?"),
"frustration": Score(
instructions="How frustrated does the customer appear?",
criteria=["calm", "frustrated", "angry"],
),
},
}
)
print(result.choices["department"].choice)
print(result.nouls["urgent"].noul)
print(result.scores["frustration"].score)
Pass a complete ClassifierRequest mapping to invoke or ainvoke. Keeping both
state and questions in the Runnable input makes the complete classification request
available to composition, batching, callbacks, and tracing. Use
await classifier.ainvoke(...) for asynchronous applications:
from langchain_typesafe import ClassifierRequest
request: ClassifierRequest = {
"state": "Stripe has failed to connect for three days. Help ASAP.",
"questions": {"urgent": Noul(instructions="Is this urgent?")},
}
result = classifier.invoke(request)
Experimental middleware
Install the experimental extra to use TypeSafe-powered agent middleware. APIs under langchain_typesafe.experimental may change without notice.
uv add "langchain-typesafe[experimental]"
ModelRouterMiddleware
ModelRouterMiddleware routes an agent to a model selected by a TypeSafe Choice question:
from langchain.agents import create_agent
from langchain_typesafe.experimental.middleware import (
ModelChoice,
ModelRouterMiddleware,
)
router = ModelRouterMiddleware(
choices={
"fast": ModelChoice(
model="openai:gpt-5-mini",
criteria="Simple, well-scoped tasks.",
),
"powerful": ModelChoice(
model=powerful_model,
criteria="Complex tasks requiring deeper reasoning.",
),
},
instructions="Choose the least costly model suited to the task.",
)
agent = create_agent("openai:gpt-5-mini", middleware=[router])
The model router classifies the latest human message once per agent run and stores the complete ChoiceAnswer in agent state, keeping its probabilities and confidence available to applications and traces.
AutoModeMiddleware
AutoModeMiddleware classifies calls to explicitly configured tools and blocks risky calls before execution:
from langchain_typesafe import NoulCriteria
from langchain_typesafe.experimental.middleware import AutoModeMiddleware
auto_mode = AutoModeMiddleware(
tools=[delete_file],
criteria=NoulCriteria(
true="The call writes, deletes, publishes, or changes access.",
false="The call only reads public or user-provided data.",
),
)
agent = create_agent(
model,
tools=[read_file, delete_file],
middleware=[auto_mode],
)
tools accepts tool names or BaseTool instances. Customize instructions for the overall risk question and criteria for application-specific risky and safe outcomes. Configured calls whose risk probability meets or exceeds the threshold return an error ToolMessage.
LangChain messages as state
BaseMessage objects and message sequences can appear at the root or anywhere inside JSON state. The integration recursively converts them to objects with role and content fields while preserving surrounding application data:
from langchain_core.messages import HumanMessage, SystemMessage
response = classifier.invoke(
{
"state": {
"conversation": [
SystemMessage("You are reviewing a customer support conversation."),
HumanMessage("My payouts have failed for three days. Help!"),
],
"account_tier": "enterprise",
},
"questions": {
"urgent": Noul(instructions="Does this customer need urgent help?")
},
}
)
Custom HTTP clients
The classifier creates sync and async httpx2 clients when they are not supplied. Applications that need custom transports, proxies, or shared connection pools can inject either client independently:
import httpx2
classifier = TypeSafeClassifier(
client=httpx2.Client(proxy="http://proxy.internal"),
async_client=httpx2.AsyncClient(proxy="http://proxy.internal"),
)
Injected clients are used as-is, and the application retains responsibility for their lifecycle.
Error handling
Provider errors also inherit from LangChain's standard model-error hierarchy. Applications can therefore catch a TypeSafe-specific error when provider metadata is needed, or a LangChain error when handling several model providers uniformly:
from langchain_core.exceptions import ModelAuthenticationError, ModelRateLimitError
from langchain_typesafe import TypeSafeRateLimitError
try:
response = classifier.invoke(
{
"state": "Classify this message.",
"questions": {"urgent": Noul(instructions="Is this urgent?")},
}
)
except TypeSafeRateLimitError as error:
print(error.request_id, error.retry_after_ms)
except (ModelAuthenticationError, ModelRateLimitError):
handle_model_error()
TypeSafeAPIError exposes the response status, parsed body, headers, sanitized endpoint, and request ID. Connection, timeout, response-validation, and status-specific subclasses follow the names used by the TypeSafe Python SDK.
Documentation
See the TypeSafe documentation for model and question semantics. LangChain API reference documentation is available at reference.langchain.com.
Contributing
For contribution instructions, see the LangChain contributing guide.
Metadata
Release files for langchain-typesafe 0.0.1a3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| langchain_typesafe-0.0.1a3.tar.gz | 201.0 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| langchain_typesafe-0.0.1a3-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 225.9 kB
Release files / langchain_typesafe-0.0.1a3.tar.gz
| Download URL | langchain_typesafe-0.0.1a3.tar.gz |
|---|---|
| Size | 201.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d77647a7a5bafaa82db8212a682b223a9bbcd52fb015e49464f211552f1f3272
|
|
BLAKE2b-256 checksum How to use checksums |
c954460d126cb5db7b031e5b3b94c63fe36d58bce020f2692fd7661f8f84c7d3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Release files / langchain_typesafe-0.0.1a3-py3-none-any.whl
| Download URL | langchain_typesafe-0.0.1a3-py3-none-any.whl |
|---|---|
| Size | 25.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f06f74ebdcb10cbc836dd89a275bbf4e2e13646cb919dcc02d4219e602cfe36e
|
|
BLAKE2b-256 checksum How to use checksums |
ca5ba14f30242eb36363ee757024a01727fef5efffbb542d2382468f457a7e2b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|