Guides

AI Gap-Fill & Adapter Training

Use this guide to distinguish a completed training job, an adapter loaded by the local model backend, an eligible cached response, and a result your application can accept. These are separate checks. Start with one selected service and representative requests whose expected behavior you can assert.

Where AI sits in the cascade

Recorded, session and configured stateful responses are distinct from eligible generated-cache responses. In ordinary MOCK, a qualifying cache miss can queue background generation while the caller receives the existing miss behavior. Eligible smart-swap can also request background work; generation is not limited to requests that miss every earlier response source.

Completion, cache admission and a later cache hit are separate outcomes. See the match cascade and background-generation conditions for the serving order rather than treating training as a new universal tier.

Local response generation and network boundaries

Full Compose routes response generation through local inference and the ghost-llamacpp model sidecar. The model container is attached only to the internal model network; inference also joins the default network. This command inspects that one network, not the whole stack's egress:

docker network inspect <project>_llama-isolated
# look for:  "Internal": true

Separately configured API analysis can contact external providers. Review external contacts and telemetry and the stored-data boundaries for your deployment; local model serving is not a whole-stack no-egress claim.

Licensed stack

This guide describes the licensed Docker Compose stack with its inference services. The separate open-source proxy does not include this training workflow.

The llamacpp sidecar & local training

The inference server has one generation path: the sibling ghost-llamacpp sidecar. It does not load an in-process generative model for serving. These inference-container settings distinguish generation from retrieval:

LLAMACPP_ENDPOINT

Routes /generate through the sibling ghost-llamacpp HTTP server. The Full stack sets it to http://ghost-llamacpp:8080. The sidecar serves the quantized base model and any per-service LoRA adapters loaded via --lora. Without an endpoint, the inference server reports generation as unavailable rather than falling back to another backend.

ENABLE_RAG

On by default. Enables retrieval over the local mock library. A qualifying recorded response can be returned without applying an adapter; retrieval and generated responses have different origins.

ENABLE_GENERATION

Retired. In-process PyTorch serving has been removed: a leftover true value is ignored with a startup warning and never loads a model for serving. You can delete it from older .env files.

# Full stack: generation through the isolated sidecar, grounded by retrieval
docker compose up ghost-inference ghost-llamacpp

# Set on ghost-inference by the Full stack
LLAMACPP_ENDPOINT=http://ghost-llamacpp:8080   # the only generation backend
ENABLE_RAG=true                                # retrieval grounding (on by default)

Adapter training is local. Each training job runs as a worker process inside ghost-inference, fits a LoRA adapter for one service, and converts it to the GGUF format the sidecar loads. No external training service is involved. In the shipped image it runs on CPU, because the image carries the CPU build of PyTorch. The trainer uses a CUDA GPU when PyTorch sees one, so a ghost-inference image you build with a CUDA build of PyTorch, given a GPU, trains on it. On such a container, set FINETUNE_DEVICE=cpu in its environment to keep training on the CPU, or FINETUNE_DEVICE=cuda to fail a run that finds no GPU; the default is auto. The shipped Compose files do not pass it from .env, so set it where you set the custom image, for example in a Compose override for ghost-inference.

Inspect the resource limits

Full Compose defaults to a 12G memory limit for inference, 6G for the model sidecar and four CPUs each. Training loads the base model in its worker process. These are configured limits, not a guarantee that a particular job or number of adapters will fit. Inspect the effective limits and memory pressure for your workload, and see Inference CPU and memory to change them. Lite omits the AI containers.

Per-service LoRA adapters

A per-service LoRA adapter specializes base-model weights for one API without retraining the whole model. Whether its responses help your application must be checked on representative held-out cases.

The most important property: adapters train only on rows marked as scrubbed. The training stream is drawn from the Postgres mock library, not from the verbatim local replay library the deterministic tiers serve from, and training reads only rows that carry the scrubbed mark. Recorded traffic and newly admitted snapshot Postgres rows receive the broader scrub pipeline before they are marked. Imported and seeded mocks receive structural credential redaction and a sensitive response-header floor before storage; that insert step does not set the scrubbed mark, so unmarked rows are excluded from training. A scrubbed mark is not a guarantee that every sensitive value was removed; review the data and detection limits.

Use the dashboard's Fine-tuning page (New Training Session) or these control-plane operations, relative to your installation's API base. This is an operation inventory, not a complete request/payload recipe. See API authentication and the training reference. Training and activation require member authorization and the inference entitlement. The session and service must belong to your tenant; activation rejects a different requested service.

POST /v1/training/versions/generate-context
POST /v1/training/sessions/{session_id}/train
GET  /v1/training/sessions/{session_id}/status
POST /v1/training/sessions/{session_id}/activate

A training session needs at least 20 examples for its service. Examples are the service's scrubbed mock-library rows described above: a recorded request becomes one when you choose Build mocks, and imported and seeded mocks do not count. The examples of any OpenAPI specification attached to the session also count. With fewer than 20, the session fails, and its failure message says how many examples it found. The Fine-tuning page shows how many examples a draft has now, for example "12 of 20 examples", and keeps Train Model unavailable below 20. Recordings can still change before the run starts, and the run counts them again.

  1. Create a version for the selected service, then start training. The start acknowledgement means admission, not successful training.
  2. Inspect status and its failure message. A failed terminal session can report 100% progress. A ready session still needs valid finalized artifacts, loading and activation. See Training time and failed runs for what the messages mean.
  3. Activate that exact session. Inspect serving_ready, reason/action, the returned service and session, and binding revision. Prepared or pending is not serving; resolve rejected outcomes before continuing.
  4. On the Fine-tuning page, activation is the Attach button. After every training run the first Attach is refused, unless the model service has restarted since the run finished: the page shows a red message that starts "Attach failed: Adapter activation failed: llamacpp_restart_required". That is expected, because the model service loads adapter files only when it starts. Run the command below in the install folder, wait until docker compose ps shows ghost-llamacpp as healthy, then choose Attach again; the version then shows ACTIVE. If a red message comes back, wait a little and choose Attach again. The restart alone does not activate the adapter.
docker compose restart ghost-llamacpp

Serving readiness covers the acknowledged local agent process, not every replica. Finally, use your own caller to assert required values, error handling and state transitions. Accept the result only after those caller-level checks pass.

Adapter files load in the model backend; response-cache entries live separately in the agent. The cache key includes method, URI, service, body and adapter session/revision. Reuse lasts while an entry remains eligible and current: TTL expiry, eviction, invalidation or a binding change can require another generation attempt. A repeat request does not guarantee a cache hit.

Compare retrieval and adapter behavior

Keep representative held-out requests and expected outcomes fixed when comparing recorded retrieval with adapter generation. Inspect failures and unmatched cases alongside accepted responses. There is no example-count threshold here that establishes one approach as better.

Training time and failed runs

Training runs on the CPUs of the ghost-inference container, which may use four CPUs and four threads by default. A run takes longer the more examples the session has. On four CPUs, a run on 30 examples takes about three hours: 18 training steps of about nine minutes each, and three evaluations. Once a draft has 20 examples, the Fine-tuning page gives its estimate from that measurement. For a first run, keep the session close to the 20-example minimum. To give the container more CPUs, threads or memory, see Inference CPU and memory.

The progress figure moves after every training step. It shows 20% when fine-tuning starts, 90% when the last step ends, and 100% once the adapter is saved and converted. The evaluation at the end of each epoch moves it a little after each batch of eight held-out examples. On four CPUs a step takes about nine minutes and a batch about eleven, so the figure can stand still for about 20 minutes during a healthy run.

The time limits fail a run that stops making progress, not one that is only long. For its first two hours, a run is failed only if its trainer stops responding. After two hours it goes on while its trainer responds and its progress moves at least once an hour; a run whose progress has stood still for an hour is failed. No run goes on past 24 hours. These limits are ghost-web settings in .env: TRAINING_IDLE_TTL_SECS (900 seconds without a response from the trainer), TRAINING_STUCK_TTL_SECS (7200, the two hours), TRAINING_STALL_TTL_SECS (3600, the hour without progress) and TRAINING_MAX_TTL_SECS (86400, the 24 hours). After changing one, run docker compose up -d. If a service has more recordings than you want to wait for, train on part of them: open Filters on the Fine-tuning page, select the service, type part of a path in URI contains (for example /v1/orders), and choose New Training Session. The session then uses only the recordings whose path and query contain that text; the match is literal and case-sensitive. The 20-example minimum applies to what is left. Once the run has started, View corpus shows how many records it uses.

To train again after a failure, select the failed version on the Fine-tuning page and choose Create new version: this makes a new draft with the same service and filters. Then choose Train Model. Where a failure message says "Retrain to try again", this is how.

What these failure messages mean:

  • Training did not complete within 120 min and was reaped ... The run reached two hours without ever sending a heartbeat, which only a session started by an older version can do. Start a new version.
  • Training made no progress for over 60 min after running ... min and was reaped ... The run was past two hours, its trainer still responded, and its progress had stood still for an hour: the trainer is likely stuck. Start a new version; if it happens again, restart ghost-inference first.
  • Training ran for 1440 min, the most a run may take (TRAINING_MAX_TTL_SECS), and was reaped ... The run reached the 24-hour limit while it was still making progress. Train a smaller session, or raise TRAINING_MAX_TTL_SECS, and start a new version.
  • Training worker shut down The inference service stopped or restarted while the run was in progress, for example because docker compose up -d applied a change to ghost-inference. Check with docker compose ps -a that the container is running, then start a new version.
  • Training worker stopped responding for over 15 min (no heartbeat) and was reaped ... The training process stopped reporting, for example because the container was killed or the host restarted. Check the container the same way, then start a new version.
  • force-failed by operator A user with the admin or owner role chose Force fail on the run.

There is no cancel button. A user with the admin or owner role can choose Force fail on a run that is in training: the session is marked failed at once, so that you can create a new version. Force fail does not stop the training process itself. Like the process of a run the time limits failed, it keeps running in the container until it finishes or the container restarts, and a new run started meanwhile shares the container's CPUs with it. To stop it, restart the container: docker compose restart ghost-inference. This also fails any other run that is training.

Sending a request the adapter can answer

The model's answer is served only in MOCK mode and only when nothing earlier in the match cascade answers the request. The first send of such a request returns the miss response (404 by default, with X-Ghost-Miss: true and X-Gostly-Miss-Reason: pending) while the model works in the background. Send the same request again after the Retry-After interval. An answer from the model carries X-Ghost-Generated: true, and X-Ghost-Source: generative means the service's adapter was applied. The answer is kept until the adapter changes, so the same request keeps getting the same bytes; INFERENCE_CACHE_TTL_SECONDS sets an expiry instead.

A request with the path shape of a recorded request is first tried by smart swap. When it differs from the recording only in an id in the path, or in the value of a query parameter the recording also has, smart swap can answer it from that recording with the new value put in (X-Ghost-SwapMatch: true); the recording's other values stay as recorded. Smart swap answers before the model, so such a request does not return the model's answer. A path segment counts as an id when it is a number, a UUID, or a mix of letters and digits such as s3-orders; a version such as v1 does not. To see the adapter answer, send something no recording has in that form, for example a recorded path with a new query parameter.

On a path that has no recording of the same shape, the model is asked only when something shows that the endpoint answers text: an Accept header that names a text type, such as Accept: application/json, a path that ends in a text extension such as .json, a JSON request body (Content-Type: application/json), or recordings of the same service that answer JSON with none of them binary. Accept: */*, which curl sends by default, is not enough on its own: on a service with no JSON recordings, every send returns the miss response with X-Gostly-Miss-Reason: media_unknown and nothing is generated.

The model's output is compared with your recordings only when the service has a recording of the same method and path shape, made without a query string or with the same query string as the request. In that case, output that is not valid JSON, or a JSON object that lacks a top-level field those recorded responses have, is dropped. In every other case, such as a path with no recording of that shape, or a query string that differs from the recorded one, the output is served as generated at the default confidence threshold, with X-Ghost-Confidence: 0.70 unless a similar recording was found for it. A generation that takes longer than 120 seconds (the default) is discarded. After dropped or discarded output the request keeps returning the miss response (X-Gostly-Miss-Reason: degraded for dropped output) and is tried again after a back-off. The miss body's hint reads "no recording matches: record it in LEARN mode, or retry if the service generates answers"; a workspace that saved its own body under Settings > Unmatched Response keeps that saved text instead. Compare generated answers with your real API before you rely on them.

Knowing when a response was generated

The inference /generate envelope carries a source field distinguishing recorded retrieval, base-model generation and adapter generation, a confidence signal, and degraded. These fields describe the inference-service envelope; do not assume that envelope is the body your application receives. Inspect the caller-facing provenance headers to inspect the serving origin.

Confidence reflects similarity or a prior, not the probability of business correctness. Repaired or template output is flagged degraded; the agent drops degraded output rather than caching it as genuine generation. Neither a source label nor a non-degraded result replaces your application assertions.

Cold-start seeding

You don't have to record live traffic to give the gap-fill engine something to work with. Existing artifacts can seed the mock library directly — drag-drop a HAR capture, a Postman collection, or an OpenAPI spec into the dashboard, which posts to the control-plane seeding endpoints:

POST /v1/seed/har
POST /v1/seed/postman
POST /v1/seed/openapi

Seeded entries enter the mock library and serving files after credential-focused redaction. This is not a general personal-data scrub and does not set the scrubbed mark required for adapter training. Seeding can supply exact-match coverage and local retrieval grounding; review source files for sensitive values outside the import rules before uploading. Captured local replay bodies and restored snapshot replay files retain their separate data boundary. See the security model.

Observability

The agent exposes Prometheus metrics at /metrics. Match counters describe serving outcomes, not how many model calls were made or how many application tests passed:

ghost_requests_total{match_type}

Request counter by match-path outcome. generated_cached counts eligible AI-tier cache serves, including recorded retrieval; it is not generation attempts, adapter adoption or accepted results.

ghost_mock_library_size

Mock-library size gauge — how much recorded coverage the deterministic tiers have to draw on.

ghost_io_errors_total{operation}

Disk-sink open/write failures by operation.

axum_http_requests_total / _duration

HTTP request rate and latency by endpoint, method, and status.

Name the service, time window and denominator when reporting a share. Keep misses, queue drops, generation failures and degraded-output drops separate from cache serves, using the relevant status and error evidence alongside the counters. No mix is guaranteed to be healthy, and zero misses do not establish realistic behavior or business correctness.

Check application acceptance

Use an authored quote plan to freeze input controls, reserve held-out families and record actual caller observations. Keep response origin, serving and application acceptance distinct; the plan is not a model-quality benchmark. Read the worked example.

Next steps