nlq-validator 0.1.0__tar.gz

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,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,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,136 @@
1
+ # nlq-validator
2
+
3
+ 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.
4
+
5
+ ## Features
6
+
7
+ - **TF-IDF scoring** out of the box — no model downloads needed
8
+ - **Semantic embeddings** via sentence-transformers for paraphrase-aware matching
9
+ - **Threshold calibration** — find the F1-optimal cutoff for your domain
10
+ - **Incremental retraining** — add examples without rebuilding from scratch
11
+ - **LLM-powered question generation** — auto-generate training data from your system prompt (Claude, ChatGPT, Gemini, Mistral, Grok, Perplexity)
12
+ - **Async support** for all LLM integrations
13
+ - **Zero runtime dependencies** beyond scikit-learn for the core validator
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pip install nlq-validator
19
+ ```
20
+
21
+ ### Optional extras
22
+
23
+ ```bash
24
+ pip install 'nlq-validator[embeddings]' # sentence-transformers for semantic matching
25
+ pip install 'nlq-validator[anthropic]' # Claude integration
26
+ pip install 'nlq-validator[openai]' # ChatGPT, Grok, Perplexity integrations
27
+ pip install 'nlq-validator[gemini]' # Google Gemini integration
28
+ pip install 'nlq-validator[mistral]' # Mistral integration
29
+ pip install 'nlq-validator[all-llm]' # All LLM integrations
30
+ ```
31
+
32
+ ## Quick start
33
+
34
+ ```python
35
+ from nlq_validator import NLQValidator
36
+
37
+ SYSTEM_PROMPT = (
38
+ "You are a SQL assistant. You help users write queries, "
39
+ "understand JOINs, indexes, and query optimization."
40
+ )
41
+
42
+ # Train from a plain-text file (one question per line)
43
+ v = NLQValidator.from_training_file("questions.txt", SYSTEM_PROMPT)
44
+
45
+ result = v.validate("How do I write a SELECT statement?")
46
+ print(result.is_valid) # True
47
+
48
+ result = v.validate("What is my horoscope today?")
49
+ print(result.is_valid) # False
50
+ print(result.errors) # ['Query appears off-topic (score=0.000, threshold=0.250)']
51
+ ```
52
+
53
+ ## Training data format
54
+
55
+ Supported file formats: `.txt` (one question per line), `.csv` (first column), `.json` (list of strings or list of `{"text": "..."}` objects).
56
+
57
+ ```
58
+ # questions.txt
59
+ How do I write a SELECT statement?
60
+ What is a SQL JOIN?
61
+ How do I filter rows with WHERE clause?
62
+ What is the difference between INNER JOIN and LEFT JOIN?
63
+ ...
64
+ ```
65
+
66
+ ## Threshold calibration
67
+
68
+ The default threshold of `0.25` is a conservative starting point. Use `calibrate()` to find the optimal value for your domain:
69
+
70
+ ```python
71
+ in_domain = ["How do I use GROUP BY?", "What is a primary key?", ...]
72
+ off_domain = ["How do I bake bread?", "What is my horoscope?", ...]
73
+
74
+ result = v.calibrate(in_domain, off_domain)
75
+ result.summary() # prints precision/recall/F1 table
76
+ v.apply_calibration(result) # applies suggested threshold
77
+ ```
78
+
79
+ ## Incremental retraining
80
+
81
+ ```python
82
+ v.retrain(["How do I write a CTE?", "What is a window function?"])
83
+ # or from a file:
84
+ v.retrain_from_file("more_questions.txt")
85
+ ```
86
+
87
+ ## Semantic embeddings
88
+
89
+ For queries that use different words but mean the same thing:
90
+
91
+ ```python
92
+ v = NLQValidator.from_training_file(
93
+ "questions.txt",
94
+ SYSTEM_PROMPT,
95
+ embedding_model="all-MiniLM-L6-v2", # requires nlq-validator[embeddings]
96
+ )
97
+ ```
98
+
99
+ ## LLM-powered question generation
100
+
101
+ Generate training data automatically from your system prompt:
102
+
103
+ ```python
104
+ from nlq_validator.integrations.claude import ClaudeIntegration
105
+
106
+ llm = ClaudeIntegration() # reads ANTHROPIC_API_KEY env var
107
+ v = NLQValidator.from_llm(llm, SYSTEM_PROMPT, count=50)
108
+ ```
109
+
110
+ Async variant:
111
+
112
+ ```python
113
+ v = await NLQValidator.from_llm_async(llm, SYSTEM_PROMPT, count=50)
114
+ ```
115
+
116
+ ### Supported LLM providers
117
+
118
+ | Provider | Extra | Class | Env vars |
119
+ |-------------|--------------------|-----------------------|---------------------------------------|
120
+ | Claude | `[anthropic]` | `ClaudeIntegration` | `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL`|
121
+ | ChatGPT | `[openai]` | `ChatGPTIntegration` | `OPENAI_API_KEY`, `OPENAI_MODEL` |
122
+ | Gemini | `[gemini]` | `GeminiIntegration` | `GEMINI_API_KEY`, `GEMINI_MODEL` |
123
+ | Mistral | `[mistral]` | `MistralIntegration` | `MISTRAL_API_KEY`, `MISTRAL_MODEL` |
124
+ | Grok | `[openai]` | `GrokIntegration` | `XAI_API_KEY`, `XAI_MODEL` |
125
+ | Perplexity | `[openai]` | `PerplexityIntegration`| `PERPLEXITY_API_KEY`, `PERPLEXITY_MODEL`|
126
+
127
+ ## Save and load
128
+
129
+ ```python
130
+ v.save("my_model.pkl")
131
+ v2 = NLQValidator.load("my_model.pkl")
132
+ ```
133
+
134
+ ## License
135
+
136
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,63 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "nlq-validator"
7
+ version = "0.1.0"
8
+ description = "Lightweight Natural Language Query validator — keep your LLM assistant on-topic"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ authors = [{ name = "Balajee K", email = "kalyanasundarambalajee@gmail.com" }]
12
+ requires-python = ">=3.10"
13
+ keywords = [
14
+ "nlp",
15
+ "nlq",
16
+ "validator",
17
+ "llm",
18
+ "natural-language",
19
+ "query-validation",
20
+ "topic-model",
21
+ "tfidf",
22
+ "embeddings",
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 3 - Alpha",
26
+ "Intended Audience :: Developers",
27
+ "Programming Language :: Python :: 3",
28
+ "Programming Language :: Python :: 3.10",
29
+ "Programming Language :: Python :: 3.11",
30
+ "Programming Language :: Python :: 3.12",
31
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
32
+ "Topic :: Software Development :: Libraries :: Python Modules",
33
+ "Typing :: Typed",
34
+ ]
35
+ dependencies = [
36
+ "scikit-learn>=1.4",
37
+ ]
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/balajeekalyan/nlq-validator"
41
+ Repository = "https://github.com/balajeekalyan/nlq-validator"
42
+ "Bug Tracker" = "https://github.com/balajeekalyan/nlq-validator/issues"
43
+
44
+ [project.optional-dependencies]
45
+ dev = ["pytest>=8.0", "pytest-cov>=5.0", "ruff>=0.4"]
46
+ openai = ["openai>=1.0"]
47
+ anthropic = ["anthropic>=0.25"]
48
+ gemini = ["google-generativeai>=0.8"]
49
+ mistral = ["mistralai>=1.0"]
50
+ all-llm = ["openai>=1.0", "anthropic>=0.25", "google-generativeai>=0.8", "mistralai>=1.0"]
51
+ embeddings = ["sentence-transformers>=2.7"]
52
+
53
+ [tool.setuptools.packages.find]
54
+ where = ["src"]
55
+
56
+ [tool.pytest.ini_options]
57
+ testpaths = ["tests"]
58
+
59
+ [tool.ruff]
60
+ line-length = 100
61
+
62
+ [tool.ruff.lint]
63
+ select = ["E", "F", "I"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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)