> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nano-gpt.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Quickstart

> A first request, then streaming with errors, usage and request IDs.

## Setup

Create an [API key](https://nano-gpt.com/api) and add [balance](https://nano-gpt.com/balance). These examples use `openai/gpt-4o-mini`, which is paid from balance; with Pro, use a Subscription only key and a model Pro includes, as in [Your first request](https://docs.nano-gpt.com/introduction.md#use-my-pro-allowance). Install `pip install openai` and set `NANOGPT_API_KEY` in your environment. Never put your key in browser code or source control.

## First, a complete response

The SDK base URL is `https://api.nano-gpt.com/api/v1`. This calls `POST /api/v1/chat/completions`.

```python theme={null}
import os
from openai import OpenAI

with OpenAI(
    api_key=os.environ["NANOGPT_API_KEY"],
    base_url="https://api.nano-gpt.com/api/v1",
    timeout=60.0,
    max_retries=0,
) as client:
    response = client.chat.completions.create(
        model="openai/gpt-4o-mini",
        messages=[{"role": "user", "content": "Say hello in one sentence."}],
    )
    print("Request ID:", response._request_id)
    print(response.choices[0].message.content)
```

## Then, streaming

This example closes the HTTP connection even if parsing fails or you stop consuming the stream. The timeout bounds network operations, including time waiting for another chunk; it is not a total generation deadline.

```python theme={null}
import json
import os
import sys
import httpx
from openai import APIError, APIStatusError, OpenAI

# No automatic retries: retrying an interrupted generation can create a new charge.
with OpenAI(
    api_key=os.environ["NANOGPT_API_KEY"],
    base_url="https://api.nano-gpt.com/api/v1",
    timeout=60.0,
    max_retries=0,
) as client:
    try:
        with client.chat.completions.with_streaming_response.create(
            model="openai/gpt-4o-mini",
            messages=[{"role": "user", "content": "Say hello in one sentence."}],
            stream=True,
            stream_options={"include_usage": True},
        ) as response:
            print("Request ID:", response.headers.get("x-request-id", "not supplied"))
            tools = {}
            seen_choices, finished_choices = set(), set()
            for chunk in response.parse():
                if chunk.usage:
                    print("Usage:", chunk.usage.model_dump(), file=sys.stderr)
                # Usage-only frames can have no choices; never assume choices[0].
                for choice in chunk.choices or []:
                    seen_choices.add(choice.index)
                    if choice.finish_reason == "error":
                        raise RuntimeError("Generation failed in-stream; save the request ID before retrying.")
                    if choice.finish_reason is not None:
                        finished_choices.add(choice.index)
                    delta = choice.delta
                    if delta is None:
                        continue
                    reasoning = getattr(delta, "reasoning_content", None) or getattr(delta, "reasoning", None)
                    if reasoning:
                        print(reasoning, end="", file=sys.stderr, flush=True)
                    if delta.content:
                        print(delta.content, end="", flush=True)
                    for part in delta.tool_calls or []:
                        key = (choice.index, part.index)
                        tool = tools.setdefault(key, {"id": "", "name": "", "arguments": ""})
                        if part.id:
                            tool["id"] = part.id
                        if part.function:
                            tool["name"] += part.function.name or ""
                            tool["arguments"] += part.function.arguments or ""
            if not seen_choices or seen_choices != finished_choices:
                raise RuntimeError("Stream ended before completion; save the request ID before retrying.")
            print()
            # Inspect completed calls; validate names/arguments before executing anything.
            for tool in tools.values():
                print("Tool call:", json.dumps(tool), file=sys.stderr)
    except APIStatusError as error:
        print("Request ID:", error.request_id, file=sys.stderr)
        print("HTTP error:", error.status_code, error.response.text, file=sys.stderr)
        raise
    except (APIError, httpx.HTTPError, json.JSONDecodeError, RuntimeError) as error:
        # Mid-stream reads can raise httpx errors directly, outside the SDK wrapper.
        print("Generation failed:", error, file=sys.stderr)
        if isinstance(error, APIError) and error.body is not None:
            print("Error details:", error.body, file=sys.stderr)
        raise
```

The SDK parses SSE and raises for HTTP and in-stream error frames. Usage-only frames, empty deltas, reasoning and fragmented tool calls are handled separately. An early end without a finish reason is treated as an incomplete generation; malformed frames and read timeouts also fail explicitly. Reasoning and tool support depend on the selected model; this prompt does not request tools. The tool-call collector shows how to handle models that emit them; it never executes a tool.

Keep the request ID printed before streaming when reporting an interrupted request. HTTP failures show the status, response body and request ID; avoid exposing raw error bodies or reasoning in public logs. A timeout or interrupted stream does not prove the request was unbilled. Inspect the failure before retrying; honor `Retry-After` on rate limits, and do not retry authentication or validation failures without correcting the request.

## Other endpoints

* [Text generation](https://docs.nano-gpt.com/api-reference/text-generation.md)
* [Image generation](https://docs.nano-gpt.com/api-reference/image-generation.md), including `POST /api/v1/images/generations`
* [Video generation](https://docs.nano-gpt.com/api-reference/video-generation.md), including asynchronous job polling
* [API Hosts](https://docs.nano-gpt.com/api-reference/miscellaneous/api-hosts.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.