nlq-validator 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ from nlq_validator.integrations.base import BaseLLMIntegration
2
+ from nlq_validator.validator import CalibrationResult, NLQValidator, ValidationResult
3
+
4
+ __all__ = ["NLQValidator", "ValidationResult", "CalibrationResult", "BaseLLMIntegration"]
5
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from nlq_validator.integrations.base import BaseLLMIntegration
2
+
3
+ __all__ = ["BaseLLMIntegration"]
@@ -0,0 +1,68 @@
1
+ import re
2
+ from abc import ABC, abstractmethod
3
+ from pathlib import Path
4
+
5
+
6
+ class BaseLLMIntegration(ABC):
7
+ _PROMPT_TEMPLATE = (
8
+ "You are generating training data for a query validator.\n"
9
+ "Given the system prompt below, generate {count} diverse, realistic questions "
10
+ "that users might ask this assistant.\n\n"
11
+ "System prompt: {system_prompt}\n\n"
12
+ "Rules:\n"
13
+ "- Return exactly {count} questions\n"
14
+ "- One question per line\n"
15
+ "- No numbering, bullets, or extra text\n"
16
+ "- Vary question length, phrasing, and complexity"
17
+ )
18
+
19
+ @abstractmethod
20
+ def generate_questions(self, system_prompt: str, count: int = 50) -> list[str]:
21
+ """Call the LLM synchronously and return `count` sample questions."""
22
+
23
+ @abstractmethod
24
+ async def generate_questions_async(self, system_prompt: str, count: int = 50) -> list[str]:
25
+ """Call the LLM asynchronously and return `count` sample questions."""
26
+
27
+ def generate_and_save(
28
+ self,
29
+ system_prompt: str,
30
+ path: str | Path,
31
+ count: int = 50,
32
+ ) -> list[str]:
33
+ """Generate questions synchronously and save them to a file."""
34
+ questions = self.generate_questions(system_prompt, count)
35
+ path = Path(path)
36
+ path.parent.mkdir(parents=True, exist_ok=True)
37
+ path.write_text("\n".join(questions), encoding="utf-8")
38
+ return questions
39
+
40
+ async def generate_and_save_async(
41
+ self,
42
+ system_prompt: str,
43
+ path: str | Path,
44
+ count: int = 50,
45
+ ) -> list[str]:
46
+ """Generate questions asynchronously and save them to a file."""
47
+ questions = await self.generate_questions_async(system_prompt, count)
48
+ path = Path(path)
49
+ path.parent.mkdir(parents=True, exist_ok=True)
50
+ path.write_text("\n".join(questions), encoding="utf-8")
51
+ return questions
52
+
53
+ def _build_prompt(self, system_prompt: str, count: int) -> str:
54
+ return self._PROMPT_TEMPLATE.format(system_prompt=system_prompt, count=count)
55
+
56
+ def _parse_response(self, text: str) -> list[str]:
57
+ """Strip blank lines and common list prefixes from raw LLM response."""
58
+ questions = []
59
+ for line in text.splitlines():
60
+ line = line.strip()
61
+ if not line:
62
+ continue
63
+ line = re.sub(r"^[\d]+[.):\-]\s*", "", line)
64
+ line = re.sub(r"^[-*•]\s*", "", line)
65
+ line = line.strip()
66
+ if line:
67
+ questions.append(line)
68
+ return questions
@@ -0,0 +1,43 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from nlq_validator.integrations.base import BaseLLMIntegration
6
+
7
+
8
+ class ChatGPTIntegration(BaseLLMIntegration):
9
+ def __init__(self, api_key: str | None = None, model: str | None = None) -> None:
10
+ try:
11
+ from openai import OpenAI # noqa: F401
12
+ except ImportError:
13
+ raise ImportError(
14
+ "openai package is required. Install it with: pip install 'nlq-validator[openai]'"
15
+ )
16
+ self._api_key = api_key or os.environ.get("OPENAI_API_KEY")
17
+ self._model = model or os.environ.get("OPENAI_MODEL")
18
+
19
+ def generate_questions(self, system_prompt: str, count: int = 50) -> list[str]:
20
+ from openai import OpenAI
21
+
22
+ client = OpenAI(api_key=self._api_key)
23
+ prompt = self._build_prompt(system_prompt, count)
24
+ response = client.chat.completions.create(
25
+ model=self._model,
26
+ messages=[{"role": "user", "content": prompt}],
27
+ temperature=0.8,
28
+ )
29
+ text = response.choices[0].message.content or ""
30
+ return self._parse_response(text)
31
+
32
+ async def generate_questions_async(self, system_prompt: str, count: int = 50) -> list[str]:
33
+ from openai import AsyncOpenAI
34
+
35
+ client = AsyncOpenAI(api_key=self._api_key)
36
+ prompt = self._build_prompt(system_prompt, count)
37
+ response = await client.chat.completions.create(
38
+ model=self._model,
39
+ messages=[{"role": "user", "content": prompt}],
40
+ temperature=0.8,
41
+ )
42
+ text = response.choices[0].message.content or ""
43
+ return self._parse_response(text)
@@ -0,0 +1,44 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from nlq_validator.integrations.base import BaseLLMIntegration
6
+
7
+
8
+ class ClaudeIntegration(BaseLLMIntegration):
9
+ def __init__(self, api_key: str | None = None, model: str | None = None) -> None:
10
+ try:
11
+ import anthropic # noqa: F401
12
+ except ImportError:
13
+ raise ImportError(
14
+ "anthropic package is required. "
15
+ "Install it with: pip install 'nlq-validator[anthropic]'"
16
+ )
17
+ self._api_key = api_key or os.environ.get("ANTHROPIC_API_KEY")
18
+ self._model = model or os.environ.get("ANTHROPIC_MODEL")
19
+
20
+ def generate_questions(self, system_prompt: str, count: int = 50) -> list[str]:
21
+ import anthropic
22
+
23
+ client = anthropic.Anthropic(api_key=self._api_key)
24
+ prompt = self._build_prompt(system_prompt, count)
25
+ message = client.messages.create(
26
+ model=self._model,
27
+ max_tokens=4096,
28
+ messages=[{"role": "user", "content": prompt}],
29
+ )
30
+ text = message.content[0].text if message.content else ""
31
+ return self._parse_response(text)
32
+
33
+ async def generate_questions_async(self, system_prompt: str, count: int = 50) -> list[str]:
34
+ import anthropic
35
+
36
+ client = anthropic.AsyncAnthropic(api_key=self._api_key)
37
+ prompt = self._build_prompt(system_prompt, count)
38
+ message = await client.messages.create(
39
+ model=self._model,
40
+ max_tokens=4096,
41
+ messages=[{"role": "user", "content": prompt}],
42
+ )
43
+ text = message.content[0].text if message.content else ""
44
+ return self._parse_response(text)
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+
6
+ from nlq_validator.integrations.base import BaseLLMIntegration
7
+
8
+
9
+ class GeminiIntegration(BaseLLMIntegration):
10
+ def __init__(self, api_key: str | None = None, model: str | None = None) -> None:
11
+ try:
12
+ import google.generativeai # noqa: F401
13
+ except ImportError:
14
+ raise ImportError(
15
+ "google-generativeai package is required. "
16
+ "Install it with: pip install 'nlq-validator[gemini]'"
17
+ )
18
+ self._api_key = api_key or os.environ.get("GEMINI_API_KEY")
19
+ self._model = model or os.environ.get("GEMINI_MODEL")
20
+
21
+ def generate_questions(self, system_prompt: str, count: int = 50) -> list[str]:
22
+ import google.generativeai as genai
23
+
24
+ genai.configure(api_key=self._api_key)
25
+ model = genai.GenerativeModel(self._model)
26
+ prompt = self._build_prompt(system_prompt, count)
27
+ response = model.generate_content(prompt)
28
+ text = response.text if response.text else ""
29
+ return self._parse_response(text)
30
+
31
+ async def generate_questions_async(self, system_prompt: str, count: int = 50) -> list[str]:
32
+ # google-generativeai does not expose a native async client;
33
+ # run the synchronous call in a thread to avoid blocking the event loop.
34
+ return await asyncio.to_thread(self.generate_questions, system_prompt, count)
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from nlq_validator.integrations.base import BaseLLMIntegration
6
+
7
+
8
+ class GrokIntegration(BaseLLMIntegration):
9
+ _BASE_URL = "https://api.x.ai/v1"
10
+
11
+ def __init__(self, api_key: str | None = None, model: str | None = None) -> None:
12
+ try:
13
+ from openai import OpenAI # noqa: F401
14
+ except ImportError:
15
+ raise ImportError(
16
+ "openai package is required. Install it with: pip install 'nlq-validator[openai]'"
17
+ )
18
+ self._api_key = api_key or os.environ.get("XAI_API_KEY")
19
+ self._model = model or os.environ.get("XAI_MODEL")
20
+
21
+ def generate_questions(self, system_prompt: str, count: int = 50) -> list[str]:
22
+ from openai import OpenAI
23
+
24
+ client = OpenAI(api_key=self._api_key, base_url=self._BASE_URL)
25
+ prompt = self._build_prompt(system_prompt, count)
26
+ response = client.chat.completions.create(
27
+ model=self._model,
28
+ messages=[{"role": "user", "content": prompt}],
29
+ temperature=0.8,
30
+ )
31
+ text = response.choices[0].message.content or ""
32
+ return self._parse_response(text)
33
+
34
+ async def generate_questions_async(self, system_prompt: str, count: int = 50) -> list[str]:
35
+ from openai import AsyncOpenAI
36
+
37
+ client = AsyncOpenAI(api_key=self._api_key, base_url=self._BASE_URL)
38
+ prompt = self._build_prompt(system_prompt, count)
39
+ response = await client.chat.completions.create(
40
+ model=self._model,
41
+ messages=[{"role": "user", "content": prompt}],
42
+ temperature=0.8,
43
+ )
44
+ text = response.choices[0].message.content or ""
45
+ return self._parse_response(text)
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+
6
+ from nlq_validator.integrations.base import BaseLLMIntegration
7
+
8
+
9
+ class MistralIntegration(BaseLLMIntegration):
10
+ def __init__(self, api_key: str | None = None, model: str | None = None) -> None:
11
+ try:
12
+ from mistralai import Mistral # noqa: F401
13
+ except ImportError:
14
+ raise ImportError(
15
+ "mistralai package is required. "
16
+ "Install it with: pip install 'nlq-validator[mistral]'"
17
+ )
18
+ self._api_key = api_key or os.environ.get("MISTRAL_API_KEY")
19
+ self._model = model or os.environ.get("MISTRAL_MODEL")
20
+
21
+ def generate_questions(self, system_prompt: str, count: int = 50) -> list[str]:
22
+ from mistralai import Mistral
23
+
24
+ client = Mistral(api_key=self._api_key)
25
+ prompt = self._build_prompt(system_prompt, count)
26
+ response = client.chat.complete(
27
+ model=self._model,
28
+ messages=[{"role": "user", "content": prompt}],
29
+ temperature=0.8,
30
+ )
31
+ text = response.choices[0].message.content if response.choices else ""
32
+ return self._parse_response(text)
33
+
34
+ async def generate_questions_async(self, system_prompt: str, count: int = 50) -> list[str]:
35
+ # mistralai's async client requires an explicit event loop context;
36
+ # wrapping in asyncio.to_thread is the safest cross-version approach.
37
+ return await asyncio.to_thread(self.generate_questions, system_prompt, count)
@@ -0,0 +1,45 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from nlq_validator.integrations.base import BaseLLMIntegration
6
+
7
+
8
+ class PerplexityIntegration(BaseLLMIntegration):
9
+ _BASE_URL = "https://api.perplexity.ai"
10
+
11
+ def __init__(self, api_key: str | None = None, model: str | None = None) -> None:
12
+ try:
13
+ from openai import OpenAI # noqa: F401
14
+ except ImportError:
15
+ raise ImportError(
16
+ "openai package is required. Install it with: pip install 'nlq-validator[openai]'"
17
+ )
18
+ self._api_key = api_key or os.environ.get("PERPLEXITY_API_KEY")
19
+ self._model = model or os.environ.get("PERPLEXITY_MODEL")
20
+
21
+ def generate_questions(self, system_prompt: str, count: int = 50) -> list[str]:
22
+ from openai import OpenAI
23
+
24
+ client = OpenAI(api_key=self._api_key, base_url=self._BASE_URL)
25
+ prompt = self._build_prompt(system_prompt, count)
26
+ response = client.chat.completions.create(
27
+ model=self._model,
28
+ messages=[{"role": "user", "content": prompt}],
29
+ temperature=0.8,
30
+ )
31
+ text = response.choices[0].message.content or ""
32
+ return self._parse_response(text)
33
+
34
+ async def generate_questions_async(self, system_prompt: str, count: int = 50) -> list[str]:
35
+ from openai import AsyncOpenAI
36
+
37
+ client = AsyncOpenAI(api_key=self._api_key, base_url=self._BASE_URL)
38
+ prompt = self._build_prompt(system_prompt, count)
39
+ response = await client.chat.completions.create(
40
+ model=self._model,
41
+ messages=[{"role": "user", "content": prompt}],
42
+ temperature=0.8,
43
+ )
44
+ text = response.choices[0].message.content or ""
45
+ return self._parse_response(text)
@@ -0,0 +1,73 @@
1
+ import csv
2
+ import json
3
+ from pathlib import Path
4
+
5
+
6
+ class FileLoader:
7
+ _JSON_TEXT_KEYS = ("text", "query", "question")
8
+
9
+ @staticmethod
10
+ def load(path: str | Path) -> list[str]:
11
+ path = Path(path)
12
+ suffix = path.suffix.lower()
13
+ if suffix == ".txt":
14
+ examples = FileLoader._load_txt(path)
15
+ elif suffix == ".csv":
16
+ examples = FileLoader._load_csv(path)
17
+ elif suffix == ".json":
18
+ examples = FileLoader._load_json(path)
19
+ else:
20
+ raise ValueError(f"Unsupported file extension '{suffix}'. Use .txt, .csv, or .json.")
21
+ if len(examples) < 2:
22
+ raise ValueError(
23
+ f"Training file must contain at least 2 examples, got {len(examples)}."
24
+ )
25
+ return examples
26
+
27
+ @staticmethod
28
+ def _load_txt(path: Path) -> list[str]:
29
+ return [
30
+ line.strip()
31
+ for line in path.read_text(encoding="utf-8").splitlines()
32
+ if line.strip()
33
+ ]
34
+
35
+ @staticmethod
36
+ def _load_csv(path: Path) -> list[str]:
37
+ examples: list[str] = []
38
+ with path.open(encoding="utf-8", newline="") as f:
39
+ reader = csv.reader(f)
40
+ rows = list(reader)
41
+ if not rows:
42
+ return examples
43
+ # Skip header if first cell doesn't look like a sample query
44
+ first = rows[0][0].strip() if rows and rows[0] else ""
45
+ looks_like_header = (
46
+ first and not first.endswith("?") and len(rows) > 1 and first.replace(" ", "").isalpha()
47
+ )
48
+ start = 1 if looks_like_header else 0
49
+ for row in rows[start:]:
50
+ if row and row[0].strip():
51
+ examples.append(row[0].strip())
52
+ return examples
53
+
54
+ @staticmethod
55
+ def _load_json(path: Path) -> list[str]:
56
+ data = json.loads(path.read_text(encoding="utf-8"))
57
+ if not isinstance(data, list):
58
+ raise ValueError("JSON file must contain a top-level list.")
59
+ examples: list[str] = []
60
+ for item in data:
61
+ if isinstance(item, str):
62
+ if item.strip():
63
+ examples.append(item.strip())
64
+ elif isinstance(item, dict):
65
+ for key in FileLoader._JSON_TEXT_KEYS:
66
+ if key in item and isinstance(item[key], str) and item[key].strip():
67
+ examples.append(item[key].strip())
68
+ break
69
+ else:
70
+ raise ValueError(
71
+ f"JSON list items must be strings or objects, got {type(item).__name__}."
72
+ )
73
+ return examples
nlq_validator/model.py ADDED
@@ -0,0 +1,72 @@
1
+ from dataclasses import dataclass, field
2
+
3
+ import numpy as np
4
+ from scipy.sparse import csr_matrix
5
+ from sklearn.feature_extraction.text import TfidfVectorizer
6
+ from sklearn.metrics.pairwise import cosine_similarity
7
+
8
+
9
+ @dataclass
10
+ class TopicModel:
11
+ vectorizer: TfidfVectorizer
12
+ train_matrix: csr_matrix
13
+ centroid: np.ndarray
14
+ training_examples: list[str]
15
+ system_prompt_vec: np.ndarray | None = field(default=None)
16
+
17
+ # Retrain bookkeeping — user examples only, no system prompt sentences
18
+ user_examples: list[str] = field(default_factory=list)
19
+ system_prompt_text: str | None = field(default=None)
20
+
21
+ # Optional semantic embedding support (sentence-transformers)
22
+ embedding_model_name: str | None = field(default=None)
23
+ example_embeddings: np.ndarray | None = field(default=None)
24
+ centroid_embedding: np.ndarray | None = field(default=None)
25
+
26
+ # Live encoder — never serialized, re-instantiated lazily after load
27
+ _encoder: object = field(default=None, init=False, repr=False, compare=False)
28
+
29
+ def __post_init__(self) -> None:
30
+ self._encoder = None
31
+
32
+ def __getstate__(self) -> dict:
33
+ state = self.__dict__.copy()
34
+ state.pop("_encoder", None)
35
+ return state
36
+
37
+ def __setstate__(self, state: dict) -> None:
38
+ self.__dict__.update(state)
39
+ self._encoder = None
40
+
41
+ def _get_encoder(self):
42
+ if self.embedding_model_name is None:
43
+ return None
44
+ if self._encoder is None:
45
+ try:
46
+ from sentence_transformers import SentenceTransformer
47
+ except ImportError:
48
+ return None
49
+ self._encoder = SentenceTransformer(self.embedding_model_name)
50
+ return self._encoder
51
+
52
+ def score(self, query: str) -> float:
53
+ vec = self.vectorizer.transform([query])
54
+ centroid_sim = float(cosine_similarity(vec, self.centroid)[0][0])
55
+ nn_sim = float(cosine_similarity(vec, self.train_matrix).max())
56
+ candidates = [centroid_sim, nn_sim]
57
+ if self.system_prompt_vec is not None:
58
+ sp_sim = float(cosine_similarity(vec, self.system_prompt_vec)[0][0])
59
+ candidates.append(sp_sim)
60
+
61
+ encoder = self._get_encoder()
62
+ if (
63
+ encoder is not None
64
+ and self.example_embeddings is not None
65
+ and self.centroid_embedding is not None
66
+ ):
67
+ q_emb = encoder.encode([query], normalize_embeddings=True)
68
+ emb_nn_sim = float(cosine_similarity(q_emb, self.example_embeddings).max())
69
+ emb_centroid_sim = float(cosine_similarity(q_emb, self.centroid_embedding)[0][0])
70
+ candidates.extend([emb_nn_sim, emb_centroid_sim])
71
+
72
+ return max(candidates)
@@ -0,0 +1,18 @@
1
+ from pathlib import Path
2
+
3
+ import joblib
4
+
5
+ from nlq_validator.model import TopicModel
6
+
7
+
8
+ def save_model(model: TopicModel, path: str | Path) -> None:
9
+ path = Path(path)
10
+ path.parent.mkdir(parents=True, exist_ok=True)
11
+ joblib.dump(model, path, compress=3)
12
+
13
+
14
+ def load_model(path: str | Path) -> TopicModel:
15
+ path = Path(path)
16
+ if not path.exists():
17
+ raise FileNotFoundError(f"Model file not found: {path}")
18
+ return joblib.load(path)
@@ -0,0 +1,59 @@
1
+ import re
2
+
3
+ import numpy as np
4
+ from sklearn.feature_extraction.text import TfidfVectorizer
5
+
6
+ from nlq_validator.model import TopicModel
7
+
8
+
9
+ def _split_sentences(text: str) -> list[str]:
10
+ """Split text into non-empty sentences on punctuation boundaries."""
11
+ parts = re.split(r"(?<=[.!?])\s+", text.strip())
12
+ return [p.strip() for p in parts if p.strip()]
13
+
14
+
15
+ def train(
16
+ examples: list[str],
17
+ system_prompt: str | None = None,
18
+ embedding_model: str | None = None,
19
+ ) -> TopicModel:
20
+ user_examples = list(examples)
21
+
22
+ corpus = list(examples)
23
+ if system_prompt:
24
+ corpus.extend(_split_sentences(system_prompt))
25
+
26
+ vectorizer = TfidfVectorizer(
27
+ analyzer="word", ngram_range=(1, 2), min_df=1, sublinear_tf=True, stop_words="english"
28
+ )
29
+ train_matrix = vectorizer.fit_transform(corpus)
30
+ centroid = np.asarray(train_matrix.mean(axis=0))
31
+
32
+ system_prompt_vec: np.ndarray | None = None
33
+ if system_prompt:
34
+ sp_sparse = vectorizer.transform([system_prompt])
35
+ system_prompt_vec = np.asarray(sp_sparse.todense())
36
+
37
+ example_embeddings: np.ndarray | None = None
38
+ centroid_embedding: np.ndarray | None = None
39
+ if embedding_model is not None:
40
+ try:
41
+ from sentence_transformers import SentenceTransformer
42
+ encoder = SentenceTransformer(embedding_model)
43
+ example_embeddings = encoder.encode(corpus, normalize_embeddings=True)
44
+ centroid_embedding = example_embeddings.mean(axis=0, keepdims=True)
45
+ except ImportError:
46
+ pass
47
+
48
+ return TopicModel(
49
+ vectorizer=vectorizer,
50
+ train_matrix=train_matrix,
51
+ centroid=centroid,
52
+ training_examples=corpus,
53
+ system_prompt_vec=system_prompt_vec,
54
+ user_examples=user_examples,
55
+ system_prompt_text=system_prompt,
56
+ embedding_model_name=embedding_model,
57
+ example_embeddings=example_embeddings,
58
+ centroid_embedding=centroid_embedding,
59
+ )
@@ -0,0 +1,193 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ from typing import TYPE_CHECKING
6
+
7
+ from nlq_validator.model import TopicModel
8
+
9
+ if TYPE_CHECKING:
10
+ from nlq_validator.integrations.base import BaseLLMIntegration
11
+
12
+
13
+ @dataclass
14
+ class ValidationResult:
15
+ is_valid: bool
16
+ errors: list[str] = field(default_factory=list)
17
+ warnings: list[str] = field(default_factory=list)
18
+
19
+
20
+ @dataclass
21
+ class CalibrationResult:
22
+ in_domain_scores: list[float]
23
+ off_domain_scores: list[float]
24
+ suggested_threshold: float
25
+
26
+ def summary(self) -> None:
27
+ """Print a precision/recall/F1 table over a sweep of threshold candidates."""
28
+ all_scores = self.in_domain_scores + self.off_domain_scores
29
+ labels = [1] * len(self.in_domain_scores) + [0] * len(self.off_domain_scores)
30
+ candidates = sorted(set(all_scores))
31
+
32
+ header = f"{'Threshold':>10} {'Precision':>10} {'Recall':>9} {'F1':>8}"
33
+ separator = "-" * len(header)
34
+ print(header)
35
+ print(separator)
36
+ for t in candidates:
37
+ preds = [1 if s >= t else 0 for s in all_scores]
38
+ tp = sum(p == 1 and lb == 1 for p, lb in zip(preds, labels))
39
+ fp = sum(p == 1 and lb == 0 for p, lb in zip(preds, labels))
40
+ fn = sum(p == 0 and lb == 1 for p, lb in zip(preds, labels))
41
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
42
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
43
+ f1 = (2 * precision * recall / (precision + recall)
44
+ if (precision + recall) > 0 else 0.0)
45
+ marker = " <-- suggested" if abs(t - self.suggested_threshold) < 1e-9 else ""
46
+ print(f"{t:>10.4f} {precision:>10.4f} {recall:>9.4f} {f1:>8.4f}{marker}")
47
+ print(separator)
48
+ print(f"Suggested threshold: {self.suggested_threshold:.4f}")
49
+
50
+
51
+ class NLQValidator:
52
+ def __init__(
53
+ self,
54
+ model: TopicModel,
55
+ threshold: float = 0.25,
56
+ ) -> None:
57
+ self._model = model
58
+ self._threshold = threshold
59
+
60
+ @classmethod
61
+ def from_training_file(
62
+ cls,
63
+ path: str | Path,
64
+ system_prompt: str,
65
+ threshold: float = 0.25,
66
+ embedding_model: str | None = None,
67
+ ) -> "NLQValidator":
68
+ from nlq_validator.loader import FileLoader
69
+ from nlq_validator.trainer import train
70
+
71
+ examples = FileLoader.load(path)
72
+ model = train(examples, system_prompt=system_prompt, embedding_model=embedding_model)
73
+ return cls(model, threshold)
74
+
75
+ @classmethod
76
+ def from_llm(
77
+ cls,
78
+ integration: "BaseLLMIntegration",
79
+ system_prompt: str,
80
+ count: int = 50,
81
+ threshold: float = 0.25,
82
+ embedding_model: str | None = None,
83
+ ) -> "NLQValidator":
84
+ from nlq_validator.trainer import train
85
+
86
+ examples = integration.generate_questions(system_prompt, count)
87
+ model = train(examples, system_prompt=system_prompt, embedding_model=embedding_model)
88
+ return cls(model, threshold)
89
+
90
+ @classmethod
91
+ async def from_llm_async(
92
+ cls,
93
+ integration: "BaseLLMIntegration",
94
+ system_prompt: str,
95
+ count: int = 50,
96
+ threshold: float = 0.25,
97
+ embedding_model: str | None = None,
98
+ ) -> "NLQValidator":
99
+ from nlq_validator.trainer import train
100
+
101
+ examples = await integration.generate_questions_async(system_prompt, count)
102
+ model = train(examples, system_prompt=system_prompt, embedding_model=embedding_model)
103
+ return cls(model, threshold)
104
+
105
+ @classmethod
106
+ def load(
107
+ cls,
108
+ path: str | Path,
109
+ threshold: float = 0.25,
110
+ ) -> "NLQValidator":
111
+ from nlq_validator.persistence import load_model
112
+
113
+ model = load_model(path)
114
+ return cls(model, threshold)
115
+
116
+ def save(self, path: str | Path) -> None:
117
+ from nlq_validator.persistence import save_model
118
+
119
+ save_model(self._model, path)
120
+
121
+ def retrain(self, additional_examples: list[str]) -> None:
122
+ """Merge new examples with existing training data and retrain in-place."""
123
+ from nlq_validator.trainer import train
124
+
125
+ merged = self._model.user_examples + list(additional_examples)
126
+ self._model = train(
127
+ merged,
128
+ system_prompt=self._model.system_prompt_text,
129
+ embedding_model=self._model.embedding_model_name,
130
+ )
131
+
132
+ def retrain_from_file(self, path: str | Path) -> None:
133
+ """Load additional examples from a file and retrain in-place."""
134
+ from nlq_validator.loader import FileLoader
135
+
136
+ self.retrain(FileLoader.load(path))
137
+
138
+ def apply_calibration(self, result: CalibrationResult) -> None:
139
+ """Apply the suggested threshold from a CalibrationResult."""
140
+ self._threshold = result.suggested_threshold
141
+
142
+ def calibrate(
143
+ self,
144
+ in_domain: list[str],
145
+ off_domain: list[str],
146
+ ) -> CalibrationResult:
147
+ """Score sample queries and find the F1-optimal threshold."""
148
+ in_scores = [self._model.score(q) for q in in_domain]
149
+ off_scores = [self._model.score(q) for q in off_domain]
150
+
151
+ all_scores = in_scores + off_scores
152
+ labels = [1] * len(in_scores) + [0] * len(off_scores)
153
+ candidates = sorted(set(all_scores))
154
+
155
+ best_f1 = -1.0
156
+ best_t = candidates[0] if candidates else 0.25
157
+
158
+ for t in candidates:
159
+ preds = [1 if s >= t else 0 for s in all_scores]
160
+ tp = sum(p == 1 and lb == 1 for p, lb in zip(preds, labels))
161
+ fp = sum(p == 1 and lb == 0 for p, lb in zip(preds, labels))
162
+ fn = sum(p == 0 and lb == 1 for p, lb in zip(preds, labels))
163
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
164
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0
165
+ f1 = (2 * precision * recall / (precision + recall)
166
+ if (precision + recall) > 0 else 0.0)
167
+ if f1 > best_f1:
168
+ best_f1 = f1
169
+ best_t = t
170
+
171
+ return CalibrationResult(
172
+ in_domain_scores=in_scores,
173
+ off_domain_scores=off_scores,
174
+ suggested_threshold=best_t,
175
+ )
176
+
177
+ def validate(self, query: str) -> ValidationResult:
178
+ s = self._model.score(query)
179
+ if s < self._threshold:
180
+ return ValidationResult(
181
+ is_valid=False,
182
+ errors=[
183
+ f"Query appears off-topic (score={s:.3f}, threshold={self._threshold:.3f})"
184
+ ],
185
+ )
186
+ return ValidationResult(is_valid=True)
187
+
188
+ def score(self, query: str) -> float:
189
+ return self._model.score(query)
190
+
191
+ @property
192
+ def threshold(self) -> float:
193
+ return self._threshold
@@ -0,0 +1,180 @@
1
+ Metadata-Version: 2.4
2
+ Name: nlq-validator
3
+ Version: 0.1.0
4
+ Summary: Lightweight Natural Language Query validator — keep your LLM assistant on-topic
5
+ Author-email: Balajee K <kalyanasundarambalajee@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/balajeekalyan/nlq-validator
8
+ Project-URL: Repository, https://github.com/balajeekalyan/nlq-validator
9
+ Project-URL: Bug Tracker, https://github.com/balajeekalyan/nlq-validator/issues
10
+ Keywords: nlp,nlq,validator,llm,natural-language,query-validation,topic-model,tfidf,embeddings
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: scikit-learn>=1.4
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest>=8.0; extra == "dev"
26
+ Requires-Dist: pytest-cov>=5.0; extra == "dev"
27
+ Requires-Dist: ruff>=0.4; extra == "dev"
28
+ Provides-Extra: openai
29
+ Requires-Dist: openai>=1.0; extra == "openai"
30
+ Provides-Extra: anthropic
31
+ Requires-Dist: anthropic>=0.25; extra == "anthropic"
32
+ Provides-Extra: gemini
33
+ Requires-Dist: google-generativeai>=0.8; extra == "gemini"
34
+ Provides-Extra: mistral
35
+ Requires-Dist: mistralai>=1.0; extra == "mistral"
36
+ Provides-Extra: all-llm
37
+ Requires-Dist: openai>=1.0; extra == "all-llm"
38
+ Requires-Dist: anthropic>=0.25; extra == "all-llm"
39
+ Requires-Dist: google-generativeai>=0.8; extra == "all-llm"
40
+ Requires-Dist: mistralai>=1.0; extra == "all-llm"
41
+ Provides-Extra: embeddings
42
+ Requires-Dist: sentence-transformers>=2.7; extra == "embeddings"
43
+ Dynamic: license-file
44
+
45
+ # nlq-validator
46
+
47
+ A lightweight Natural Language Query (NLQ) validator that keeps your LLM assistant on-topic. Train it on a handful of example questions, and it will accept in-domain queries while rejecting off-topic ones — no server, no API key required for the core functionality.
48
+
49
+ ## Features
50
+
51
+ - **TF-IDF scoring** out of the box — no model downloads needed
52
+ - **Semantic embeddings** via sentence-transformers for paraphrase-aware matching
53
+ - **Threshold calibration** — find the F1-optimal cutoff for your domain
54
+ - **Incremental retraining** — add examples without rebuilding from scratch
55
+ - **LLM-powered question generation** — auto-generate training data from your system prompt (Claude, ChatGPT, Gemini, Mistral, Grok, Perplexity)
56
+ - **Async support** for all LLM integrations
57
+ - **Zero runtime dependencies** beyond scikit-learn for the core validator
58
+
59
+ ## Installation
60
+
61
+ ```bash
62
+ pip install nlq-validator
63
+ ```
64
+
65
+ ### Optional extras
66
+
67
+ ```bash
68
+ pip install 'nlq-validator[embeddings]' # sentence-transformers for semantic matching
69
+ pip install 'nlq-validator[anthropic]' # Claude integration
70
+ pip install 'nlq-validator[openai]' # ChatGPT, Grok, Perplexity integrations
71
+ pip install 'nlq-validator[gemini]' # Google Gemini integration
72
+ pip install 'nlq-validator[mistral]' # Mistral integration
73
+ pip install 'nlq-validator[all-llm]' # All LLM integrations
74
+ ```
75
+
76
+ ## Quick start
77
+
78
+ ```python
79
+ from nlq_validator import NLQValidator
80
+
81
+ SYSTEM_PROMPT = (
82
+ "You are a SQL assistant. You help users write queries, "
83
+ "understand JOINs, indexes, and query optimization."
84
+ )
85
+
86
+ # Train from a plain-text file (one question per line)
87
+ v = NLQValidator.from_training_file("questions.txt", SYSTEM_PROMPT)
88
+
89
+ result = v.validate("How do I write a SELECT statement?")
90
+ print(result.is_valid) # True
91
+
92
+ result = v.validate("What is my horoscope today?")
93
+ print(result.is_valid) # False
94
+ print(result.errors) # ['Query appears off-topic (score=0.000, threshold=0.250)']
95
+ ```
96
+
97
+ ## Training data format
98
+
99
+ Supported file formats: `.txt` (one question per line), `.csv` (first column), `.json` (list of strings or list of `{"text": "..."}` objects).
100
+
101
+ ```
102
+ # questions.txt
103
+ How do I write a SELECT statement?
104
+ What is a SQL JOIN?
105
+ How do I filter rows with WHERE clause?
106
+ What is the difference between INNER JOIN and LEFT JOIN?
107
+ ...
108
+ ```
109
+
110
+ ## Threshold calibration
111
+
112
+ The default threshold of `0.25` is a conservative starting point. Use `calibrate()` to find the optimal value for your domain:
113
+
114
+ ```python
115
+ in_domain = ["How do I use GROUP BY?", "What is a primary key?", ...]
116
+ off_domain = ["How do I bake bread?", "What is my horoscope?", ...]
117
+
118
+ result = v.calibrate(in_domain, off_domain)
119
+ result.summary() # prints precision/recall/F1 table
120
+ v.apply_calibration(result) # applies suggested threshold
121
+ ```
122
+
123
+ ## Incremental retraining
124
+
125
+ ```python
126
+ v.retrain(["How do I write a CTE?", "What is a window function?"])
127
+ # or from a file:
128
+ v.retrain_from_file("more_questions.txt")
129
+ ```
130
+
131
+ ## Semantic embeddings
132
+
133
+ For queries that use different words but mean the same thing:
134
+
135
+ ```python
136
+ v = NLQValidator.from_training_file(
137
+ "questions.txt",
138
+ SYSTEM_PROMPT,
139
+ embedding_model="all-MiniLM-L6-v2", # requires nlq-validator[embeddings]
140
+ )
141
+ ```
142
+
143
+ ## LLM-powered question generation
144
+
145
+ Generate training data automatically from your system prompt:
146
+
147
+ ```python
148
+ from nlq_validator.integrations.claude import ClaudeIntegration
149
+
150
+ llm = ClaudeIntegration() # reads ANTHROPIC_API_KEY env var
151
+ v = NLQValidator.from_llm(llm, SYSTEM_PROMPT, count=50)
152
+ ```
153
+
154
+ Async variant:
155
+
156
+ ```python
157
+ v = await NLQValidator.from_llm_async(llm, SYSTEM_PROMPT, count=50)
158
+ ```
159
+
160
+ ### Supported LLM providers
161
+
162
+ | Provider | Extra | Class | Env vars |
163
+ |-------------|--------------------|-----------------------|---------------------------------------|
164
+ | Claude | `[anthropic]` | `ClaudeIntegration` | `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL`|
165
+ | ChatGPT | `[openai]` | `ChatGPTIntegration` | `OPENAI_API_KEY`, `OPENAI_MODEL` |
166
+ | Gemini | `[gemini]` | `GeminiIntegration` | `GEMINI_API_KEY`, `GEMINI_MODEL` |
167
+ | Mistral | `[mistral]` | `MistralIntegration` | `MISTRAL_API_KEY`, `MISTRAL_MODEL` |
168
+ | Grok | `[openai]` | `GrokIntegration` | `XAI_API_KEY`, `XAI_MODEL` |
169
+ | Perplexity | `[openai]` | `PerplexityIntegration`| `PERPLEXITY_API_KEY`, `PERPLEXITY_MODEL`|
170
+
171
+ ## Save and load
172
+
173
+ ```python
174
+ v.save("my_model.pkl")
175
+ v2 = NLQValidator.load("my_model.pkl")
176
+ ```
177
+
178
+ ## License
179
+
180
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,19 @@
1
+ nlq_validator/__init__.py,sha256=59q4Bu6qwL1ArJXpqDl5lo-yecv1n_Zi-ha6ZH1PpY4,262
2
+ nlq_validator/loader.py,sha256=QiDU6bshaEPP0xq7zD5LrmPUvTVaXz3nDlk5zW6wy2k,2613
3
+ nlq_validator/model.py,sha256=qDQISpFgbD_aCwQdM1CmCuu-k_KwhgdlVaacwN18rDA,2722
4
+ nlq_validator/persistence.py,sha256=ZYpzCEL085j33K5NapW-64TJx_mn5CdAM1-ZWaJy1Ec,453
5
+ nlq_validator/trainer.py,sha256=4qCzNK6PQHqBFOL5kbtgDrjFul4LGVowDcAniR9psFY,1965
6
+ nlq_validator/validator.py,sha256=2wD7NiNr8uH5YxLg3xrCCRPMK7S2EtocyfSf5UGruqM,6770
7
+ nlq_validator/integrations/__init__.py,sha256=tn6fLWWgL8DEYMSazRmQAFxiG6aELk2bUp4ymlEeuqs,97
8
+ nlq_validator/integrations/base.py,sha256=8BGYl8kPHC-NxkNhwzfli6H-qz_zSfZtjIjCnW5-_wg,2562
9
+ nlq_validator/integrations/chatgpt.py,sha256=Cz0z1CGhW9lQ0YbL-UuazSmb3ifeDTJMfWPvhg1Zy6k,1649
10
+ nlq_validator/integrations/claude.py,sha256=pMNkMzKYfX6_6uxXVqEmuyqWykBv5QiS_8CRyv-jZeo,1673
11
+ nlq_validator/integrations/gemini.py,sha256=m-os2JxPB14uucqH2UP6ObT_29ycjrBG8xsByQ6l15A,1423
12
+ nlq_validator/integrations/grok.py,sha256=5SN9DbtpmlYRhm2oWd9ORd-swws82v5UPFtt3D-GOBw,1729
13
+ nlq_validator/integrations/mistral.py,sha256=BaxZaJpgwdanoRBMNxsymhHEUckGWXq7igtrUc7AeRM,1514
14
+ nlq_validator/integrations/perplexity.py,sha256=K-4AMtRvLD1kx--83s-OHO2bkHJSJUCV_JRK5Fuujsk,1755
15
+ nlq_validator-0.1.0.dist-info/licenses/LICENSE,sha256=Lg3GWN5x-BRjmQXXg0ZvQlMp7KRpMzO1DhXURhN4tFA,1070
16
+ nlq_validator-0.1.0.dist-info/METADATA,sha256=G0HBAXHcoIJe8nTxwyvm45-o6-wlOIs_iGMYamPfif8,6544
17
+ nlq_validator-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
18
+ nlq_validator-0.1.0.dist-info/top_level.txt,sha256=JlT6E_YCzBp1Eqai8YceNPliQTe5bmSBYMpBNcnrmN0,14
19
+ nlq_validator-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 balajeekalyan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ nlq_validator