AiCredits
Notebook to Prod

From Notebook to API: Serving Your LLM Prototype Around the Clock

Turn a Jupyter LLM prototype into a 24/7 API: async client setup, retries, concurrency caps, caching, health checks, and a deployment checklist that lasts.

Published 2026-11-26 Updated 2026-11-26 9 min

Why the notebook version dies at 3 a.m.

Notebooks are great for discovering that a prompt works, and terrible for discovering that it stops working once you close the lid. The distance between a cell that returns a nice summary and a service that answers at 3 a.m. is rarely model quality. It is a short list of unglamorous decisions: where the API key lives, what happens on a timeout, how many requests hit the model at once, and which process restarts yours when it crashes.

Below is the whole path for a single-endpoint prototype: text in, summary out. Every snippet runs as written against the AiCredits DeepSeek endpoint, with deepseek-v4-flash as the default model and deepseek-v4-pro reserved for requests that actually earn it.

Step 1: Move the key and the client out of the notebook

The first thing to break in production is a hardcoded key sitting in cell 3. Read it from the environment, and keep one client instance for the whole process so HTTP connections are pooled instead of rebuilt on every request. In a notebook you can afford a fresh client per cell; under load you cannot.

Set an explicit timeout. A summarization endpoint that can hang indefinitely will quietly fill your concurrency slots with zombie requests. Also set max_retries=0 at the client level and handle retries in your own service code, so retries are counted, logged and visible instead of hidden inside a library. Run the smoke test below once to confirm the key and base URL work before wrapping anything in FastAPI.

import asyncio
import os

from openai import AsyncOpenAI

client = AsyncOpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
    timeout=45.0,
    max_retries=0,  # retries are handled explicitly in the service layer
)


async def main() -> None:
    resp = await client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[{"role": "user", "content": "Reply with the single word: ready"}],
        max_tokens=8,
    )
    print(resp.choices[0].message.content)


if __name__ == "__main__":
    asyncio.run(main())

Step 2: Make every model call retryable and bounded

Three failure modes matter when a model call sits on the critical path: the request is slow, the provider pushes back with a rate limit, and the endpoint is briefly unreachable. All three are transient and none of them should reach your user as a 500 if a short backoff fixes it. What you should not retry is a bad request — malformed messages, an unknown model name or a payload beyond the context limit will fail identically every single time.

The second half of the problem is concurrency. Without a cap, one traffic spike becomes thousands of in-flight calls, and the retry storm after a hiccup makes it worse. A semaphore around the client call is the cheapest, most effective protection you can add. The service below combines retries, the concurrency cap, a content-hash cache, and a health check that actually verifies the upstream instead of returning a cheerful 200 while the key is expired.

# app.py — a 24/7-ready wrapper around one model call
import asyncio
import hashlib
import logging
import os
import random

from fastapi import FastAPI, HTTPException
from openai import (
    APIConnectionError,
    APITimeoutError,
    AsyncOpenAI,
    RateLimitError,
)
from pydantic import BaseModel, Field

log = logging.getLogger("summarizer")

client = AsyncOpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
    timeout=45.0,
    max_retries=0,
)

app = FastAPI(title="summarizer")
SEM = asyncio.Semaphore(int(os.environ.get("MAX_CONCURRENCY", "8")))
CACHE: dict[str, str] = {}

SYSTEM = "You are a concise technical editor. Summarize in at most five sentences."


class SummarizeRequest(BaseModel):
    text: str = Field(min_length=1, max_length=20000)
    tier: str = "fast"  # "fast" -> flash, "pro" -> pro


async def call_model(messages: list[dict], model: str, attempts: int = 4) -> str:
    for attempt in range(attempts):
        try:
            async with SEM:
                resp = await client.chat.completions.create(
                    model=model,
                    messages=messages,
                    temperature=0.2,
                )
            log.info(
                "model_call model=%s tokens=%s finish=%s",
                model,
                resp.usage.total_tokens if resp.usage else "n/a",
                resp.choices[0].finish_reason,
            )
            return resp.choices[0].message.content or ""
        except (RateLimitError, APITimeoutError, APIConnectionError) as exc:
            if attempt == attempts - 1:
                raise
            delay = 2 ** attempt + random.random()
            log.warning("retrying in %.1fs after %s", delay, type(exc).__name__)
            await asyncio.sleep(delay)
    raise RuntimeError("unreachable")


@app.get("/health")
async def health() -> dict:
    await client.chat.completions.create(
        model="deepseek-v4-flash",
        messages=[{"role": "user", "content": "ping"}],
        max_tokens=1,
    )
    return {"status": "ok"}


@app.post("/summarize")
async def summarize(req: SummarizeRequest) -> dict:
    model = "deepseek-v4-pro" if req.tier == "pro" else "deepseek-v4-flash"
    key = hashlib.sha256(f"{model}:{req.text}".encode()).hexdigest()
    if key in CACHE:
        return {"summary": CACHE[key], "model": model, "cached": True}

    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": req.text},
    ]
    try:
        summary = await call_model(messages, model)
    except Exception:
        log.exception("model call failed")
        raise HTTPException(status_code=503, detail="model temporarily unavailable")

    if len(CACHE) > 5000:
        CACHE.clear()
    CACHE[key] = summary
    return {"summary": summary, "model": model, "cached": False}
  • SEM caps in-flight calls per process. Size it to your upstream quota, not to your CPU count.

  • The retry loop backs off with jitter and re-raises after the final attempt, so the endpoint returns a clean 503 instead of hanging forever.

  • The cache is keyed on model plus input, so identical repeat requests cost nothing. Swap the dict for Redis the moment you run more than one worker.

  • /health makes a real one-token call. Load balancers need to tell the difference between the process being alive and the dependency being reachable.

Step 3: Run it under a supervisor, not a kernel

A notebook kernel is not a supervisor. Close the browser and the process dies; re-run one cell and it keeps running with stale state. Run the app under uvicorn with a restart policy, and point it at an environment file rather than an exported variable that only exists in your shell session.

pip install "fastapi" "uvicorn[standard]" "openai" "pydantic"
uvicorn app:app --host 0.0.0.0 --port 8000 --workers 2
[Unit]
Description=summarizer api
After=network-online.target

[Service]
EnvironmentFile=/etc/summarizer.env
ExecStart=/opt/summarizer/.venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000 --workers 2
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

Two operational details bite people here. First, --workers N means N separate Python processes: each gets its own semaphore and its own in-memory cache, so effective concurrency is N times MAX_CONCURRENCY and your cache hit rate drops. Start with one or two workers and a smaller per-worker cap, and move to a shared cache before scaling out. Second, the unit above restarts on crash but not on a hung process — that is what the /health probe is for, whether your host is Kubernetes, a container platform, or a plain VM checked by cron.

Step 4: Keep an always-on bill predictable

Always-on means idle cost as well as busy cost. The model split does most of the work: deepseek-v4-flash handles the overwhelming majority of summarization, classification and extraction traffic, while deepseek-v4-pro is reserved for requests that genuinely need deeper reasoning. Beyond that, the real savings come from not calling the model at all when you can avoid it, and from keeping prompts byte-stable so repeated prefixes can be served from cache — cache hits are cheaper than fresh tokens, and off-peak traffic costs less than peak. Check aicreditsapi.com/deepseek-prices for current rates before you size anything.

  • Default to flash. Expose a tier flag and let the caller opt into pro deliberately.

  • Deduplicate before you generate: hash the input, return the stored answer, skip the call.

  • Batch anything that is not user-facing into a nightly job instead of doing it inline.

  • Keep the system prompt stable — editing it invalidates both your cache and your ability to compare logs week over week.

  • Log token usage per request. A service that cannot say what it consumed yesterday cannot be tuned.

Notebook habitProduction equivalent
Key pasted into a cellEnvironment variable or secret manager
One synchronous call per cellAsync client, retry loop, concurrency cap
Prints for debuggingStructured logs with model, tokens, latency
Re-run the cell on failureIdempotent endpoint plus exponential backoff
Fresh kernel, fresh stateExplicit cache with eviction
You watch it runProcess supervisor plus `/health` probe

Rule of thumb: flash by default, pro by exception, and only once your logs prove the exception is real.

Checklist before you call it done

  • The key is in the environment, never in the repo or the notebook output.

  • Every model call has a timeout, a retry budget and a concurrency cap.

  • Bad requests fail fast with a 4xx and never enter the retry loop.

  • /health exercises the upstream, not just the web framework.

  • Token usage and cache hit rate are logged per request.

  • One worker was tested before you scaled to many.

FAQ

Do I need a GPU to serve an LLM prototype?

No. The service above calls a hosted model over HTTPS; your server only holds connections and runs FastAPI. That is why a small VM is enough to keep a prototype online around the clock.

How do I keep it running when my laptop is closed?

Move it off the laptop. Any always-on host — a cheap VM, a container platform, or a serverless container — plus a restart policy and a /health probe gets you most of the way.

Should I stream responses?

Stream when a human is waiting on a long answer, because perceived latency drops noticeably. For batch or machine-consumed output, non-streaming is simpler to cache, retry and test.

What about jobs that take minutes?

Do not hold the HTTP request open. Put the job on a queue, return an id, and let a worker write the result. Your endpoint stays fast and retries become safe.

Which model should be the production default?

deepseek-v4-flash. It is the right default for high-volume work; escalate to deepseek-v4-pro per request or per route, and only where your logs show flash is actually falling short.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link

服务器宕机了?别等用户告诉你

Wakeless 梦哨 帮你 30 秒监控网站 / API / SSL 证书,宕机秒级告警到邮箱、飞书、Slack。免费档 30 个监控,永久免费,无需信用卡。

免费开始监控 →
💬
反馈意见 / Feedback ×