Skip to content

About

Let your users ask your database anything, in their own words — safely. The model fills in a validated Query AST, never a query string, and deterministic Go compiles it to SQL, MongoDB or whatever backend you add. Config-driven, read-only by design, standard-library Go.

Topics

Resources

Security policy

Stars

16 stars

Watchers

1 watching

Forks

Latest commit

 

History

77 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

QueryForge — NLP to any query: a natural-language question passes through security, RBAC, scope, policy, validation and a typed AST, then compiles to PostgreSQL, MySQL, MongoDB and Elasticsearch. Available for Go, Python, Java and MCP. No invented columns, no injection, no mutation.

QueryForge

Replace the whole filter panel with one sentence.

CI Go Reference License Go 1.25+ PyPI Maven Central

Website Config Builder


Your users stop translating what they want into dropdowns, checkboxes and date pickers — they just say it. You get back a parameterized query you can actually trust.

"orders over 500 dollars in the last 30 days that were not cancelled, newest first, top 20"
SELECT status, created_at, amount, customer_name FROM orders
WHERE (status <> $1 AND created_at >= $2 AND amount > $3)
ORDER BY created_at DESC LIMIT 20
-- args: ["CANCELLED", "2026-06-29T08:49:06Z", 500]

The same sentence, against MongoDB, from the identical intermediate object — no second prompt:

{ amount: {$gt: 500}, createdAt: {$gte: "2026-06-29T08:49:06Z"}, status: {$ne: "CANCELLED"} }

Why not just ask an LLM for SQL?

Because you can't check what comes back. A model asked for SQL can invent a column, invent a table, quietly widen a filter, or hand you a statement that is only probably right.

QueryForge never lets the model near a query string. It fills in a typed form — the Query AST — constrained to a vocabulary your config registers. Everything after that is ordinary Go:

Natural language  →  [ AI planner ]  →  Query AST  →  [ generators ]  →  SQL / MySQL / Mongo
   (unbounded)        model + config     (typed)       pure code — no AI, no network
Invented a field? Rejected by the validator before anything compiles — with "did you mean" suggestions.
SQL injection? The model emits structure, never a string. Values are bound ($1, $2); only config-supplied identifiers reach the statement.
Asked to delete something? Not expressible. The AST has no mutation node, so every output is a SELECT or a find.
Asked about a field you hid? returnable: false is enforced on the default projection too, not just explicit select.
Asked something impossible? A typed refusal — not a plausible query built on a lookalike field.
Asked for another tenant's rows? Scope filters (below) are AND-ed on after the model answers. It never learns the field exists.

Everything that must be guaranteed lives on the deterministic side, where it can be tested offline.

Install

Four ways to call it. All need the same two things and nothing else: a config file describing your data (build one in your browser) and a model API key in the environment. No server, no Docker, no database connection.

🐹 Go — the library
go get github.com/awsaman-ai/queryforge
cfg, _ := qf.LoadConfig("orders.config.json")
engine := qf.New(cfg)

res, _ := engine.Translate(ctx, "cancelled orders over 200 dollars", "sql", nil)

fmt.Println(res.Query.SQL)   // SELECT … WHERE (status = $1 AND amount > $2) …
fmt.Println(res.Query.Args)  // [CANCELLED 200]
fmt.Println(res.Explain)     // plain-English readback of what it understood

No third-party dependencies — standard library only. API docs →

🐍 Python — pip
pip install queryforge-ai   # installs as queryforge-ai, imports as queryforge
from queryforge import QueryForge

qf = QueryForge.postgres("orders.config.json")
pending = qf.query("cancelled orders over $200")

print(pending.to_sql())    # SELECT … WHERE (status = $1 AND amount > $2) …
print(pending.to_args())   # ('CANCELLED', 200)

The engine ships inside the wheel — no Go toolchain needed. Docs →

☕ Java — Maven, Java 11+

Maven Central

Two dependencies: the classes, and the engine binary for the platform you run on. Set the property once to the version in the badge above and both stay in step.

<properties>
    <queryforge.version>LATEST</queryforge.version>  <!-- the version in the badge -->
</properties>

<dependency>
    <groupId>io.github.awsaman-ai</groupId>
    <artifactId>queryforge</artifactId>
    <version>${queryforge.version}</version>
</dependency>
<dependency>
    <groupId>io.github.awsaman-ai</groupId>
    <artifactId>queryforge</artifactId>
    <version>${queryforge.version}</version>
    <classifier>linux-amd64</classifier>
</dependency>
QueryForge forge = QueryForge.postgres(Paths.get("orders.config.json"));

String sql       = forge.query("cancelled orders over $200").toSql();
List<Object> args = forge.query("cancelled orders over $200").toArgs();

Zero runtime dependencies — not even a JSON library. Docs →

🔌 MCP — Claude Desktop, Cursor
go install github.com/awsaman-ai/queryforge_mcp@latest
{
  "mcpServers": {
    "queryforge": {
      "command": "queryforge-mcp",
      "args": ["--config", "orders.config.json"]
    }
  }
}

Restart Claude and ask "cancelled orders over $200" — it comes back as a validated query. Docs →

Whichever you pick, the answer is the same query. Swap postgres for mysql or mongo and the same sentence compiles for that backend instead.

QueryForge never connects to your database. It hands you the query; executing it stays yours.

Configure

One JSON file is the prompt context, the validation rulebook, the field→backend mapping, and the model selector:

{
  "entity": "Order",
  "model":    { "provider": "gemini", "baseURL": "…/v1beta/openai",
                "model": "gemini-3.1-flash-lite", "apiKeyEnv": "QF_API_KEY" },
  "backends": { "sql": { "table": "orders" }, "mongo": { "collection": "orders" } },
  "fields": [
    { "name": "status", "type": "enum", "values": ["PLACED", "DELIVERED", "CANCELLED"],
      "synonyms": ["state", "delivery status"],
      "mapping": { "sql": "status", "mongo": "status" } },
    { "name": "amount", "type": "number",
      "mapping": { "sql": "amount", "mongo": "amount" } },
    { "name": "createdAt", "type": "date",
      "mapping": { "sql": "created_at", "mongo": "createdAt" } }
  ]
}

Don't hand-write it — build it. The config builder is a single self-contained page (open it straight from disk, nothing leaves the browser). Four settings per field up front, the rest behind Advanced, every one with an ⓘ and a worked example, validated as you type by the same rules the loader enforces.

📖 Full configuration reference →

Try it

# Offline — no API key. Compiles a hand-written AST.
go run ./examples -config examples/orders.config.json -backend sql   -ast sample_ast.json
go run ./examples -config examples/orders.config.json -backend mongo -ast sample_ast.json

# Natural language — needs a key.
export QF_API_KEY=<your-key>
go run ./examples -config examples/orders.config.json -backend sql \
  -text "delivered but not refunded, created in the last 30 days, tagged premium and express"

Features

🗄 Five backends, one brain Postgres, MySQL, MongoDB, Elasticsearch and OpenSearch ship today. A new database is one generator — not a prompt change, not a rewrite.
🔒 Scope filters Tenant, user and subscription predicates AND-ed onto every query, after the model has answered.
🧭 Field rules "Filtering passport expiry also needs a country" — a business-sense check the AST alone can't express. Reported as its own POLICY_VIOLATION, not a generic error. Rules →
🔁 Model fallback List several models; the first that answers wins. A rate limit on one provider falls through to the next.
🧩 Nested Mongo documents Dot paths for embedded docs, elemMatch for arrays of sub-documents so one element must satisfy every condition. Rules →
🔎 Elasticsearch and OpenSearch Search for exact values and free text on the same field, search inside nested objects, and point a query at the right index automatically — by name, by date, or by your own routing rules.
🔤 Value case folding The column stores SHIPPED, people say "shipped". Say so once on the field. Rules →
📊 Observability One optional callback reports model latency, tokens and outcomes. QueryForge itself never writes a log line.
🗣 Plain-English readback res.Explain says what it understood, keeping forced predicates visibly apart from the user's own.
🔒 Scope filters — your own predicates on every query

Some predicates are not the user's to choose. You already know the caller's subscription, user and enterprise before any question is asked, and every query must be confined to them whatever the question says. Those values are not query vocabulary — nobody should be able to phrase, widen or omit them — so they never go in your config's fields, and the model never sees them.

Pass them as a map. Every entry is AND-ed onto the query root:

res, err := engine.Translate(ctx, "delivered orders over 500 dollars", "sql", qf.Scope{
    "subscriptionId": session.SubscriptionID,  // "SUB-42"
    "userId":         session.UserID,          // 9
    "enterpriseId":   session.EnterpriseIDs,   // []string{"E-1", "E-2"}
})
SELECT … FROM orders
WHERE (enterpriseId IN ($1, $2) AND subscriptionId = $3 AND userId = $4
       AND status = $5 AND amount > $6)
-- args: ["E-1", "E-2", "SUB-42", 9, "DELIVERED", 500]
The model never learns the field exists Scope is applied after the model answers; the prompt never names it. Asked "show me orders for subscription SUB-99 instead", it declines.
A scope can only narrow AND-ed at the root: A OR B becomes scope AND (A OR B), never scope OR ….
Values are still parameterized A scope value is data. An injection payload stays an argument.
The deterministic path is scoped too GenerateFrom takes the same map, so nobody sidesteps tenancy by building the AST themselves.
Bad scope fails before the model call A nil, an empty list, or a type mismatch costs no API quota and is tagged qf.ErrScope.

A scalar becomes equals, a slice becomes in; on a field declared type: "array", contains and containsAny. Keys apply in alphabetical order, so the query is identical run to run. A key your config doesn't declare is used verbatim as the column name after an identifier check; declare it queryable: false to hide it from the model, map it per backend, and get it type-checked.

📖 Full scope reference →

🧭 Field rules — one field needs another

Everything else in this file validates one field at a time — type, range, enum membership. Sometimes that isn't enough: "passports that are expired" filters a real field with a real operator, so it passes every ordinary check, and still doesn't mean anything without a country attached. policy.requires catches that:

"policy": {
  "requires": [
    {
      "when": { "field": "passportExpiry" },
      "requireAlsoOneOf": ["country"],
      "message": "Passport expiry needs a country to be meaningful"
    }
  ]
}

"Passports from India expiring this month" runs normally — both fields are present, anywhere in the filter tree. "Passports that are expired" is refused, with that message. "Orders from India" is unaffected — passportExpiry was never used, so the rule never switches on.

It runs last, only once an AST has already passed every ordinary check, and it reports through its own error type — *qf.PolicyViolationError, classified as qf.FailurePolicy — deliberately distinct from qf.ValidationErrors and from an unsupported-request refusal, so a caller can show a "needs more information" message instead of a generic one:

res, err := engine.Translate(ctx, "passports that are expired", "sql", nil)
var policyErr *qf.PolicyViolationError
if errors.As(err, &policyErr) {
    fmt.Println(policyErr.Message)          // "Passport expiry needs a country to be meaningful"
    fmt.Println(policyErr.RequireAlsoOneOf) // ["country"]
}

Like a refusal, it is not retried — the model already answered correctly given the words it was given, and asking again would not add information the question never contained. The cmd/queryforge stdio protocol carries the same distinction on the wire as "code": "POLICY_VIOLATION" plus a structured policyError object, separate from details.

Build one without writing JSON: the config builder's Step 6 turns it into two dropdowns — "When ▾ is filtered, also require ▾" — populated only from fields you've already added.

📖 Full field-rules reference →

🔁 Choosing a model, and falling back

A config change, never a code change. The default provider speaks any OpenAI-compatible /chat/completions endpoint; a second speaks Anthropic's native Messages API; a third speaks Amazon Bedrock's Converse API (see below).

Naming a known provider supplies the endpoint, so the common case is two keys:

"model": { "provider": "groq", "model": "llama-3.3-70b-versatile", "apiKeyEnv": "GROQ_API_KEY" }

Built-in endpoints: anthropic, bedrock (region-based), cerebras, deepseek, fireworks, gemini, google, groq, lmstudio, mistral, nvidia, ollama, openai, openrouter, perplexity, together, vllm, xai. { "provider": "ollama", "model": "qwen2.5" } is a complete config on a stock install — no URL, no key.

Amazon Bedrock needs a region and a credential, and you can supply the credential by reference to an environment variable or write it in the config:

{ "provider": "bedrock", "model": "us.anthropic.claude-sonnet-4-6",
  "aws": { "region": "us-east-1", "bearerTokenEnv": "AWS_BEARER_TOKEN_BEDROCK" } }

With no aws block at all, the standard AWS_REGION and AWS_BEARER_TOKEN_BEDROCK (or AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY + AWS_SESSION_TOKEN) variables are read. A credential written inline (bearerToken, secretAccessKey, …) works but raises a warning on every translate. QueryForge signs requests itself (SigV4) but does not resolve profiles, SSO, AssumeRole or instance roles; resolve those yourself and pass the temporary credentials in. Details in the config reference.

This list holds no model ids, so a provider shipping a new model needs no QueryForge release. An explicit baseURL always overrides a preset, and a provider that is not listed is not unsupported — set baseURL and it works identically:

"model": { "provider": "acme", "baseURL": "https://api.acme.ai/v1", "model": "acme-ultra", "apiKeyEnv": "ACME_API_KEY" }

Prefer keeping the key out of the config: apiKeyEnv names the environment variable that holds it. When that is not possible (a quick local test, a config built in the browser), "apiKey": "…" puts the key in the file itself — one or the other, never both. It is a redacted type: it never appears in logs, error messages, %v output or re-marshalled JSON, but it does travel with the file, so keep that file out of version control. From Java or Python you can also supply a key at runtime, straight from a secret manager:

QueryForge.mysql("orders.config.json", credentials={"QF_API_KEY": vault.get("openai/key")})
QueryForge.mysql(configPath)
        .withCredentials(Collections.singletonMap("QF_API_KEY", vault.read("openai/key")));

The value goes into the engine subprocess's environment only: never into the request, never into a log, never into your own process's environment.

Retries. A failed call is retried only when waiting could fix it — a rate limit, a 5xx, a dropped connection. A bad key, an unknown model, a malformed request or an exhausted quota fail immediately, because the next attempt would send exactly the same thing. Tunable per model block with timeoutSeconds, maxRetries and retryBackoffMs; a provider's Retry-After header always wins.

Fallback. List several and QueryForge tries them in order, using the first that answers, so a rate limit or billing block falls through transparently:

"model":  { "provider": "gemini", "model": "gemini-3.1-flash-lite", "apiKeyEnv": "QF_API_KEY", "baseURL": "…" },
"models": [
  { "provider": "groq",      "baseURL": "https://api.groq.com/openai/v1", "model": "llama-3.3-70b-versatile", "apiKeyEnv": "GROQ_API_KEY" },
  { "provider": "anthropic", "baseURL": "https://api.anthropic.com",      "model": "claude-opus-4-8",         "apiKeyEnv": "ANTHROPIC_API_KEY" },
  { "provider": "ollama",    "baseURL": "http://localhost:11434/v1",      "model": "qwen2.5" }
]

Ready to run: examples/orders.fallback.config.json.

📊 Observability

QueryForge never writes a log line. It reports facts through one optional callback and lets you decide destination, format and severity:

engine.SetObserver(func(ctx context.Context, e qf.Event) {
    switch e.Kind {
    case qf.EventModelCall:  // one round trip: latency, tokens, finish reason
    case qf.EventAttempt:    // one plan+validate cycle; e.Raw on failure
    case qf.EventTranslate:  // the whole call, on every exit path
    }
})

A traced live request measured the entire deterministic half — parse, validate, compile, explain — at 0.5 ms against a 1,781 ms model call. Roughly 99.97% of a translation is one HTTP round trip, so the seam watches the model interaction and leaves the deterministic core alone.

Privacy is a design property, not a convention. The question text is never in an Event. Scope values are never in an Event — only ScopeKeys — because those values are tenant, user and enterprise ids. The API key is never in an Event. The one field that can echo caller data is Raw, the model's verbatim reply, populated only on a failed attempt; log it at debug level and truncate. A test asserts the rest with a canary.

Use SetObserver, not engine.Observe: only the former pushes the observer down into the provider, where latency and token counts live. The callback is synchronous, must be concurrency-safe, and must not panic.

🌳 What the AST looks like

AST = Abstract Syntax Tree — a plain JSON object describing what the user asked for, between the sentence and the query. A tree because filters nest; abstract because it knows nothing about SQL or Mongo: it says "operator": "gt", never > and never $gt.

{
  "entity": "Order",
  "filter": {
    "type": "logical", "op": "AND",
    "children": [
      { "type": "comparison", "field": "amount",    "operator": "gt",        "value": {"kind":"number","v":500} },
      { "type": "comparison", "field": "createdAt", "operator": "after",     "value": {"kind":"relative_date","unit":"day","amount":-30} },
      { "type": "comparison", "field": "status",    "operator": "notEquals", "value": {"kind":"enum","v":"CANCELLED"} }
    ]
  },
  "sort":  [{ "field": "createdAt", "dir": "DESC" }],
  "limit": 20
}

That one object compiles to SQL and Mongo with no second prompt. And it has no node type that can write — so "read-only" doesn't depend on a check someone might forget; it depends on there being no way to express a write.

📖 Full AST reference →

Other languages

The same engine ships as a native library for Python and Java. Each SDK spawns the bundled binary as a local subprocess and exchanges one JSON object over stdin/stdout — no HTTP, no daemon, no socket. The SDKs contain no query logic whatsoever, so all three languages produce byte-identical output.

Python Java
Install pip install queryforge-ai one Maven <dependency>
Runtime dependencies none none — not even a JSON library
Wrapper size ~30 KB of code ~35 KB jar
Engine binary in the platform wheel (~6 MB) in an auto-selected classifier jar (~2.5 MB)
Docs sdk-python/README.md sdk-java/README.md

Both offer the full pipeline (query, one model call) and the deterministic half (generate / validate — no model call, no API key, testable offline). Writing an SDK for another language? The wire format is specified in cmd/queryforge/PROTOCOL.md.

Logging and error handling

QueryForge never fails silently. If it cannot correctly complete an operation, it does not pretend that it did: there is no path that returns an empty query, a partial result, or a nil in place of a failure. Every failure carries a stable machine-readable code, keeps the original cause reachable, and reaches the caller.

The library itself does not log. A library that logs on its own initiative picks a destination, a format and a severity its host did not choose. Instead it reports facts through one optional Observer callback — and ships the adapter almost everyone was going to write by hand:

logger := slog.New(slog.NewJSONHandler(os.Stderr, nil))
engine := qf.New(cfg)
engine.SetObserver(qf.SlogObserver(logger))
{"time":"2026-08-13T01:30:00.412Z","level":"ERROR","msg":"query generation failed",
 "library":"queryforge","language":"go","component":"engine","operation":"translate",
 "backend":"mysql","entity":"Order","duration_ms":1842,"outcome":"transport_error",
 "error_code":"MODEL_TRANSPORT","error_type":"*fmt.wrapError"}

The engine binary and both SDKs emit the same field names, the same severities and the same error codes, so one saved search works across all four surfaces. Turn any of them on with QUERYFORGE_LOG_LEVEL.

Two severity choices are deliberate: a refusal is INFO, because the model declining to invent a query for something the config cannot express is the guard rail working; and a failed operation produces exactly one ERROR, at the boundary, rather than the same stack trace at every layer.

The question text, the scope values and the config contents are never logged, at any level — pinned by canary tests in all three languages. Only shape is: the entity, the backend, the scope keys.

Full field schema, error-code table and level semantics: docs/OBSERVABILITY.md.

Testing

The deterministic half is fully tested with no API key and no network:

go test ./...

Every component ships happy-path and adversarial "try to break it" tests — injection strings, unknown fields, illegal operator/type pairs, out-of-domain enums, deep nesting, oversized limits. CI also runs golangci-lint against .golangci.yml.

Architecture

File Role AI?
ast.go Query AST types + JSON (de)serialization —
config.go Config types + loader + capability flags —
validate.go The guarantee: field/operator/type/enum/depth + capability checks, with suggestions No
generate.go, gen_sql.go, gen_mongo.go, gen_es.go Registry + backend generators (parameterized, read-only) No
elastic_config.go, source_es.go Elasticsearch/OpenSearch config validation and index resolution No
scope.go Caller-supplied filters → typed predicates AND-ed onto the query root No
explain.go AST → prose (dry-run, no execution) No
provider.go ModelProvider interface + OpenAI-compatible default + test stub Yes
planner.go Build prompt from config, parse model output → AST Yes
observe.go Observer seam: facts out, no logging —
slog.go Opt-in adapter: Observer events → structured log/slog records —
failure.go Classify: any error → one stable FailureCode, shared by all four surfaces —
queryforge.go Engine: New, Translate, GenerateFrom, Validate, Register —

The planner is the only place a model runs. Validate → generate → explain is pure Go — the guarantees live there.

Ecosystem

Project What it is
queryforge_mcp QueryForge over the Model Context Protocol, so Claude Desktop, Cursor or any MCP client can query your data. The tool schema is generated from your config, so the model picks from your vocabulary instead of guessing. Hidden fields and physical column names never leave the process.
Documentation Guide, full configuration reference, and the Query AST explained.
Config builder Build a config in a form and download it, with live validation. Runs entirely in the browser.

Roadmap

  • Shipped — Go library, JSON config, validator, SQL/MySQL/Mongo/Elasticsearch/OpenSearch generators, scope filters, model fallback, observability seam, CLI, MCP server, Python and Java SDKs.
  • Next — YAML config, confidence scores, REST facade.
  • Later — Node and .NET SDKs over the same stdio protocol, a persistent engine process, an aggregation AST node, more backends (DynamoDB, Cassandra, ClickHouse).

Contributing

Issues and pull requests are welcome. CI runs gofmt, go vet and the full suite with the race detector on every PR, including from forks — the suite is entirely offline, so it needs no API key. If you're changing behaviour, please add a test that fails without your change.

Security issues go through private disclosure, not a public issue.

License

Apache 2.0 — use, modify, distribute and embed in commercial software, with an explicit patent licence from every contributor. Keep the notices, and state any significant changes you make.

About

Let your users ask your database anything, in their own words — safely. The model fills in a validated Query AST, never a query string, and deterministic Go compiles it to SQL, MongoDB or whatever backend you add. Config-driven, read-only by design, standard-library Go.

Topics

Resources

Security policy

Stars

16 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages