Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,33 @@ GENERATION_SHUTDOWN_TIMEOUT=5m
# iterations.
GENERATION_MAX_ITERS=60

# ----- Embeddings (optional; enables RAG over the saved-build library) -----
# Unset EMBEDDING_BASE_URL = recency-only retrieval, no pgvector required.
# Set it to an OpenAI-compatible /v1 root to enable semantic seeding.
#
# Local default: LM Studio (Developer tab -> load an embedding model -> start
# server). Ollama and llama.cpp expose the same /v1/embeddings shape; only the
# port and model id differ:
# LM Studio: EMBEDDING_BASE_URL=http://localhost:1234/v1
# Ollama: EMBEDDING_BASE_URL=http://localhost:11434/v1 (ollama pull nomic-embed-text)
# llama.cpp: EMBEDDING_BASE_URL=http://localhost:8080/v1
#
# EMBEDDING_DIM must match the model's output width or the API refuses to
# start (nomic-embed-text is 768).
EMBEDDING_BASE_URL=
EMBEDDING_MODEL=text-embedding-nomic-embed-text-v1.5@q8_0
EMBEDDING_DIM=768
# EMBEDDING_API_KEY= # cloud embedders only (e.g. OpenAI, Voyage)
#
# Retrieval tuning (see the README "Tuning retrieval" runbooks). Distances are
# cosine (0 = identical, 2 = opposite); good values are model-specific, so
# re-tune after any model change.
# EMBEDDING_SEED_MAX_DISTANCE=0.15 # Tier A: proactively inject the top match when within this. Tuned: 0.25-0.30.
# EMBEDDING_SIMILAR_MAX_DISTANCE=0.5 # Tier B: drop get_similar_past_builds rows beyond this. Tuned: 0.35-0.40.
# EMBEDDING_HNSW_M=16 # HNSW graph degree (build-time; reindex to change).
# EMBEDDING_HNSW_EF_CONSTRUCTION=64 # HNSW build candidate list (build-time; reindex to change).
# EMBEDDING_HNSW_EF_SEARCH=40 # HNSW query candidate list (query-time; higher = better recall, slower).

# ----- Logging -----
# Log level: debug | info | warn | error (default info).
LOG_LEVEL=info
Expand Down
90 changes: 85 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ authored for them.
│ └──────────────┘ │ ↪ LLM provider (Claude / OpenAI) │ │
│ │ ↪ Tool registry │ │
│ │ ↪ Build library (PostgreSQL) │ │
│ │ ↪ Embedding provider (optional) │ │
│ │ ↪ Scoring client → ─────┐ │ │
│ └───────────────────────────│──────────┘ │
└─────────────────────────────────────────────────│────────────┘
Expand All @@ -48,6 +49,19 @@ authored for them.

Two deployable units. Both can be run natively, via `docker compose`, or via Helm/Tilt on Kubernetes.

**Embedding provider and RAG.** The build library optionally uses an OpenAI-compatible embedding endpoint (a local LM
Studio, Ollama, or llama.cpp server, or any hosted `/v1/embeddings` API) to enable semantic retrieval over saved
builds. When configured, the orchestrator embeds the incoming
request, searches the pgvector-backed library for semantically similar past builds, and proactively injects the closest
match as a warm-start for the LLM (Tier A seeding). The LLM can also pull ranked candidates on demand through the
`get_similar_past_builds` and `get_saved_build` tools (Tier B). When no embedder is configured, retrieval falls back to
recency ordering and pgvector is not required.

Retrieval only surfaces builds the user has explicitly **accepted**. A generation that passes quality gates is saved and
fetchable immediately, but it does not seed future generations until you `POST /builds/{id}/accept` — passing gates is
not the same as being the build you wanted. Un-accepted builds are visible only through the user-facing `GET /builds`
(filterable with `?accepted=`) and `GET /builds/{id}`, never through the RAG tools.

Directory map:

```
Expand All @@ -57,6 +71,8 @@ cmd/ one Go binary per directory
build-rocalc-mapping/ rocalc-id ↔ iRO-id table (one-shot)
enrich-mapping-rms/ ratemyserver.net lookup helper
verify-mapping/ spot-check tool
backfill-embeddings/ re-embed every saved build after a model change (one-shot)
embedding-recall/ HNSW recall quality probe: approx-vs-exact KNN
internal/
api/ HTTP handlers, OpenAPI types
buildlibrary/ PostgreSQL persistence
Expand Down Expand Up @@ -89,6 +105,65 @@ scripts/ e2e.sh, generate.sh, docker-e2e.sh, ...
api/openapi.yaml the public HTTP contract
```

### EMBEDDING_* configuration

| Variable | Meaning |
|---|---|
| `EMBEDDING_BASE_URL` | OpenAI-compatible `/v1` root; presence enables the feature. Local default: `http://localhost:1234/v1` (LM Studio); Ollama is `http://localhost:11434/v1`. |
| `EMBEDDING_MODEL` | Model id, e.g. `text-embedding-nomic-embed-text-v1.5@q8_0` (LM Studio), `nomic-embed-text` (Ollama), `text-embedding-3-large` (OpenAI). |
| `EMBEDDING_API_KEY` | Optional bearer token (cloud embedders); ignored by local servers. |
| `EMBEDDING_DIM` | Required when `EMBEDDING_BASE_URL` is set (default 768). Sets the vector column width; must match the model's output dimension. |
| `EMBEDDING_SEED_MAX_DISTANCE` | Tier A proactive-seed cosine-distance ceiling (default 0.15). Inject the closest saved build only when it is this close to the request. |
| `EMBEDDING_SIMILAR_MAX_DISTANCE` | Tier B list floor (default 0.5). Drop `get_similar_past_builds` results beyond this cosine distance. |
| `EMBEDDING_HNSW_M` / `EMBEDDING_HNSW_EF_CONSTRUCTION` | HNSW index build parameters (default pgvector 16 / 64). Baked into the index; changing them needs a reindex. |
| `EMBEDDING_HNSW_EF_SEARCH` | HNSW query-time candidate-list size (default pgvector 40). Higher = better recall, slower. Applied per query. |

Unset `EMBEDDING_BASE_URL` means recency-only retrieval, no pgvector required.

### Tuning runbooks

**Threshold tuning (after a populated corpus exists).** Enable the per-firing log; each proactive seed records the
seed `id` and its cosine `distance`. Collect a sample of real requests, read the generated build alongside the log to
judge usefulness, and look at where genuinely useful matches cluster versus the noise tail. Then set
`EMBEDDING_SEED_MAX_DISTANCE` just inside the good band (tight enough to avoid seeding bad matches). The Tier B list
floor `EMBEDDING_SIMILAR_MAX_DISTANCE` (which bounds what `get_similar_past_builds` returns) is set looser than the
seed ceiling using the same observations. Re-deploy and re-observe. Distances are model-specific and do not transfer
across a model or dimension change; redo this step after any `EMBEDDING_MODEL`/`EMBEDDING_DIM` swap.

**Model and HNSW index tuning.** Pick a model and dimension (`EMBEDDING_MODEL` / `EMBEDDING_DIM`), then run:

```bash
# 1. (Re-)embed every saved build with the chosen model.
# If EMBEDDING_MODEL or EMBEDDING_DIM changed on a non-empty corpus, clear
# existing embeddings first so backfill does not exit early with an error:
# UPDATE saved_trajectories SET embedding = NULL;
# Then run backfill:
go run ./cmd/backfill-embeddings

# 2. Check HNSW index recall against exact KNN.
go run ./cmd/embedding-recall --k 10 --sample 50

# 3a. Recall is low (< 0.95): measure a higher query-time ef_search first, then set it
# on the serving path.
go run ./cmd/embedding-recall --k 10 --sample 50 --ef-search 80
# If that helps, set EMBEDDING_HNSW_EF_SEARCH=80 on the API. It is applied per query
# (SET LOCAL inside the retrieval transaction); no reindex needed.

# 3b. Still low: raise the build parameters and rebuild the index. Set EMBEDDING_HNSW_M
# and/or EMBEDDING_HNSW_EF_CONSTRUCTION on the API, then force a fresh index (the
# bootstrap's CREATE INDEX IF NOT EXISTS will not rebuild an existing one):
# DROP INDEX saved_trajectories_embedding_idx;
# and restart the API. The bootstrap recreates the index WITH (m, ef_construction).

# 4. To switch models entirely: change EMBEDDING_MODEL/EMBEDDING_DIM, clear embeddings
# (step 1 above), re-run backfill-embeddings, re-run embedding-recall, then
# re-tune the thresholds from the previous runbook.
```

`cmd/embedding-recall` reports `recall@k` = `|approx_topk intersect exact_topk| / k`. A value >= 0.98 means
the defaults are fine; below 0.85 means the index parameters need raising. Run it against a populated corpus
only; an empty corpus always returns perfect recall.

---

## Capabilities
Expand Down Expand Up @@ -242,8 +317,9 @@ Full OpenAPI 3.0 contract: [`api/openapi.yaml`](api/openapi.yaml). Bruno collect
| POST | `/score` | Direct calc; fully-specified Build → derived stats + optional combat sim |
| POST | `/generate` | LLM-driven; enqueue a generation job; returns `202 + {id}` |
| GET | `/generations/{id}` | Poll status of an enqueued generation |
| GET | `/builds` | Paginated list of saved trajectories |
| GET | `/builds` | Paginated list of saved trajectories (filter with `?accepted=true\|false`) |
| GET | `/builds/{id}` | One full saved trajectory with item / skill names resolved |
| POST | `/builds/{id}/accept` | Accept a build so RAG retrieval can seed future generations from it |

### Score a build directly

Expand Down Expand Up @@ -280,8 +356,11 @@ while :; do
sleep 30
done

# 3. Fetch enriched build
# 3. Fetch enriched build and review it
curl -s "http://localhost:8080/builds/$ID" | jq .

# 4. Accept it so future generations can seed from it (RAG only sees accepted builds)
curl -s -X POST "http://localhost:8080/builds/$ID/accept" | jq .
```

Or use the convenience wrapper:
Expand Down Expand Up @@ -439,9 +518,10 @@ Not yet done, roughly in priority order:
- [x] Add self-buffs to calc
- [ ] Add self-buffs to scoring
- [x] Include skill usage/damage in calc and scoring
- [ ] Vector search over saved trajectories' reasoning text. Today's `get_similar_past_builds` uses class+scenario
lookup.
- [ ] Add RAG with injecting get_similar_past_builds into initial system prompt
- [x] Vector search (pgvector) over saved trajectories. `get_similar_past_builds` ranks by cosine distance to the
embedded request when an embedder is configured; falls back to recency otherwise.
- [x] RAG seeding: the orchestrator embeds the incoming request, finds the closest saved build, and injects it as a
warm-start when within `EMBEDDING_SEED_MAX_DISTANCE`.
- [x] Postgres migration for the build library. The API is now stateless; horizontal scaling is supported via the
lease-based generation queue (SKIP LOCKED claim, requeue with cap), configurable replicas, and HPA/PDB in the Helm chart.
- [ ] General prompt tuning - less tokens, more progress.
Expand Down
73 changes: 67 additions & 6 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ info:
description: |
Ragnarok Online (pre-renewal) build optimizer.

Four endpoints:
- POST /score direct calc; fully-specified Build → derived stats + optional combat sim
- POST /generate LLM-driven; enqueue a generation job; returns 202 + {id}
- GET /generations/{id} poll status of an enqueued generation
- GET /builds paginated list of saved trajectories
- GET /builds/{id} one full saved trajectory with item/skill names resolved
Six endpoints:
- POST /score direct calc; fully-specified Build → derived stats + optional combat sim
- POST /generate LLM-driven; enqueue a generation job; returns 202 + {id}
- GET /generations/{id} poll status of an enqueued generation
- GET /builds paginated list of saved trajectories (filter with ?accepted=)
- GET /builds/{id} one full saved trajectory with item/skill names resolved
- POST /builds/{id}/accept mark a build user-accepted so RAG retrieval can seed from it

The /generate endpoint requires LLM_API_KEY at the API process. Without it,
/generate returns 503 (Service Unavailable); /score continues to work.
Expand Down Expand Up @@ -164,6 +165,14 @@ paths:
minimum: 1
maximum: 50
description: cap results (default 5, max 50)
- name: accepted
in: query
required: false
schema:
type: boolean
description: >
filter by acceptance state; true = accepted only, false = pending
(not yet accepted) only, omitted = all
responses:
"200":
description: List of trajectory summaries
Expand Down Expand Up @@ -221,6 +230,43 @@ paths:
schema:
$ref: "#/components/schemas/ErrorBody"

/builds/{id}/accept:
post:
operationId: acceptBuild
summary: Accept a saved trajectory, making it visible to RAG retrieval
description: >
Marks the build as user-accepted. Until accepted, a saved build is
fetchable via GET /builds/{id} but is NOT surfaced by the retrieval
tools (proactive seed injection, get_similar_past_builds,
get_saved_build). Idempotent: re-accepting keeps the original
timestamp.
parameters:
- name: id
in: path
required: true
schema:
type: string
description: id of the saved build to accept
responses:
"200":
description: Build accepted (or already accepted)
content:
application/json:
schema:
$ref: "#/components/schemas/AcceptBuildResponse"
"404":
description: No trajectory with that id
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorBody"
"500":
description: Library failure
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorBody"

components:
schemas:

Expand Down Expand Up @@ -559,6 +605,10 @@ components:
playstyle: { type: string }
description: { type: string }
gate_summary: { $ref: "#/components/schemas/GateSummary" }
accepted_at:
type: string
format: date-time
description: when the build was user-accepted; absent = pending (not RAG-visible)

ListBuildsResponse:
type: object
Expand All @@ -568,6 +618,13 @@ components:
type: array
items: { $ref: "#/components/schemas/BuildSummary" }

AcceptBuildResponse:
type: object
required: [ id, accepted_at ]
properties:
id: { type: string }
accepted_at: { type: string, format: date-time }

EnrichedBuild:
type: object
required: [ id, created_at, class, server, playstyle, mode, primary, gate_summary ]
Expand All @@ -587,3 +644,7 @@ components:
gate_summary: { $ref: "#/components/schemas/GateSummary" }
calc_version: { type: string }
catalog_version: { type: integer }
accepted_at:
type: string
format: date-time
description: when the build was user-accepted; absent = pending (not RAG-visible)
48 changes: 48 additions & 0 deletions bruno/accept-build.bru
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
meta {
name: accept-build
type: http
seq: 5
}

post {
url: {{baseUrl}}/builds/{{savedBuildId}}/accept
body: none
auth: inherit
}

docs {
Accept a saved trajectory so the RAG retrieval surface can seed future
generations from it. Until accepted, a build that passed quality gates
is fetchable via `get-saved-build` but is invisible to proactive seed
injection, `get_similar_past_builds`, and `get_saved_build` -- passing
the quality gates is not the same as being the build you wanted.

`savedBuildId` is set by the `generate` request's post-response script;
run this after reviewing the build with `get-saved-build`. Idempotent:
accepting an already-accepted build returns the original `accepted_at`.
404 if no build has that id.

Typical flow: generate -> generation-status -> get-saved-build (review)
-> accept-build.
}

tests {
test("status is 200", function() {
expect(res.getStatus()).to.equal(200);
});
test("id present", function() {
expect(res.getBody().id).to.be.a("string").and.not.empty;
});
test("accepted_at present", function() {
expect(res.getBody().accepted_at).to.be.a("string").and.not.empty;
});
}

script:post-response {
const data = res.getBody() || {};
console.log("");
console.log("Build accepted: " + (data.id || "?"));
console.log(" accepted_at: " + (data.accepted_at || "?"));
console.log("");
console.log("It is now visible to RAG retrieval and can seed future generations.");
}
6 changes: 5 additions & 1 deletion bruno/list-builds.bru
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
meta {
name: list-builds
type: http
seq: 5
seq: 6
}

get {
Expand All @@ -14,6 +14,7 @@ params:query {
limit: 10
~class: taekwon_kid
~server: uaro
~accepted: true
}

docs {
Expand All @@ -22,6 +23,9 @@ docs {
- `class`; restrict to one class
- `server`; restrict to one server profile
- `limit`; 1..50, default 5
- `accepted`; `true` = user-accepted (RAG-visible) only, `false` =
pending review only, omitted = all. Each row carries `accepted_at`
(absent = pending). See `accept-build`.
}

tests {
Expand Down
Loading
Loading