Test serving and the test API
Read this page to start a model on the server, test it, and call the same model over HTTP from your own program. LLMs are called through an OpenAI-compatible address. Models such as classifiers and detectors run with your own inference code (predict.py).
Test serving and the test API
Section titled “Test serving and the test API”A model started in Deploy › Playground is a test serving. You can chat with it or upload an image and see the result right in the app. The address your programs use to call that test serving is the test API.
http://<server address>:<web port>/serve/<serving id>/…A test serving is for testing. It stops by itself after a set time with no requests, and its test API address goes away with it. If another system needs an address it can always call, promote it to an endpoint.
| Kind | What runs | Paths |
|---|---|---|
| LLM chat | A conversational LLM | /v1/models, /v1/chat/completions, /v1/completions, /v1/embeddings |
| My inference code | Your predict.py and a model file |
/predict, /info, /cancel |
Both kinds report their state at /health. Paths not in the table are not open.
Create a personal key
Section titled “Create a personal key”Programs call the test API with a personal key (qgk_…). It is not the API key (access/secret) you create in settings. A personal key can call only test APIs, and endpoints within their scope. It cannot call the rest of the qgon API.
- Open Deploy › Playground from the same LAN as the server. Personal keys can be created and deleted only from the LAN.
- In the API usage view, go to My personal keys and select Create personal key. Enter a name and pick an expiry.
- Copy the key value right away. It is shown only once, and the server keeps only a hash.
Each person can hold up to five personal keys. Deleting a key blocks calls made with it at once. If an account is deleted, that person's personal keys stop working too.
Do not write key values in code. Pass them in an environment variable. The examples below all use the name QGON_KEY.
export QGON_KEY="qgk_…"You can also create one through the API. See REST API for how to get a token. The key field in the response is the key value, and only this response shows it.
BASE="http://<server address>:<web port>"curl -X POST "$BASE/qgon-api/account/serve-keys" \ -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ -d '{"name": "laptop", "expires_days": 90}'Start and call an LLM
Section titled “Start and call an LLM”Models you can start
Section titled “Models you can start”- A base LLM brought onto the server through the import center or the installer (
install.sh import-model). - A registered model made of safetensors weights,
config.jsonand tokenizer files. In training code, save the folder withsave_pretrained(…, safe_serialization=True)and upload it as the model.
Pickle-based weights such as .bin, .pt and .pkl, user code (.py), or an auto_map in config.json will not start. These formats can run code the moment the file is opened.
Anyone on the server can start a published model under their own name. An unpublished model can be started only by its author (or the author of the run that made it) and admins. The memory is counted against the person who starts it.
Start it
Section titled “Start it”- In Deploy › Playground, select Start a model and choose LLM chat as the kind. Start in Playground on a model's details in Deploy › Models opens the same dialog.
- Pick a model. The dialog shows the memory it needs and whether it can start now.
- Set the idle time before it stops and who can use it (everyone on this server, or only me). Then start it.
- When the list shows Ready, chat in Chat or copy the address from API usage.
Some models show a notice that the model file stayed inside the training container and never reached the server. This happens when the model was trained with an environment saved with an old SDK. Update the SDK in the workspace, save the environment as a new version, and train again with that version.
Call an LLM
Section titled “Call an LLM”The test API is OpenAI compatible. The address is $BASE/serve/<serving id>/v1. For the model value, use the name that /v1/models returns.
BASE="http://<server address>:<web port>"SID="<serving id>"
# Find the model valuecurl "$BASE/serve/$SID/v1/models" -H "Authorization: Bearer $QGON_KEY"
curl "$BASE/serve/$SID/v1/chat/completions" \ -H "Authorization: Bearer $QGON_KEY" -H "Content-Type: application/json" \ -d '{"model": "<model name>", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 128}'# pip install openaiimport osfrom openai import OpenAI
BASE = "http://<server address>:<web port>"client = OpenAI(base_url=f"{BASE}/serve/<serving id>/v1", api_key=os.environ["QGON_KEY"])
model = client.models.list().data[0].id # name of the running modelstream = client.chat.completions.create( model=model, messages=[{"role": "user", "content": "Hello"}], max_tokens=128, stream=True,)for chunk in stream: if chunk.choices: print(chunk.choices[0].delta.content or "", end="", flush=True)- With
streamon, the response arrives as SSE chunks. - Default sampling values come from the model's
generation_config.json. - Request bodies are accepted up to 4 MB.
Start with your own inference code (predict.py)
Section titled “Start with your own inference code (predict.py)”Models that are not LLMs (image classification, detection, segmentation, keypoints, tabular regression) run with inference code you write. For each request the server calls your predict() and checks the result against a fixed shape. The app draws that result on top of the uploaded image.
Code contract
Section titled “Code contract”Put three functions in the entry file (predict.py by default) in your workspace code folder.
import torchfrom qgon import servefrom mynet import build_model, preprocess # your own module in the same code folder
def load(model_dir): """Once, at start. model_dir is the read-only model folder.""" ck = torch.load(serve.model_file(model_dir), map_location="cpu", weights_only=True) net = build_model() net.load_state_dict(ck["model"]) return {"net": net.eval(), "classes": ck["classes"]}
@torch.inference_mode()def predict(m, inp): """Per request. inp.image (PIL RGB, photo orientation applied) · inp.image_bytes · inp.table · inp.params""" p = torch.softmax(m["net"](preprocess(inp.image)), 1)[0] return serve.labels(m["classes"], p.tolist(), top_k=5)
def describe(m): """(Optional) Input kind and class list. Used for the legend and the table input form.""" return serve.describe(input="image", labels=m["classes"])serve.model_file(model_dir)finds the model file path inside the model folder.- Load model files made by someone else with
weights_only=True. A pickle file can run code the moment it is opened. - A test serving has no outside network, so
pip installdoes not work. The packages you need must already be in the environment version you pick when starting. - Models trained from a starter template already include
predict.py.
Result shapes
Section titled “Result shapes”predict() returns a value built by one of these functions. Coordinates are pixels of the input image.
| Function | Use | Example |
|---|---|---|
serve.labels(names, scores, top_k=5) |
Classification | serve.labels(["cat", "dog"], [0.9, 0.1]) |
serve.boxes(items, xyxy=False) |
Detection. bbox is [x, y, w, h] |
serve.boxes([{"bbox": [10, 20, 50, 40], "label": "car", "score": 0.8}]) |
serve.masks(items) |
Segmentation. One of mask (H×W array), polygon or rle |
serve.masks([{"mask": m, "label": "road", "score": 0.7}]) |
serve.values(v) |
Values (tabular regression and similar) | serve.values({"quality": 5.6}) |
serve.keypoints(items, names=None, skeleton=None) |
Keypoints. Each point is [x, y, v] |
serve.keypoints([{"keypoints": kps, "score": 0.9}], names="coco17") |
serve.image(img, format="png", quality=90) |
A result image. The app shows it next to the input | serve.image(drawn, format="jpeg") |
serve.text(s) |
Text | serve.text("description") |
serve.combine(*parts) |
Several results in one | serve.combine(serve.boxes(b), serve.image(drawn)) |
Scores are between 0 and 1. A result image can be up to 4096 pixels on the long side and 4 MB. If the shape is wrong, the server returns 502 bad_output and says where it went wrong (a location such as boxes[3].bbox). The accepted values and limits for each function are in the qgon.serve reference.
Test in the workspace before starting
Section titled “Test in the workspace before starting”Before you start a serving, run it once with qgon serve test in a workspace terminal. It parses the input and checks the result the same way the serving does, then prints the response JSON.
# Image inputqgon serve test --entry predict.py --model outputs/best.pt --image sample.jpg
# Table inputqgon serve test --entry predict.py --model outputs/model.pt --table '{"alcohol": 9.4}'
# Save the result image (serve.image) to a fileqgon serve test --entry predict.py --model outputs/best.pt --image sample.jpg --save-image result.pngIt exits with 0 on success, 1 on failure and 2 on a usage error.
qgon serve pack builds the code bundle that would be pinned at start. It uses the same exclusion rules as qgon run (secret files, .qgonignore, .gitignore, virtual environments, checkpoint extensions). You can see whether the bundle is too large or misses the entry file before you start.
qgon serve pack --json --entry predict.py --out /tmp/bundle.zip .All options are in qgon command.
Start it in the app
Section titled “Start it in the app”- Start the workspace that holds the code. The code folder is bundled and pinned the moment the serving starts, so the workspace must be running then. After that, the test serving stays the same even if you edit the code or stop the workspace.
- In Deploy › Playground, select Start a model, choose My inference code as the kind, and pick a model. The workspace, code folder, entry file and environment version are filled in from the run that made the model.
- Check the request time limit (30 seconds, 2 minutes, 10 minutes or no limit), GPU use and reserved memory, then start it.
- When it is ready, drop an image or enter table values in the Try inference code view to see the result.
The reserved memory becomes the memory limit of the test serving container. GPU memory is not capped by the reservation, so when the server runs low on memory, the memory guard stops the most recently started workload first.
If starting fails, the list shows a reason.
| Reason | Meaning |
|---|---|
code |
The entry file or the load or predict function was not found (including when .qgonignore left it out) |
pack |
The code could not be bundled |
load |
load() raised an exception. The message includes its first line |
load_timeout |
load() did not finish within the safety limit |
crashloop |
It crashed several times in a short period |
oom |
It went over the reserved memory |
memguard |
The server ran low on memory and the memory guard stopped it |
Call predict
Section titled “Call predict”The address is $BASE/serve/<serving id>/predict. Send images as multipart files or as base64 inside JSON. params is passed to predict() as inp.params.
BASE="http://<server address>:<web port>"SID="<serving id>"
# Image file (multipart)curl "$BASE/serve/$SID/predict" -H "Authorization: Bearer $QGON_KEY" \ -F image=@photo.jpg -F 'params={"threshold": 0.5}'
# base64 inside JSON (sent through standard input so large photos work too)python3 -c 'import base64,json,sys; print(json.dumps({"image": base64.b64encode(open(sys.argv[1],"rb").read()).decode(), "params": {}}))' photo.jpg \ | curl "$BASE/serve/$SID/predict" -H "Authorization: Bearer $QGON_KEY" \ -H "Content-Type: application/json" --data-binary @-
# Table inputcurl "$BASE/serve/$SID/predict" -H "Authorization: Bearer $QGON_KEY" \ -H "Content-Type: application/json" \ -d '{"table": {"alcohol": 9.4}, "params": {}}'
# Several images at oncecurl "$BASE/serve/$SID/predict" -H "Authorization: Bearer $QGON_KEY" \ -F image=@a.jpg -F image=@b.jpg -F image=@c.jpg# pip install requestsimport jsonimport osimport requests
BASE = "http://<server address>:<web port>"H = {"Authorization": "Bearer " + os.environ["QGON_KEY"]}
with open("photo.jpg", "rb") as f: r = requests.post(f"{BASE}/serve/<serving id>/predict", headers=H, files={"image": f}, data={"params": json.dumps({"threshold": 0.5})}, timeout=None)r.raise_for_status()print(r.json()["result"])The response holds qgon_serve (the response shape version), id, serving, model, image (size and photo orientation), result and timing_ms. result is what predict() returned.
{"type": "labels", "labels": [{"label": "cat", "score": 0.9}, {"label": "dog", "score": 0.1}]}Inputs have these limits.
- The body can be up to 12 MB, and each image file up to 10 MB.
- Images can be JPEG, PNG, WebP, BMP or GIF. HEIC is not accepted yet.
paramsmust be a JSON object of up to 4 KB.- You can send up to 16 images at once. In JSON the form is
{"images": ["<base64>", …]}.
With several images the response becomes {"batch": {…}, "items": [ … ]}. Each item has ok. An image with a bad format, or one where predict() raised an error, fails on its own. A cancel or a timeout stops the batch there, and the remaining images are not processed. The time limit for a whole multi-image request is limits.batch_max_s in GET …/info.
Check state and cancel
Section titled “Check state and cancel”A test serving handles one request at a time and queues the ones that arrive after it. When the queue is full it returns 429 busy.
curl "$BASE/serve/$SID/health" -H "Authorization: Bearer $QGON_KEY" # state, busy, queuecurl "$BASE/serve/$SID/info" -H "Authorization: Bearer $QGON_KEY" # input kind, classes, limitscurl -X POST "$BASE/serve/$SID/cancel" -H "Authorization: Bearer $QGON_KEY"cancel stops the running request. Only the person who sent the request, the person who started the test serving, or an admin can use it. The stopped request ends with 409 cancelled. The server reloads the model and then continues with the queued requests.
Errors
Section titled “Errors”Test API errors use the OpenAI shape {"error": {"message", "type", "code"}}. The message is in Korean.
| Status | code |
Meaning |
|---|---|---|
| 400 | bad_input |
The input is malformed |
| 401 | unauthorized |
The key is missing or wrong |
| 403 | forbidden, not_found, not_ready, external_denied |
Outside the sharing scope, no such test serving, still starting, blocked by the external access level |
| 409 | cancelled |
The request was cancelled |
| 413 | too_large |
The body or image is too large |
| 415 | unsupported_image |
The image format is not accepted |
| 422 | predict_error |
predict() raised an exception |
| 429 | busy, rate_limited |
The queue is full, or too many requests |
| 502 | bad_output |
predict() returned the wrong shape |
| 503 | unavailable |
The engine could not be reached (it may be stopping) |
| 504 | predict_timeout |
The request went over the time limit |
Call from inside the server
Section titled “Call from inside the server”Code inside a workspace or a training job uses the in-server address.
from openai import OpenAI
client = OpenAI(base_url="http://qdix-gateway:82/serve/<serving id>/v1", api_key="qgk_…")The workspace key that the workspace SDK uses cannot call the test API. Use a personal key inside the server as well.
Sharing, limits and automatic stop
Section titled “Sharing, limits and automatic stop”- Sharing: Each test serving is set to everyone on this server (the default) or only me. You can change it after starting.
- Automatic stop: It stops after the set time passes since the last inference request. Only real inference requests (chat, completion, embeddings and
predict) reset the clock. Calling only/v1/modelsor/healthdoes not keep it running. Apredictrequest in progress delays the stop. - How many can run: The admin sets, in Settings › Test serving, how many test servings can run on the server and per person, and the reserved memory cap for one. LLM and custom inference code servings count together.
- Call rate: There is a per-second call cap per key and per client address. Going over returns 429
rate_limitedwith aRetry-Afterheader. - Logs: The person who started the test serving and admins can read its log. The log records the account name of the caller for each request.