Skip to main content

langchaint

Provider-neutral async LLM and embedding clients over official SDKs. Alpha: the API is unstable and may change without notice.

The point

langchaint sits between application workflows and provider SDKs. Generation uses one message tree, error taxonomy, priced Usage, and SharedBackoff. Embeddings return normalized NumPy matrices directly. Applications keep agent loops, caching choices, and vector persistence.

Install

langchaint requires Python 3.13 or newer. Its core dependencies are pydantic, jsonschema, and NumPy. Applications pin every provider SDK directly. langchaint declares no dependency extras.

Install OpenAI generation support:

pip install langchaint openai

Install OpenAI embedding support:

pip install langchaint openai tiktoken

Install Cohere embedding support through Amazon Bedrock:

pip install langchaint boto3

Top-level import langchaint requires no provider SDK. Backend imports report missing SDK dependencies through ModuleNotFoundError.

Generation example

import asyncio

from pydantic import BaseModel

from langchaint.openai import OpenAIAccount


class Sentiment(BaseModel):
    label: str
    confidence: float


async def main() -> None:
    async with OpenAIAccount() as account:
        classifier = account.model("gpt-5.6-terra").bind(
            system_prompt="Classify the sentiment of the user's message.",
            response_format=Sentiment,
            automatic_prompt_caching=False,
        )
        response = await classifier.generate_one("This is the best day in months.")
        print(response.output.label, response.usage.cost_in_usd)


asyncio.run(main())

bind(response_format=Sentiment) returns BoundLLM[Sentiment]. Its response.output is a validated Sentiment instance. Without response_format, response.output is assistant text. A bare generation str becomes one UserMessage.

Embedding example

import asyncio

from langchaint.openai import OpenAIAccount


async def main() -> None:
    async with OpenAIAccount() as account:
        embedding_model = account.embedding_model(
            "text-embedding-3-small",
            dimension=1024,
        )
        documents = await embedding_model.embed(
            ["The Moon orbits Earth.", "Mars has two small moons."],
            task="retrieval_document",
        )
        query = await embedding_model.embed(
            ["Which object circles Earth?"],
            task="retrieval_query",
        )
        print(documents.shape, query.shape)


asyncio.run(main())

OpenAI accepts task for interface consistency. It sends no corresponding OpenAI request field.

Use this construction for Cohere through Amazon Bedrock:

from langchaint.cohere import CohereBedrockAccount

async with CohereBedrockAccount(aws_region="us-east-1") as account:
    embedding_model = account.embedding_model("cohere.embed-v4:0", dimension=1024)

Each result has shape (len(inputs), dimension) and dtype np.float32. Every row has L2 norm one. Each result owns writable, C-contiguous storage. langchaint performs no vector persistence.

What it has

Generation only through binding. LLM.bind() returns BoundLLM[OutputT] with frozen inference configuration. BoundLLM provides generate_one, generate_many, and stream_one. Changing generation parameters uses rebind().

Embeddings without binding. EmbeddingModel.embed() takes texts and one required task. It returns Float2D directly. Provider adapters maximize ordered batches under documented request limits.

One Account per SDK client configuration. Accounts share SDK clients and one SharedBackoff across request clients. Each account closes resources it created.

One accounting contract for generation. Generation success and GenerationError both carry paid usage across attempts.

Priced generation usage. Usage partitions input tokens by cache outcome. It carries one cost per priced category.

One SharedBackoff owning pacing. Its admitted() block gates every request start. Rate limits pause the complete account request domain.

User-stated prompt caching. automatic_prompt_caching is required because caching changes billing. cache_breakpoint=True places a prompt-cache boundary on that content part.

Streaming through a handle. stream_one returns a StreamHandle async context manager. Its final() method returns the assembled result.

Tools under one protocol. PydanticTool, JSONSchemaTool, and CaptureTool implement Tool. Applications may implement additional Tool forms.

Reasoning preserved across turns. langchaint re-emits provider reasoning elements verbatim on later requests.

OTel tracing as a wrapper. langchaint.tracing wraps generation clients and ToolManager. capture_message_content is required because prompt recording affects privacy.

What it does not have

  • No agent class or agent loop.
  • No vector storage or retrieval index.
  • No client-side guessing at undocumented provider rules.
  • No document or PDF content part.

Convert documents before generation requests. Use ImagePart for rasterized pages or TextPart for extracted text.

Layout

src/langchaint/           the provider-neutral core
src/langchaint/anthropic/ the Anthropic backend
src/langchaint/cohere/    the Cohere Bedrock embedding backend
src/langchaint/deepseek/  the DeepSeek backend using the OpenAI SDK
src/langchaint/gemini/    the Gemini backend
src/langchaint/openai/    the OpenAI backend
src/langchaint/tracing/   the OTel tracing subpackage
examples/                 focused examples and migration guidance

Verification

Run scripts/CI.sh. The tests are offline and require no API keys.

Release files for langchaint 0.13.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 langchaint 0.13.0
File Size Uploaded
langchaint-0.13.0.tar.gz 225.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for langchaint 0.13.0
File Interpreter ABI Platform
langchaint-0.13.0-py3-none-any.whl Python 3 none any Details

Total release size: 468.5 kB

Release files / langchaint-0.13.0.tar.gz

Download URL langchaint-0.13.0.tar.gz
Size 225.1 kB
Tags Source
SHA-256 checksum
How to use checksums
d1e32594c583d773ddfb31f3e804855ad7b15f78a569cf02ecc3aac3a0b2c7af
BLAKE2b-256 checksum
How to use checksums
0d5562a4507ef91e5d99ba171aca2a5799ba9f0e1f983704c883f7eff401db54
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / langchaint-0.13.0-py3-none-any.whl

Download URL langchaint-0.13.0-py3-none-any.whl
Size 243.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2ffce89ebbc2e7d3ae729832551c25ac7762be56534c76744345c47049767cc0
BLAKE2b-256 checksum
How to use checksums
ae0e4c1d6dca53582eec4c944e780145ae714d66e5409ce235d31ccd304efa0c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release history Release notifications | RSS feed

0.23.3

2 release files

0.23.2

2 release files

0.23.1

2 release files

0.23.0

2 release files

0.22.0

2 release files

0.21.2

2 release files

0.19.4

2 release files

0.19.3

2 release files

0.19.1

2 release files

0.19.0

2 release files

0.18.1

2 release files

0.18.0

2 release files

0.17.1

2 release files

0.17.0

2 release files

0.16.0

2 release files

0.15.3

2 release files

0.15.2

2 release files

0.15.1

2 release files

0.15.0

2 release files

0.14.0

2 release files

This release

0.13.0 This release

2 release files

0.11.2

2 release files

0.11.1

2 release files

0.11.0

2 release files

0.10.0

2 release files

0.9.0

2 release files

0.8.0

2 release files

0.7.1

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.0

2 release files

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