Skip to content
qgonDEV DOCSSDK 0.3.31
ENKR

Test serving and the test API

In the appDeploy › PlaygroundExamples checked on SDK 0.3.29

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).

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.

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.

  1. Open Deploy › Playground from the same LAN as the server. Personal keys can be created and deleted only from the LAN.
  2. In the API usage view, go to My personal keys and select Create personal key. Enter a name and pick an expiry.
  3. 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}'
  • 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.json and tokenizer files. In training code, save the folder with save_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.

  1. 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.
  2. Pick a model. The dialog shows the memory it needs and whether it can start now.
  3. Set the idle time before it stops and who can use it (everyone on this server, or only me). Then start it.
  4. 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.

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 value
curl "$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}'
  • With stream on, 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.

Put three functions in the entry file (predict.py by default) in your workspace code folder.

import torch
from qgon import serve
from 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 install does 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.

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.

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 input
qgon serve test --entry predict.py --model outputs/best.pt --image sample.jpg
# Table input
qgon serve test --entry predict.py --model outputs/model.pt --table '{"alcohol": 9.4}'
# Save the result image (serve.image) to a file
qgon serve test --entry predict.py --model outputs/best.pt --image sample.jpg --save-image result.png

It 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.

  1. 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.
  2. 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.
  3. Check the request time limit (30 seconds, 2 minutes, 10 minutes or no limit), GPU use and reserved memory, then start it.
  4. 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

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 [email protected] -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 input
curl "$BASE/serve/$SID/predict" -H "Authorization: Bearer $QGON_KEY" \
-H "Content-Type: application/json" \
-d '{"table": {"alcohol": 9.4}, "params": {}}'
# Several images at once
curl "$BASE/serve/$SID/predict" -H "Authorization: Bearer $QGON_KEY" \

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.
  • params must 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.

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, queue
curl "$BASE/serve/$SID/info" -H "Authorization: Bearer $QGON_KEY" # input kind, classes, limits
curl -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.

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

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: 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/models or /health does not keep it running. A predict request 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_limited with a Retry-After header.
  • 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.
  • If another system needs an address it can always call, promote the test serving to an endpoint. Select Deploy as an endpoint in the API usage view.
  • To start and stop test servings from code as well, get a token as described in REST API.