Python SDK
The Python SDK is in private beta. This page documents the intended surface; it does not claim a PyPI package that is not published.
Back to docsPrivate beta
Access is provisioned by the team. No public package is promised before it exists.
Availability
Private beta for design partners. Request access through the contact form. When the package is published, this page will show the install command and a CI badge.
Intended surface
Sync and async clients, typed models, pagination, retries and webhook verification.
Example shape
The final package will expose a typed client. The following is illustrative, not an installable API yet.
from loopnow import LoopNow
client = LoopNow(api_key=os.environ["LOOPNOW_KEY"])
client.contacts.create(email="asha@example.com")
The short version
- There is no LoopNow package on PyPI. This page describes the client contract Python teams are building against the live endpoints, not an installable library.
- Only two routes exist: POST /api/chat streams Server-Sent Events, and POST /api/contact accepts JSON or form data. Everything else on this page wraps those two.
- Use one blocking client for scripts and workers, and one async client for web handlers. Do not run the async client from synchronous code with a bare event loop call.
- Map status codes to a small exception hierarchy: 429, 502 and 504 are retryable; 400 and 503 are not, and a 503 means configuration rather than load.
- The endpoint returns no request id today, so correlate logs with your own identifiers and never log message text containing customer data.
The state of the Python client
Nothing is published on PyPI, and this page will not pretend otherwise. The Python SDK is an early-access contract written around the two routes that actually run on loopnow.in. If you have seen an install line in a slide deck, it described an intention rather than a release. What follows is enough to build a working integration today and to replace it with a package later without rewriting call sites.
Python teams usually arrive with a different shape of problem than JavaScript teams. The chat integration often lives in a worker or a scheduled job rather than a browser, the contact form is submitted by a backend that already has the data, and the service is frequently a FastAPI app, a Celery worker or a notebook somebody runs by hand. The client contract below is organised around those three environments.
The honest framing is that you are writing a thin transport layer. Two endpoints, one streaming, one not. The value of documenting it in advance is that the fiddly parts, which are frame parsing, cancellation and exception mapping, get designed once instead of being rediscovered in each repository. The names of the classes are provisional; the wire behaviour is not.
Sync and async are two clients, not one
A single class that offers both blocking and async methods is a trap. It either runs an event loop inside a synchronous method, which fails the moment the caller already has one, or it hides threads behind a coroutine, which makes cancellation unpredictable. The cleaner design is two small classes with the same method names, one using a blocking transport and one using an async transport, sharing only the request builders and the parser.
The blocking client is the right choice for scripts, cron jobs, CLI tools and Celery tasks. Those environments have no event loop and gain nothing from async machinery. The async client belongs in FastAPI, Starlette, aiohttp services and anything already awaiting other I/O. Two classes, one contract, and a shared set of dataclasses for the payloads keeps the duplication to a minimum.
Whichever you pick, keep the payload construction in a pure function. That function takes plain Python values and returns a dictionary, so it can be unit tested without a network, reused by both clients, and compared against a recorded request when the endpoint contract changes. Most integration bugs are body-shape bugs, and they are the cheapest kind to catch.
Modelling the chat request
The chat body has a messages list and an optional page string. Each message is a mapping with a role and content. The server reads only the last twenty messages and rejects any single content longer than four thousand characters, so a client that accumulates an unbounded history will eventually send a body that fails for reasons the user cannot see. Trim before you post, not after you are refused.
A dataclass for the message and one for the request keep this readable without pulling in a validation framework. Both should serialise to primitives at the boundary, because a dataclass passed straight to a JSON encoder will either fail or leak a field you did not intend. If you use pydantic in the rest of your service, use it here too, but do not add a dependency just to build two dictionaries.
The page argument is normalised on the server: it must start with a slash, the query string is dropped and trailing slashes are trimmed. It is then used to prefer knowledge-base content from that page family. Passing a route name without the leading slash is silently ignored, which produces a general answer that looks like a scoping bug. Validate the shape in your own client so the mistake surfaces locally.
Streaming without blocking the loop
The chat route answers with an event stream. Frames are separated by a blank line, and the payload inside each frame follows the model server rather than the route, which forwards bytes unchanged. In an async client, iterate over the response content in chunks, decode incrementally and split on the frame separator. Never call a method that waits for the whole body; that discards the only reason the endpoint streams.
Two details bite Python clients in particular. First, decoding: use an incremental decoder so a multi-byte character split across chunks does not raise or produce mojibake. Second, line endings: the separator is two newlines, but a frame may use carriage returns depending on the upstream, so normalise before splitting. A parser that splits on a single newline will hand you half a JSON object and a confusing exception.
Yield the text deltas rather than the raw frames. Callers should not need to know about data prefixes or sentinels, and a generator that yields strings is trivial to consume from a FastAPI streaming response, a queue producer or a test. Keep the raw frame available behind a debug flag, because when the upstream changes its envelope you will want to see exactly what arrived.
Cancellation and timeout budgets
Timeouts in Python clients are usually expressed as one number for the whole request, which is exactly wrong for a stream. The connect phase should be short, the wait for the first byte should be short, and the wait between subsequent bytes should be a separate idle budget. A single thirty-second timeout either kills a healthy stream that is producing slowly or lets a dead connection hang for far too long.
Cancellation is the other half. When a client disconnects from your FastAPI endpoint, the framework cancels the task, and your generator must propagate that cancellation upstream instead of swallowing it. Catch broad exceptions around the stream only to translate them, never to continue reading a response nobody wants. A worker that keeps consuming tokens after the user left is paying for output it will throw away.
The route itself gives the model forty-five seconds before aborting, so a Python budget should be under that to fail on its own terms. In asyncio, wrap the whole exchange in a timeout context and let the cancellation close the connection; do not catch the timeout at every layer, or the stack trace you finally see will point at the wrong place.
Mapping status codes to exceptions
A Python client that returns raw responses pushes error handling into every caller. A small hierarchy is better: one base exception for the client, a subclass for retryable failures, a subclass for terminal ones and a subclass for configuration problems. The mapping is mechanical, and having it in one function means a new status code is a one-line change rather than a search across the codebase.
Rate limiting is the case worth naming, because it is normal operation rather than an outage. A 429 from chat means the IP sent more than twelve messages in a minute, and the right response is to wait and retry once, then surface a message. Raising the same exception type as a 500 teaches callers to retry everything, which is how a rate limit becomes an outage.
A 503 is different again. It means the environment has no model key, so the assistant is not configured. Retrying that is pure delay, and the exception should say so in its message. Keeping these three meanings distinct, retryable, terminal and misconfigured, is most of the value a client library provides even before it has any other feature.
Knowing the real limits
The limits that matter are enforced on the server and are small enough to memorise. Chat accepts twelve requests per minute from one IP. Contact accepts five per minute from one hashed IP. Chat keeps the last twenty messages of a conversation and refuses any single message over four thousand characters. Contact caps the message field at five thousand characters and validates the name and email before writing anything.
These are per-IP limits, which matters for Python services more than for browsers. A Celery fleet behind one NAT gateway shares a single chat budget, so a burst of jobs will hit 429 even though each job sends one message. If your workload is backend-to-backend rather than user-driven, pace the jobs instead of retrying aggressively, and put the pacing in the queue rather than in the request loop.
Client-side budgets are yours to choose, and the honest advice is to be conservative. A server that answers in under a second normally should not be given sixty seconds of patience, because the timeout is also the time a user stares at a spinner. Pick numbers you can defend, write them in one configuration object, and change them for a reason rather than in response to one slow afternoon.
Configuration without a framework
A Python service usually reads configuration from the environment, an untracked dotenv file in development, and a secret manager in production. For this integration the only value you need is the base URL of the site and, if you call the model server directly rather than through the route, a key. The route itself needs no client secret, which removes a whole class of leak from your side.
Read configuration once, at import time or in an application factory, and fail with a clear message when something required is absent. A default of an empty string turns a missing value into a 401 discovered by a user. Loading a dotenv file in production because it happened to exist is the other classic mistake; make the file development-only and let production fail if the environment is genuinely empty.
Keep secrets out of repr output. Dataclasses print their fields, exception messages get logged, and a settings object with a key field will eventually appear in a traceback. Store the key in a field marked as repr false, or hold it in a separate object that is never logged. This is a five-minute decision that saves an incident later.
Testing with pytest and recorded frames
The most valuable test does not touch the network. Record a real event stream once, store it as a fixture, and feed the bytes to your parser in deliberately awkward slices: one byte at a time, splitting a JSON object in half, splitting a multi-byte character across a boundary. A parser that survives those cases will survive a production connection, and the test runs in milliseconds with no server.
For the request side, assert on the dictionary you would send rather than on a live call. That catches the missing leading slash on page, the over-long message and the extra field somebody added because they assumed it was forwarded. If you want an integration test, point it at a staging deployment and keep it out of the default test run, because a test that depends on a live model is a test that fails for reasons unrelated to your code.
Test the error mapping too. Construct responses with each status code and assert which exception type comes out, including the case where the body is HTML from a proxy rather than the JSON your client expects. That last one is not hypothetical: a 502 from an intermediary is frequently a branded error page, and a client that calls a JSON parser unconditionally will raise the wrong exception at the worst moment.
Where a Python deployment changes the answer
The same client behaves differently depending on where it runs. A FastAPI handler can stream a generator straight back to the browser, so the user sees tokens as they arrive. A Celery worker cannot stream anywhere useful, so it should collect the whole answer and publish it. A notebook is interactive and forgiving. A scheduled job should probably not use the chat endpoint at all if it needs to run thousands of prompts.
Serverless Python has its own constraints: a cold start before the first byte, a wall clock that can be shorter than the model deadline, and an execution environment that may not allow long-lived connections. If your platform caps execution at thirty seconds, a forty-five second upstream deadline is irrelevant because your function dies first. Check the platform limit before choosing a client timeout, not after a timeout mystery.
Workers behind a queue need pacing rather than concurrency. Twelve requests per minute per IP is easy to exceed with ten workers, and retries make it worse. Token bucket the producer, keep the consumer count low, and treat a 429 as a signal to slow the queue rather than to retry the task immediately. That is a queue design decision, but it is where most Python chat integrations actually fail.
Packaging, naming and what comes next
There is no distribution to pin, and that has a security consequence worth stating plainly. A name that looks like an official LoopNow package but is not one could be uploaded to PyPI by anybody, and a single install line in a tutorial is enough to spread it. Until there is an announcement with a project URL and a version, install nothing and write the twenty lines yourself.
The migration later should be mechanical if you structure for it now. One module owns the base URL, one function builds the body, one generator parses frames, one function maps status codes to exceptions. Those four seams are exactly where a published client would plug in. If the seams are clean, adopting a package is a small diff; if requests are scattered through the codebase, it is a refactor nobody schedules.
What a package would plausibly add is not a mystery either: typed models, a shared retry policy, sync and async variants that cannot drift apart, and a test suite covering the frame edge cases. Those are real benefits, and they are the reason to wait for a version rather than to adopt a guess. The wire contract on this page is what both the hand-written version and the published one will speak.
Frequently asked questions
Is there a LoopNow package on PyPI?
No. Nothing is published, so there is no version to pin and no import path that will work. Any install command you have seen describes an intention. Write the transport yourself against the two documented endpoints, or ask about early access through the contact form. A package will be announced with a project URL before it is referenced anywhere as installable.
Should I use the sync client inside FastAPI?
No. A blocking call inside an async handler occupies the event loop thread, so one slow model answer stalls every other request in that worker. Use the async client in FastAPI and Starlette, and keep the blocking client for scripts, Celery tasks and command line tools where no event loop exists. Two small clients are easier to reason about than one class that pretends to be both.
How do I stream the answer to a browser from Python?
Yield each text delta from an async generator and return a streaming response from your framework. Check that the framework and any reverse proxy do not buffer the body, because a buffered stream arrives as one block and loses the benefit. Also make sure your generator propagates cancellation, otherwise a closed browser tab leaves the request consuming tokens until the upstream finishes.
What happens if I send more than twenty messages?
The server keeps the last twenty and ignores the rest, so the request succeeds with a shortened context rather than failing. That is convenient and slightly dangerous: if your own history trimming is broken, the model silently forgets the beginning of a conversation. Trim client-side and log the count you sent so a context problem is visible in your own telemetry rather than inferred from odd answers.
Why do I get 429 when my service is the only user?
Because the limit is per IP, not per process or per user. A fleet of workers behind one NAT gateway shares twelve chat requests per minute, and a retry loop spends that budget quickly. Pace the producer with a token bucket, keep concurrency low, and treat a 429 as a signal to slow down. Retrying immediately converts a brief limit into a sustained one.
Do I need an API key to call the chat route?
No. The route holds the model key on the server and forwards only the streamed text, so a client calling loopnow.in needs no secret. You would need a key only if you bypass the route and call a model server directly, which is a different agreement. Keeping the key server-side removes the most common leak path from your Python service entirely.
How should retries interact with asyncio cancellation?
Cancellation should win. If the caller cancels, or the framework cancels because the client disconnected, stop the retry loop instead of sleeping and trying again. Catch the cancellation exception narrowly, re-raise it, and let the connection close. A retry loop that swallows cancellation keeps a worker busy for output nobody will read, and it hides shutdown problems during deploys.
Can I use this from a Jupyter notebook?
Yes, with the blocking client. A notebook has no running event loop by default, and the async client will either need a loop you manage yourself or fail with a runtime warning. The blocking client is simpler, and the streaming behaviour still works if you iterate rather than waiting for the full body. Notebooks are also a reasonable place to prototype the parser against recorded frames.
What does a 503 from the chat endpoint mean for my client?
That the environment has no model key configured, so the assistant is unavailable rather than overloaded. Retrying cannot help, and the exception should tell the caller to fall back to the contact form. In Python services this usually shows up right after a deployment that missed an environment variable, so alarm on it separately from ordinary server errors.
How do I keep customer text out of my logs?
Log identifiers, status codes and durations, not message content. Exception handlers that print the failing request body are the usual culprit, and they turn a policy document into a liability the first time somebody greps production. Truncate and hash where you need correlation, and keep full payloads only in a controlled debugging environment with a short retention window.