Skip to main content

NanoGPT Python SDK

Minimal first-party Python client for stable NanoGPT API endpoints, with a sync client (NanoGPT) and an asyncio client (AsyncNanoGPT). It needs Python 3.9 or later and has no dependencies.

pip install nanogpt-python
import os
from nanogpt import NanoGPT

client = NanoGPT(api_key=os.environ["NANOGPT_API_KEY"])

completion = client.chat_completion(
    model="openai/gpt-6.1-sol",
    messages=[{"role": "user", "content": "Say hello in one sentence."}],
)

print(completion.choices[0].message.content)   # typed attributes
print(completion["choices"][0]["message"]["content"])  # still a plain dict

deposit = client.create_deposit("kas", amount=100)
status = client.deposit_status("kas", str(deposit["txId"]))

The SDK covers chat, responses, messages, embeddings, the model list, usage, account helpers and the file-backed Batch API. For every other endpoint, see the API reference.

Async

AsyncNanoGPT has the same methods and options. Await the regular methods and use async for with the stream_ helpers:

import asyncio
import os
from nanogpt import AsyncNanoGPT

async def main():
    client = AsyncNanoGPT(api_key=os.environ["NANOGPT_API_KEY"])
    response = await client.create_response(model="openai/gpt-6.1-sol", input="Write a haiku.")
    print(response.output_text)

    async for event in client.stream_message(
        model="anthropic/claude-sonnet-5.5",
        max_tokens=1024,
        messages=[{"role": "user", "content": "Count to three."}],
    ):
        print(event.text, end="", flush=True)

asyncio.run(main())

It keeps the dependency-free design: blocking I/O runs on background daemon threads over the same transport as NanoGPT (credential-safe redirects, timeouts, retries), so the event loop never blocks. Each in-flight request uses one thread, and a stream keeps its thread until it ends. on_response callbacks run on the event loop thread.

To cancel, cancel the task or set a deadline with asyncio.wait_for. Control returns at once and no request or retry is sent afterwards. Once response headers have arrived, the connection is shut down and nothing more is read, for streams and plain responses alike; on_response has already received the metadata, including x-request-id. A request still waiting for headers can't be withdrawn (it may still be billed): its thread finishes waiting in the background and discards the result.

Typed responses

Results and stream events are typed models. Each one is a dict subclass holding the JSON exactly as the API sent it, so indexing, == with dicts and json.dumps work as before, and fields this SDK doesn't know about stay reachable by key. Attributes read known fields: an absent field is None, an absent list is [], and values are never validated or converted, so a new or unexpected field can't break parsing.

Method Returns
chat_completion / stream_chat_completion ChatCompletion (.text) / ChatCompletionChunk events (.text)
create_response, retrieve_response / stream_response Response (.output_text) / ResponseStreamEvent
create_message / stream_message Message (.text) / MessageStreamEvent (.text for text deltas)
usage / request_billing UsageReport (snake_case attributes over camelCase keys) / RequestBilling
models, embeddings, count_message_tokens ModelList, EmbeddingList, MessageTokenCount
Batch methods Batch, BatchList, BatchFile, BatchFileList, BatchQuote, BatchResult, DeletedObject

The models live in nanogpt.types, and the package ships type information (py.typed).

Streaming and errors

Use the stream_ helpers. chat_completion, create_response and create_message return one JSON response and raise ValueError for stream=True.

from nanogpt import NanoGPTError, RateLimitError

try:
    for chunk in client.stream_chat_completion(
        model="openai/gpt-6.1-sol",
        messages=[{"role": "user", "content": "Count to three."}],
    ):
        print(chunk.text, end="")
except RateLimitError as error:
    print("rate limited; retry after", error.retry_after, "advice:", error.retry_advice)
except NanoGPTError as error:
    print(error.status, error.code, error.message, error.request_id)

Every API error is a NanoGPTError; a subclass is chosen by status: BadRequestError (400), AuthenticationError (401), PaymentRequiredError (402), PermissionDeniedError (403), NotFoundError (404), ConflictError (409), RequestTooLargeError (413), UnprocessableEntityError (422), RateLimitError (429) and InternalServerError (5xx). Each carries status, message, code, type, param and retry_advice (when the body has them), the parsed body, lowercase response headers, request_id and retry_after (seconds, from Retry-After). Errors never contain request headers, so an API key can't leak through one, and the SDK doesn't log. Network failures raise the standard library's urllib.error.URLError, TimeoutError or OSError.

stream_response and stream_message work the same way. A failure after a stream has started arrives as an event on the HTTP 200 response. The SDK raises it as a NanoGPTError (or subclass) with the status from that event, or 500 if the event has none, and stream_started=True, so output you have already received may be partial.

Retries

Both clients retry automatically, at most max_retries times (default 2), with exponential backoff from 0.5 seconds (at most 8) plus jitter. A Retry-After header is honoured as a minimum wait; if it asks for more than 60 seconds, the error is raised instead so you can schedule the retry. Retries happen only where a replay is safe:

  • GET requests retry on 408, 429, 500, 502, 503 and 504, and on network errors.
  • POST and DELETE requests, including inference, retry only on 429, or on a 503 whose body says the request wasn't processed (retry_advice of retry_with_backoff or wait_for_completion). They never retry a bare 503, 500, 502, 504 or a network error, because a proxy can return those after the request already ran and was billed.
  • Nothing is retried when the error's retry_advice is check_request_status, add_funds_or_reduce_request or wait_for_reset, or its code reports missing funds.
  • Requests carrying a payment proof (X-Payment, Payment-Signature, X-X402-Payment-Id or Authorization: L402 ...) are never retried.
  • A stream retries only before its first event, never after events were received.

on_response sees only the final attempt. Use NanoGPT(max_retries=0) to turn this off.

Timeouts

NanoGPT(timeout=600.0) is the default. It applies to connecting and to each socket read, not to a whole response, so on a stream it is the longest wait between bytes. Use another number of seconds, or timeout=None to wait indefinitely. For a deadline on a whole call with AsyncNanoGPT, use asyncio.wait_for (see Async).

Batch API

Upload a JSONL file, create a batch, wait for it, and read the results. Every row uses the same endpoint and model. Batch requests are billed at batch rates.

import json

rows = [
    {"custom_id": f"q-{i}", "method": "POST", "url": "/v1/chat/completions",
     "body": {"model": "openai/gpt-6.1-sol", "messages": [{"role": "user", "content": question}]}}
    for i, question in enumerate(["What is 2+2?", "Name a prime."])
]
upload = client.upload_batch_file(
    "\n".join(json.dumps(row) for row in rows).encode(), endpoint="/v1/chat/completions",
)

quote = client.quote_batch(input_file_id=upload.id, endpoint="/v1/chat/completions")
print("maximum reservation (not a bill):", quote.maximum_reservation_usd)

batch = client.create_batch(input_file_id=upload.id, endpoint="/v1/chat/completions")
batch = client.wait_for_batch(batch.id, poll_interval=30)
for row in client.batch_results(batch):
    if row.error is None and row.response and row.response.status_code == 200:
        print(row.custom_id, row.response.body["choices"][0]["message"]["content"])
    else:
        print(row.custom_id, "failed:", row.error.code if row.error else row.response.status_code)
Method Endpoint
upload_batch_file(file, endpoint=None, filename=None) POST /v1/files (bytes, a path, or a binary file object; a str is a path)
list_batch_files, retrieve_batch_file, delete_batch_file GET /v1/files, GET / DELETE /v1/files/{id}
batch_file_content(file_id) GET /v1/files/{id}/content, as JSONL text
quote_batch(input_file_id=..., endpoint=...) POST /v1/batches/quote: a read-only maximum reservation
create_batch(input_file_id=..., endpoint=..., metadata=None, callback_url=None) POST /v1/batches
retrieve_batch, list_batches(status=..., after=..., before=...), cancel_batch GET /v1/batches[/{id}], POST /v1/batches/{id}/cancel
delete_batch(batch_id) DELETE /v1/batches/{id}; servers without it answer 404 or 405
batch_results(batch), wait_for_batch(batch_id) Output rows then error rows of a terminal batch; polling

batch_results raises ValueError until the batch is terminal, and on a malformed line. parse_batch_results(text) parses a result file you downloaded yourself. To build a retry file from failed rows, see examples/batch_retry.py. Batch uses the direct API host (the default base_url).

Request billing

deposit_status keeps crypto status polling on GET. It also preserves POST for usd checkout status polling as a browser checkout compatibility helper; that USD helper is not part of the public OpenAPI contract.

Use client.request_billing(request_id) with the same inference key to retrieve a recorded primary charge after an SSE disconnect. The lookup covers a rolling 24 hours, accepts no dates, and returns an exact decimal cost string, currency, token usage and expiry. Refunds and separately billed extras are excluded. Reused request IDs can return 409; missing charges return 404, never zero. See the billing contract. Prefer the server-generated X-Request-ID from response headers; a caller-supplied ID is not an idempotency key and must be different for every inference execution. The method makes one lookup (plus the automatic retries above for 429 and 5xx; a 404 is not retried). Poll first after about two seconds, then honor Retry-After (30 seconds on 404), add jitter, and stop on success or a permanent error. Pass on_response=callback to the chat, Responses and Messages helpers to receive ResponseMetadata before the response body is read. Capture metadata.headers.get("x-request-id"). NanoGPTError.headers.get("retry-after") preserves retry advice, including HTTP-date values. Python response header names are lowercase. These helpers also accept optional outgoing headers.

For drop-in OpenAI-compatible usage, you can also use the official OpenAI Python SDK with base_url="https://api.nano-gpt.com/api/v1".

API host

The client defaults to the direct API host, https://api.nano-gpt.com, which serves API-key inference and catalog routes and accepts larger requests than the website host. Set base_url to use another host. USD checkout status goes to https://nano-gpt.com when base_url is left at the default, because the direct host doesn't serve it. Browser-session, dashboard and Management API flows belong on https://nano-gpt.com and are not part of this SDK.

Lightning L402 quote retries

x402 payments (XNO/Nano and USDC) were removed on November 20, 2026. Without Lightning, create an account and use an API key with a prepaid balance; see https://docs.nano-gpt.com/introduction. Lightning L402 quotes still use the request headers and paths below.

For POST requests with X-X402: true or an /api/x402/v1/ path, the SDK automatically generates an Idempotency-Key unless you supply one. A new SDK call starts a new payment intent. Anonymous quote requests retry network failures and HTTP 502/503/504 responses up to twice, reusing the same key and request body, whatever max_retries is. The Lightning quote arrives as HTTP 402, which the helpers raise as a PaymentRequiredError with the quote in error.body. It is not retried, and the SDK does not pay invoices.

Payment-proof requests and interrupted response bodies or streams are not automatically retried; authenticated requests get only the general retries above. For retries you manage across separate SDK calls, supply the same private, random UUID in Idempotency-Key; use a new UUID for a new purchase. The server currently deduplicates Lightning quotes only.

For lightning-l402, POST the option's invoiceUrl (extra.invoiceUrl in legacy accepts[]) to get invoice, paymentHash, l402Token and expiresAt. The 402 quote contains no invoice or Lightning challenge. Pay the returned invoice, then replay the original request with Authorization: L402 <token>:<preimage>. Concurrent calls and retries to the same invoice URL reuse one invoice. After a pending/uncertain creation error, retry the same URL with backoff. After 45 seconds, the server recovers a stale claim by looking up the payment ID as BTCPay orderId and adopting an existing matching invoice; only a successful empty lookup allows creation. A 410 means start a new purchase with a fresh quote key. The SDK does not perform this payment flow.

Redirects

The client follows redirects as urllib does, but credential headers stay on the request's origin (scheme, host and port). A redirect to another origin drops Authorization, X-API-Key, Cookie, payment-proof headers and the checkout status key, and they stay dropped for the rest of the chain. A redirect from HTTPS to HTTP is not followed and raises NanoGPTError with the redirect status.

License

MIT

Metadata

Release files for nanogpt-python 0.2.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 nanogpt-python 0.2.0
File Size Uploaded Provenance Actions
nanogpt_python-0.2.0.tar.gz 31.5 kB Without provenance Details for nanogpt_python-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nanogpt-python 0.2.0
File Interpreter ABI Platform Actions
nanogpt_python-0.2.0-py3-none-any.whl Python 3 none any Details for nanogpt_python-0.2.0-py3-none-any.whl

Total release size: 61.3 kB

Release files / nanogpt_python-0.2.0.tar.gz

Download URL nanogpt_python-0.2.0.tar.gz
Size 31.5 kB
Tags Source
SHA-256 checksum
How to use checksums
4cf9d164ab33c3cec1994171e3259c0902e8c76c6393afff2629f8c84db5632c
BLAKE2b-256 checksum
How to use checksums
fff19f17584bce49fa949eadb611edcbd912f0782d629078026cec0a7a06a115
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Release files / nanogpt_python-0.2.0-py3-none-any.whl

Download URL nanogpt_python-0.2.0-py3-none-any.whl
Size 29.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7f7d6e49575089ea2fc6806ffb9a66435395d2efdec3c6a12401a7bdc29617a1
BLAKE2b-256 checksum
How to use checksums
ad21b7756a6a24f31308912ec0e4f3b0f29378ac07cf81ad7635e6188232dbe0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Security for nanogpt-python 0.2.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.2.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