Skip to main content

langchaint

langchaint is a provider-neutral Python client for LLM applications, with typed, asynchronous APIs for generation, streaming, embeddings, and tool dispatch.

Alpha: the API may change without notice.

Why langchaint

  • Types follow configuration: typed output and tool-call variants, narrowed by .kind.
  • Agent loops in ordinary Python: your code controls state, approvals, model changes, recovery, stopping, and persistence.
  • Shared rate limiting: concurrency limits, request pacing, and rate-limit pauses across your application.
  • Usage accounting: available provider-reported usage across every recorded request, including retries and failures.

Install

Requires Python 3.13+. Install each backend's extra:

pip install "langchaint[openai]"
Backend Class Install
Anthropic Anthropic langchaint[anthropic]
Anthropic on Amazon Bedrock AnthropicBedrock langchaint[anthropic-bedrock]
Cohere embeddings on Amazon Bedrock CohereBedrock langchaint[cohere-bedrock]
DeepSeek DeepSeek langchaint[deepseek]
Gemini Gemini langchaint[gemini]
OpenAI OpenAI langchaint[openai]
OpenAI embeddings OpenAI langchaint[openai-embedding]
OpenAI on Amazon Bedrock OpenAIBedrock langchaint[openai-bedrock]

Install langchaint[tracing] for OpenTelemetry tracing.

Generate a typed output

import asyncio

from pydantic import BaseModel

from langchaint.openai import OpenAI


class Answer(BaseModel):
    answer: str
    confidence: float


async def main() -> None:
    assistant = OpenAI().llm(
        "gpt-5.6-terra",
        system_prompt="Answer clearly and concisely.",
        response_format=Answer,
    )
    generation = await assistant.generate_one("Why is the sky blue?")

    print(generation.output.answer)
    print(generation.usage.cost_in_usd)


asyncio.run(main())

response_format=Answer validates the response with Pydantic and types generation.output as Answer. bind(response_format=...) returns a new model with the corresponding output type.

generate_many() returns generations in input order, or raises GenerationError after cancelling and awaiting unfinished inputs. generate_many_records() returns one normalized record per input, including failures; pass resume_path to persist records and resume interrupted batches.

To configure an adapter directly, use llm_from_adapter(adapter, ...) from langchaint.

Build agent loops

Configuring tools adds a tool-call variant to the generation's discriminated union. Match .kind to narrow its type, and set turn limits in your loop:

llm = OpenAI().llm("gpt-5.6-terra", tools=tools)
messages: list[Message] = [UserMessage(content=prompt)]

for _ in range(max_turns):
    generation = await llm.generate_one(messages)

    match generation.kind:
        case "tool_call":
            messages.append(generation.assistant_message)
            outcomes = await llm.tool_manager.dispatch_many(generation.tool_calls)
            messages.extend(outcome.tool_message for outcome in outcomes)
        case "plain":
            return generation.output

raise RuntimeError("model did not finish within max_turns")

ToolManager.dispatch_many() validates arguments and runs calls concurrently, preserving their order. Invalid arguments produce an error ToolMessage you can return to the model.

Complete typed loop: examples/02_tool_loop.py.

Coordinate rate limiting

SharedBackoff coordinates request concurrency, pacing, and rate-limit pauses across batches and separate tasks:

from langchaint import SharedBackoff
from langchaint.openai import OpenAI

shared_backoff = SharedBackoff(max_concurrent_requests=8, max_request_starts_per_second=50.0)
openai = OpenAI(shared_backoff=shared_backoff)
assistant = openai.llm("gpt-5.6-terra")

generations = await assistant.generate_many(
    ["Explain photosynthesis.", "Explain cellular respiration."],
)

Rate limits pause further request starts against the quota. For transient failures local to one request, langchaint waits and retries that request.

Track costs

generation.usage.cost_in_usd includes every recorded billed retry; GenerationError.usage retains a failed input's recorded cost.

Stream with an explicit lifetime

text_assistant = OpenAI().llm("gpt-5.6-terra")

async with text_assistant.stream_one("Explain photosynthesis.") as stream:
    async for item in stream:
        # Answer text chunks are str; ReasoningDelta, ToolCallDelta, and ToolCall are the other items
        if isinstance(item, str):
            print(item, end="", flush=True)

    generation = await stream.final()

final() consumes the remaining stream and returns the assembled generation.

More examples

Complete examples: examples/README.md.

License

MIT License

Metadata

Release files for langchaint 0.38.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.38.0
File Size Uploaded Provenance Actions
langchaint-0.38.0.tar.gz 176.9 kB Without provenance Details for langchaint-0.38.0.tar.gz

Built distribution (wheel)

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

Total release size: 374.8 kB

Release files / langchaint-0.38.0.tar.gz

Download URL langchaint-0.38.0.tar.gz
Size 176.9 kB
Tags Source
SHA-256 checksum
How to use checksums
c535d3408b3ef9e13a3ed3bd93c8bdd2f53e9a629cade0bc4b799a8a08b954e5
BLAKE2b-256 checksum
How to use checksums
6011bc8257e4f8d755c07d103c5aef2d71b33819cae1bd9ffbb750bc899b81d2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","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.38.0-py3-none-any.whl

Download URL langchaint-0.38.0-py3-none-any.whl
Size 197.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d8f18176f6be852235ca0d8840d9bf276394303d60297a1272e65caf0c373181
BLAKE2b-256 checksum
How to use checksums
35d263a9318be94c86d44a1fbfd10f30f507404e3cd57dd82f8dfd1510aafbd0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","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}

Security for langchaint 0.38.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.

Release history Release notifications | RSS feed

This release

0.38.0 This release

2 release files No provenance

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