Skip to main content

langchain-typesafe

PyPI - Version PyPI - License

Installation

uv add langchain-typesafe

Set the TYPESAFE_API_KEY environment variable before making requests.

Usage

TypeSafeClassifier is a LangChain decision model (langchain_core.decisions.BaseDecisionModel) for probabilistic classification, scoring, and localization with TypeSafe. It supports Noul, Choice, Score, and Box questions.

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)

Images

Image content blocks with inline base64 data or a base64 data: URL can appear anywhere in state or in question instructions and criteria, including inside messages. They are sent to TypeSafe as request assets. PNG and JPEG images are supported; images are not downloaded from remote URLs.

from langchain_typesafe import Box

result = classifier.invoke(
    {
        "state": {"type": "image", "base64": image_data, "mime_type": "image/png"},
        "questions": {"dog": Box(instructions="Where is the dog?")},
    }
)
print(result.boxes["dog"].box)

Agent middleware

LangChain's ModelRouterMiddleware and AutoModeMiddleware accept any decision model as their classifier. Pass a TypeSafeClassifier to use TypeSafe.

Deprecated: langchain_typesafe.experimental.middleware is deprecated since 0.1.0 and will be removed in 0.2.0. Import the middleware from langchain.agents.middleware and pass classifier=TypeSafeClassifier() instead.

ModelRouterMiddleware

ModelRouterMiddleware routes an agent to a model selected by a Choice question:

from langchain.agents import create_agent
from langchain.agents.middleware import ModelChoice, ModelRouterMiddleware
from langchain_typesafe import TypeSafeClassifier

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.",
    classifier=TypeSafeClassifier(),
)
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.agents.middleware import AutoModeMiddleware
from langchain_typesafe import NoulCriteria, TypeSafeClassifier

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.",
    ),
    classifier=TypeSafeClassifier(),
)
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.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for langchain-typesafe 0.1.0
File Size Uploaded Provenance Actions
langchain_typesafe-0.1.0.tar.gz 172.6 kB Without provenance Details for langchain_typesafe-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for langchain-typesafe 0.1.0
File Interpreter ABI Platform Actions
langchain_typesafe-0.1.0-py3-none-any.whl Python 3 none any Details for langchain_typesafe-0.1.0-py3-none-any.whl

Total release size: 193.5 kB

Release files / langchain_typesafe-0.1.0.tar.gz

Download URL langchain_typesafe-0.1.0.tar.gz
Size 172.6 kB
Tags Source
SHA-256 checksum
How to use checksums
3abe72190913903a7ea07491a65577ac0057b752fcc3f386179a07cedb120b9a
BLAKE2b-256 checksum
How to use checksums
3beccd0b5d5f961131251cb3a79b330a5a21750067a1f6bf0aa0a184d798f85c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / langchain_typesafe-0.1.0-py3-none-any.whl

Download URL langchain_typesafe-0.1.0-py3-none-any.whl
Size 20.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fa9fcf166cac3c04e0ab0583f2bcb421fc2b31e497411222b4d9add900a213a6
BLAKE2b-256 checksum
How to use checksums
87bdf56733b4b3c9f7e59d6f2c8bc8403483ae907b31b090568285cb7deed758
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Security for langchain-typesafe 0.1.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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page