Skip to main content

neuromod

A composable, type-safe LLM inference library for Python. Everything is a step function.

Install

pip install neuromod

For thread persistence with SQLAlchemy:

pip install neuromod-sqlalchemy

Quick Start

import asyncio
from neuromod import Agent, Claude, configure

configure(api_keys={"anthropic": "sk-ant-..."})

agent = Agent(model=Claude.Sonnet5, system="You are a helpful assistant.")

async def main():
    response = await agent.generate("What is Python?")
    print(response.text)

asyncio.run(main())

Or use environment variables for zero-config setup:

export ANTHROPIC_API_KEY=sk-ant-...
agent = Agent(model=Claude.Sonnet5)
response = await agent.generate("Hello")

Core Concepts

Everything is a Step Function

The fundamental primitive is StepFunction: an async callable that takes a ConversationContext and returns a new ConversationContext.

StepFunction = Callable[[ConversationContext], Awaitable[ConversationContext]]

Agents, model calls, scopes, and threads are all step functions. They compose together with compose() and scope().

Agents

The primary public API. Configure once, use everywhere.

from neuromod import Agent, Claude, create_tool
from pydantic import BaseModel

class SearchParams(BaseModel):
    query: str

search = create_tool(
    name="search",
    description="Search the web",
    schema=SearchParams,
    execute=lambda p: search_web(p.query),
)

agent = Agent(
    model=Claude.Sonnet5,
    system="You are a research assistant.",
    tools=[search],
    max_steps=5,
    temperature=0.7,
)

# Simple generation
response = await agent.generate("Find recent papers on transformers")
print(response.text)
print(response.usage)          # TokenUsage(input_tokens=..., output_tokens=...)
print(response.finish_reason)  # "stop" or "max_steps"

# Streaming
result = agent.stream("Explain quantum computing")
async for event in result.events:
    if event.type == "text_delta":
        print(event.text, end="", flush=True)
response = await result.response

# Per-request overrides
response = await agent.generate(
    "Summarize this",
    temperature=0.3,
    max_steps=1,
    tool_choice="none",
)

# Token counting
count = await agent.count_tokens("How long is this prompt?")
print(count.tokens)

See agents module docs for full API reference.

Composition

Build pipelines by composing step functions.

from neuromod import compose, scope, Inherit, model, when, no_tools_called

# Sequential pipeline
pipeline = compose(agent_a, agent_b, agent_c)
result = await pipeline("Hello")

# Scoped execution with isolation
sub_task = scope(
    research_agent,
    inherit=Inherit.NOTHING,
    tools=[search_tool],
    until=no_tools_called,
)

pipeline = compose(planner, sub_task, writer)

# Agents are step functions — they work in compose/scope
await compose(agent_a, agent_b)("Hello")

See composition module docs for compose(), scope(), model(), when(), tap(), retry(), and loop conditions.

Tools

Define tools with Pydantic schemas for type-safe argument validation.

from neuromod import create_tool
from pydantic import BaseModel

class WeatherParams(BaseModel):
    city: str
    units: str = "celsius"

weather = create_tool(
    name="get_weather",
    description="Get current weather for a city",
    schema=WeatherParams,
    execute=fetch_weather,
    max_calls=3,
    requires_approval=True,
    retry=2,
)

See tools module docs for tool configuration options.

Threads (Persistent Conversations)

Attach thread IDs to persist conversation history across calls.

from neuromod import configure, Agent, Claude
from neuromod_sqlalchemy import SQLAlchemyThreadStore, Base

# Setup with SQLAlchemy
engine = create_async_engine("sqlite+aiosqlite:///threads.db")
async with engine.begin() as conn:
    await conn.run_sync(Base.metadata.create_all)

store = SQLAlchemyThreadStore(async_sessionmaker(engine, class_=AsyncSession))
configure(thread_store=store)

agent = Agent(model=Claude.Sonnet5)
await agent.generate("My name is Alice", thread_id="user-123")
response = await agent.generate("What's my name?", thread_id="user-123")
# response.text → "Your name is Alice"

See thread docs and neuromod-sqlalchemy.

Structured Output

Get typed responses using Pydantic models.

from pydantic import BaseModel

class Analysis(BaseModel):
    sentiment: str
    confidence: float
    topics: list[str]

agent = Agent(model=Claude.Sonnet5, schema=Analysis)
response = await agent.generate("Analyze: I love this product!")
print(response.output)  # Analysis(sentiment="positive", confidence=0.95, topics=["product review"])

Token Limits

Every Model publishes two limits, and they play different roles.

max_tokens is the default output budget sent with each request. Override it per call when you want a shorter answer — the model's value is a default, not a mandate:

agent = Agent(model=Claude.Sonnet5)              # defaults to Sonnet5.max_tokens
await agent.generate("Answer in one word.", max_tokens=16)

# or set a different default for the whole agent
agent = Agent(model=Claude.Sonnet5, max_tokens=2_048)

max_input_tokens is reference data — never sent, never enforced. It is there so you can budget context without hardcoding a number per model:

count = await agent.count_tokens(conversation)
headroom = Claude.Sonnet5.max_input_tokens - Claude.Sonnet5.max_tokens - count.tokens

Both reflect the base model at the default account tier. If your account differs, override with custom_model(..., max_input=..., max_tokens=...).

Configuration

Three-layer precedence: per-agent > configure() > environment variables.

from neuromod import configure

# Global config
configure(
    api_keys={"anthropic": "sk-...", "openai": "sk-..."},
    base_urls={"openai": "https://my-proxy.com"},
    timeouts={"anthropic": 300},
    thread_store=my_store,
)

# Per-agent override
agent = Agent(model=Claude.Sonnet5, api_key="sk-different-key")

# Environment variable fallback
# ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, XAI_API_KEY, BEDROCK

See config module docs.

Amazon Bedrock

Run Claude models through Amazon Bedrock. Authentication uses a Bedrock API key (bearer token) — no AWS SigV4 signing and no boto3 dependency.

Bedrock endpoints are region-scoped, so a region is required. Set it via BEDROCK_REGION (falls back to AWS_REGION), or pass a full endpoint through base_urls. If no region is resolvable, a ConfigError is raised rather than silently defaulting.

from neuromod import Agent, Bedrock, configure

configure(api_keys={"bedrock": "..."})   # or set BEDROCK in the environment

agent = Agent(model=Bedrock.Opus5)   # needs BEDROCK_REGION / AWS_REGION
response = await agent.generate("What is Python?")
export BEDROCK=...           # Bedrock API key (or AWS_BEARER_TOKEN_BEDROCK)
export BEDROCK_REGION=us-east-1

Only Claude models work here. This provider speaks Anthropic's Messages wire format over Bedrock's InvokeModel endpoint. Bedrock also hosts Nova, Llama, Mistral, Titan and others, but they use different request shapes and would need their own provider.

Bedrock has two families of Claude model id, both reachable through InvokeModel:

Bedrock.Opus5        # anthropic.claude-opus-5 — unversioned, pass as-is
Bedrock.Opus4_6      # global.anthropic.claude-opus-4-6-v1 — needs a routing prefix

Claude Opus 4.7 and later use unversioned ids. Claude Opus 4.6 and earlier are ARN-versioned and served only through cross-region inference — passing a bare base id returns an HTTP 400 asking for an inference profile, so those entries ship with the global. prefix (dynamic routing, no premium). For data residency, swap it for a regional prefix (10% premium):

from neuromod import custom_model

model = custom_model("bedrock", "us.anthropic.claude-opus-4-6-v1",
                     max_input=1_000_000, max_tokens=128_000)

To target a non-default region or a VPC/proxy endpoint explicitly:

configure(
    api_keys={"bedrock": "..."},
    base_urls={"bedrock": "https://bedrock-runtime.eu-west-1.amazonaws.com"},
)

Streaming Events

Subscribe to real-time events during generation.

def handler(event):
    match event.type:
        case "text_delta":
            print(event.text, end="")
        case "tool_call_start":
            print(f"\nCalling {event.name}...")
        case "tool_complete":
            print(f"Tool result: {event.result}")
        case "step_start":
            print(f"\n--- Step {event.step_number} ---")

response = await agent.generate("Research this topic", on_event=handler)

See streaming module docs for all event types.

Cancellation

Cancel in-progress generation using asyncio.Event.

import asyncio

signal = asyncio.Event()
task = asyncio.create_task(agent.generate("Write a novel", signal=signal))

# Later:
signal.set()  # Generation stops after current step
response = await task
print(response.finish_reason)  # "aborted"

Architecture

neuromod/
├── agents/          # Agent class — the primary public API
├── composition/     # Step functions: compose, scope, model, thread, helpers
├── config.py        # Global configuration with contextvars
├── messages/        # Content types, Message with properties, builders
├── models/          # Model definitions (Claude, Bedrock, Gemini, OpenAI, xAI)
├── providers/       # Provider protocol, error hierarchy, factory
├── streaming/       # Stream event types, Channel
└── tools/           # Tool definition with Pydantic schemas
Module Description Docs
agents Agent class with generate/stream/count_tokens README
composition compose, scope, model step, thread, helpers README
config configure(), API key resolution, factory management Inline
messages Content types, Message with properties, builder functions README
models Model dataclass, provider model registries README
providers Provider protocol, errors, factory, Anthropic/Bedrock/Google/OpenAI/Ollama impls README
streaming StreamEvent union, event types, Channel README
tools Tool definition, create_tool, convert_tools README

Design Principles

  1. Step functions are the primitive. Everything composes through async (ctx) -> ctx.
  2. Single source of truth. ConversationContext.messages is the truth.
  3. Content is always a list. Message.content is always list[Content], never str | list.
  4. Tool calls are content parts. They live inside content[], not on separate fields. Roles are system | user | assistant only.
  5. Provider = API connection, not model binding. One provider per API, model passed per-request.
  6. Errors typed by HTTP status. Auth (401/403), RateLimit (429), Network, API.
  7. Immutability where practical. Models and tools are frozen. Context updates produce new instances.

Development

pip install -e ".[dev]"
pytest

Requires Python 3.11+. Dependencies: pydantic, httpx.

Acknowledgements

Neuromod was inspired by and draws heavily from nvms/threaded. Its step-function architecture informed Neuromod’s design; Neuromod brings that approach to Python with a higher-level Agent API, Pydantic-based tools, and optional SQLAlchemy-backed thread persistence.

Metadata

Release files for neuromod 0.3.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 neuromod 0.3.0
File Size Uploaded Provenance Actions
neuromod-0.3.0.tar.gz 85.3 kB Without provenance Details for neuromod-0.3.0.tar.gz

Built distribution (wheel)

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

Total release size: 150.0 kB

Release files / neuromod-0.3.0.tar.gz

Download URL neuromod-0.3.0.tar.gz
Size 85.3 kB
Tags Source
SHA-256 checksum
How to use checksums
c94d60b9b74cdc86d8a5a873a5b17b38b2dd8376f31f635d1d8a9d9fcaf3cc33
BLAKE2b-256 checksum
How to use checksums
d71cd9c000bae79e13f4619ff3b7142c0cb1e8541705f40b46e7611048282df7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.2

Release files / neuromod-0.3.0-py3-none-any.whl

Download URL neuromod-0.3.0-py3-none-any.whl
Size 64.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d9456921008bd83de2f9c4a0c330a0c2a21763e55e2af402403fd212e5f8f30e
BLAKE2b-256 checksum
How to use checksums
67f1f62da5dec68f51952f060ac42e99c04b451ec8898933365635c9f73027d7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.2

Security for neuromod 0.3.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