mcp-plesk-dev-docs 0.4.2__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,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcp-plesk-dev-docs
3
+ Version: 0.4.2
4
+ Summary: A unified MCP server that indexes and retrieves Plesk documentation using vector embeddings and semantic search with reranking
5
+ Author-email: Gilson Siqueira <gilson@example.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/barateza/mcp-plesk-dev-docs
8
+ Project-URL: Documentation, https://github.com/barateza/mcp-plesk-dev-docs#readme
9
+ Project-URL: Repository, https://github.com/barateza/mcp-plesk-dev-docs.git
10
+ Project-URL: Bug Tracker, https://github.com/barateza/mcp-plesk-dev-docs/issues
11
+ Keywords: plesk,mcp,model-context-protocol,semantic-search,rag,vector-database
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Documentation
19
+ Classifier: Topic :: System :: Monitoring
20
+ Classifier: Topic :: Utilities
21
+ Requires-Python: >=3.12
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ License-File: NOTICE
25
+ Requires-Dist: beautifulsoup4>=4.14.3
26
+ Requires-Dist: fastmcp>=3.2.4
27
+ Requires-Dist: lancedb>=0.29.1
28
+ Requires-Dist: pylance>=0.23.0
29
+ Requires-Dist: numpy>=1.26.0
30
+ Requires-Dist: psutil>=6.1.1
31
+ Requires-Dist: pydantic>=2.10.0
32
+ Requires-Dist: pydantic-settings>=2.7.1
33
+ Requires-Dist: sentence-transformers>=5.2.2
34
+ Requires-Dist: torch>=2.4.0
35
+ Requires-Dist: markdownify>=0.14.1
36
+ Requires-Dist: tantivy>=0.22.0
37
+ Requires-Dist: lance-namespace==0.6.1
38
+ Provides-Extra: dev
39
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
40
+ Requires-Dist: requests>=2.32.0; extra == "dev"
41
+ Requires-Dist: ruff>=0.3.0; extra == "dev"
42
+ Requires-Dist: pre-commit>=3.6.0; extra == "dev"
43
+ Provides-Extra: test
44
+ Requires-Dist: pytest>=8.0.0; extra == "test"
45
+ Provides-Extra: tools
46
+ Requires-Dist: requests>=2.32.0; extra == "tools"
47
+ Dynamic: license-file
48
+
49
+ # mcp-plesk-dev-docs
50
+
51
+ [![Python 3.12+](https://img.shields.io/badge/python-3.12%2B-blue?style=flat-square)](https://www.python.org/downloads/)
52
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](LICENSE)
53
+ [![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-green?style=flat-square)](https://modelcontextprotocol.io/)
54
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://github.com/psf/black)
55
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=flat-square)](https://github.com/astral-sh/ruff)
56
+
57
+ **State-of-the-Art (SOTA) semantic search across the entire Plesk documentation surface, optimized for sub-second latency on Apple Silicon.**
58
+
59
+ ---
60
+
61
+ ## Why this exists
62
+
63
+ Plesk documentation is spread across five separate sources: an admin guide, a REST API reference, a CLI reference, a PHP SDK, and a JS SDK. Answering a single extension development question often means searching all of them manually, cross-referencing results, and still missing the relevant section.
64
+
65
+ This server ingests all five sources, embeds them with a multilingual model, and exposes a single `search_plesk_unified` MCP tool. It uses hybrid search (Vector + FTS), Reciprocal Rank Fusion (RRF), and Cross-Encoder reranking to deliver high-precision results in milliseconds.
66
+
67
+ ---
68
+
69
+ ## Architecture & Performance
70
+
71
+ ```mermaid
72
+ flowchart TD
73
+ Client["MCP Client\n(Claude Desktop / Cursor / etc.)"]
74
+
75
+ Client -->|"search_plesk_unified(query)"| Server
76
+
77
+ subgraph Server["FastMCP Server · Modular Architecture"]
78
+ direction TB
79
+ Main["Bootstrap · server/main.py"]
80
+ Life["Lifecycle Hooks · server/lifecycle.py"]
81
+ Tools["MCP Tools · server/mcp_app.py"]
82
+
83
+ Main --> Life --> Tools
84
+ end
85
+
86
+ subgraph Pipeline["Retrieval Pipeline"]
87
+ direction TB
88
+ E["1 · Embed query\n(Hardware-accelerated)"]
89
+ S["2 · Hybrid Search\nVector (LanceDB) + FTS (Tantivy)"]
90
+ R["3 · RRF Merge + Rerank\n(MiniLM-L4-v2)"]
91
+ N["4 · Neighbor Expansion\n(Context Enrichment)"]
92
+ A["5 · AI Synthesis\n(sampling-enabled)"]
93
+ E --> S --> R --> N --> A
94
+ end
95
+
96
+ subgraph Store["LanceDB Vector & FTS Store"]
97
+ direction LR
98
+ G["Guide"]
99
+ A_["API"]
100
+ C["CLI"]
101
+ P["PHP Stubs"]
102
+ J["JS SDK"]
103
+ end
104
+
105
+ Tools --> Pipeline
106
+ S <--> Store
107
+ ```
108
+
109
+ ### Performance Benchmarks (2026-05-04)
110
+ Optimized for Apple Silicon (M2/M3) using MPS acceleration and memory-resident table caching.
111
+
112
+ | Profile | Embed Model | HR@5 | MRR@5 | Avg Latency | Est. RAM |
113
+ | :--- | :--- | :--- | :--- | :--- | :--- |
114
+ | **`light`** | BAAI/bge-small | **100.0%** | **0.917** | **1.007 s** | ~200 MB |
115
+ | **`medium`** | BAAI/bge-base | **100.0%** | **0.917** | **~0.60s** | ~600 MB |
116
+ | **`full-tq`** | BAAI/bge-m3 | 75.0% | 0.750 | **~0.40s** | ~1300 MB |
117
+
118
+ *Metrics measured on Apple M2 Pro with LanceDB connection caching enabled.*
119
+
120
+ ---
121
+
122
+ ## Key Features
123
+
124
+ - **Sub-Second Hybrid Search:** Combined Vector + Tantivy FTS with **RAM-cached table connections** for instant retrieval.
125
+ - **AST-Aware Chunking:** Uses `tree-sitter` to respect class and method boundaries in PHP, JS, and TS documentation.
126
+ - **TurboQuant Acceleration:** Fast 4-bit quantized search for the `full-tq` profile, delivering 10x lower latency for large models.
127
+ - **Neighborhood Retrieval:** Automatically fetches adjacent chunks (prev/next) to provide complete context for grounding.
128
+ - **Macro-Context Summaries:** Injects file-level purpose summaries into every chunk using the `SummaryCache`.
129
+ - **AI-Synthesized Answers:** Generates concise answers from search results with structured inline citations `[1]`, `[2]`.
130
+
131
+ ---
132
+
133
+ ## MCP Components
134
+
135
+ This server provides tools, prompts, and resources. See **[docs/mcp-components.md](docs/mcp-components.md)** for a full reference.
136
+
137
+ ### Primary Tools
138
+
139
+ | Tool | Description |
140
+ |---|---|
141
+ | `search_plesk_unified` | Hybrid search with RRF and Cross-Encoder reranking. |
142
+ | `get_file_content` | Retrieve the full content of a specific documentation file. |
143
+ | `resolve_references` | Find all files referencing a specific symbol or topic. |
144
+ | `refresh_knowledge` | Re-fetch sources and update the index (incremental). |
145
+ | `trigger_index_sync` | Start a background indexing job. |
146
+ | `daemon_health` | Check readiness, hardware acceleration (MPS/CUDA), and latency stats. |
147
+
148
+ ### Resources
149
+
150
+ - `plesk://toc/api` - Table of Contents for API documentation.
151
+ - `plesk://toc/cli` - Table of Contents for CLI reference.
152
+ - `plesk://toc/guide` - Table of Contents for Extensions Guide.
153
+ - `plesk://toc/php-stubs` - Hierarchical list of PHP classes.
154
+
155
+ ---
156
+
157
+ ## Quickstart
158
+
159
+ ### Install
160
+
161
+ ```bash
162
+ git clone https://github.com/barateza/mcp-plesk-dev-docs.git
163
+ cd mcp-plesk-dev-docs
164
+ uv pip install -e .
165
+ ```
166
+
167
+ ### Initial Indexing
168
+
169
+ ```bash
170
+ uv run python -m mcp_plesk_dev_docs.server.main refresh_knowledge
171
+ ```
172
+
173
+ ### Running
174
+
175
+ ```bash
176
+ # Standard mode
177
+ uv run python -m mcp_plesk_dev_docs.server.main
178
+
179
+ # Responsive daemon mode (auto-warmup)
180
+ PLESK_DAEMON_AUTO_WARMUP=true uv run python -m mcp_plesk_dev_docs.server.main
181
+ ```
182
+
183
+ ---
184
+
185
+ ## Configuration
186
+
187
+ Set environment variables in `.env`:
188
+
189
+ ```env
190
+ PLESK_MODEL_PROFILE=light # light | medium | full-tq
191
+ PLESK_ENABLE_SAMPLING=true # AI-Synthesized answers
192
+ PLESK_DAEMON_AUTO_WARMUP=true # Preload models on startup
193
+ PLESK_INDEX_SUMMARIES=true # Enable file-level summaries
194
+ OPENROUTER_API_KEY=sk-or-v1-...
195
+ ```
196
+
197
+ ---
198
+
199
+ ## Documentation
200
+
201
+ - **[docs/benchmarks.md](docs/benchmarks.md)** - Detailed latency and quality reports.
202
+ - **[docs/mcp-components.md](docs/mcp-components.md)** - Full tool and resource reference.
203
+ - **[docs/turboquant.md](docs/turboquant.md)** - 4-bit quantization internals.
204
+
205
+ ---
206
+
207
+ ## License
208
+
209
+ MIT. See [LICENSE](LICENSE).
210
+
211
+ ## Ownership & Disclaimer
212
+
213
+ This is a personal project by Gilson Siqueira. It is not officially affiliated with, endorsed by, or supported by Plesk or WebPros International GmbH. Plesk is a trademark of WebPros International GmbH.
214
+
215
+ Important notice about Plesk-owned deliverables
216
+
217
+ Portions of this repository were developed under contract for Plesk International GmbH ("Plesk") only if specifically identified as such. The MIT license above applies only to material the repository owner is authorized to license. Files or directories owned by Plesk, if any, are listed in [NOTICE](NOTICE). If you need assurance about licensing for a particular file, contact Plesk or seek legal counsel before relying on the MIT License for Plesk-owned files.
218
+
219
+ *Built to make Plesk extension development faster.*
220
+
221
+ <!-- mcp-name: io.github.barateza/mcp-plesk-dev-docs -->
@@ -0,0 +1,30 @@
1
+ mcp_plesk_dev_docs-0.4.2.dist-info/licenses/LICENSE,sha256=DAUQMJI5O7eP9m7odM9DuvgQcc4aEQAz2tcr5jcsk4g,1072
2
+ mcp_plesk_dev_docs-0.4.2.dist-info/licenses/NOTICE,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ plesk_unified/__init__.py,sha256=rYrEqs-AW78q99P-HMJc0uvgiHGdVhhafkhDpVt6Cjs,74
4
+ plesk_unified/ai_client.py,sha256=qyLHZrhWgpmSeHVPPPPuSO1ySEZGVJj2dXfELflWr60,9822
5
+ plesk_unified/benchmark_engines.py,sha256=N0BqBm6DnaUss8cqKWWu4Kf0bOtFtbPjuxHI_E1tEtc,8583
6
+ plesk_unified/benchmark_gates.py,sha256=WH6Wexqj_13jhFei14IFQvqDsMzi0LpVQqVJFhTzFvY,7971
7
+ plesk_unified/benchmark_reporting.py,sha256=fhIqyibyPfqcxRLloxLbrPx07CqKiqzo-eZs5q841RM,3938
8
+ plesk_unified/benchmark_runner.py,sha256=9vxzw1C6710E5Y5eKmZknvtDM2TrCle27nDut7CuVi4,14877
9
+ plesk_unified/benchmark_suites.py,sha256=jDNUia71S_Y4nO_MAVBrnqVMAtNZtUelAZsiYfOnFjI,901
10
+ plesk_unified/chunking.py,sha256=3C-KabtgwEEjxewbkajxFtQIFOflzbappUdLqluywV0,11266
11
+ plesk_unified/error_handling.py,sha256=7BTO7eaJkB8yDiIzlXTXAZbVqpa1UoRcfMkV21_duBg,3835
12
+ plesk_unified/html_utils.py,sha256=1X_68woscZqwnXOHQK4MZ2zLcecrb7sY_tZZkuQt2Yw,6511
13
+ plesk_unified/indexing.py,sha256=9GbkRGK0-KhVN7ohVD4Thzmr57jx86qxubYAL7shfI4,1805
14
+ plesk_unified/io_utils.py,sha256=PYK9TUkoEjZPLG80ZEUoOXS7VckD7tBfjYLF2V9zztY,9749
15
+ plesk_unified/log_handler.py,sha256=NaV9rRyDjFUiItNE8T4dpnTB3k4LbgGF-6t_FzBe0HI,7553
16
+ plesk_unified/model_config.py,sha256=c05V64wbxpOlTeYDq1vxN2AJdcnYyjMjoe1z6eGc_Ys,7386
17
+ plesk_unified/platform_utils.py,sha256=Q2CqeDaErk6a5IIjF5D8rxPWEkZ4nP8jyN85ylWa5G0,6244
18
+ plesk_unified/settings.py,sha256=ptmZ7VumrlEcUJTpwYIY8fzPjpqmnCYUP_ygUxhjuzs,3255
19
+ plesk_unified/summary_cache.py,sha256=iT_kxCbndF2NDwSetqimpuY_-urZlvvUVr0IHuRw364,1890
20
+ plesk_unified/tq_index.py,sha256=T7Fusl-7GXK5PMQ2_IucBJXSkTIHVeppoDyi9cMnuE4,3085
21
+ plesk_unified/types.py,sha256=xArD8LxLb1IdvjLlPA0tkHjc8zxDbXUiBT3SzpQAHII,735
22
+ plesk_unified/turboquant/__init__.py,sha256=7mCd6gZRbMnJevSt9dB1glddUVxj1PseFmx_6KPPA40,629
23
+ plesk_unified/turboquant/compressors.py,sha256=Vo_6VabVafnvOA1OHTFGnhDnxbg9ER_TPAj1JcZhe8s,6864
24
+ plesk_unified/turboquant/lloyd_max.py,sha256=tnMboA97bDd2MGNfPPYXOrXYM2-63yEI83vvT81B5kw,6270
25
+ plesk_unified/turboquant/turboquant.py,sha256=-5G4vz9apVLATzPyu3oVJoqw7su_DdLOZOE5OM-EI1k,7795
26
+ mcp_plesk_dev_docs-0.4.2.dist-info/METADATA,sha256=NsFuaU_dsArUG3aNwWgLT-26mxMxw9fCSzYEPfU9CGg,8692
27
+ mcp_plesk_dev_docs-0.4.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
28
+ mcp_plesk_dev_docs-0.4.2.dist-info/entry_points.txt,sha256=iBoGseS6PEcwx4sBqTp76JDE5PWCobbei5vKTeFide8,65
29
+ mcp_plesk_dev_docs-0.4.2.dist-info/top_level.txt,sha256=UCi5kMuaZggLf-5-cJZXODKDlL6xQBpPQCjASPasBiQ,14
30
+ mcp_plesk_dev_docs-0.4.2.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,2 @@
1
+ [console_scripts]
2
+ mcp-plesk-dev-docs = plesk_unified.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Gilson Siqueira
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.
File without changes
@@ -0,0 +1 @@
1
+ plesk_unified
@@ -0,0 +1,3 @@
1
+ """plesk_unified helper package."""
2
+
3
+ __all__ = ["html_utils", "chunking"]
@@ -0,0 +1,257 @@
1
+ import json
2
+ import logging
3
+ import os
4
+ import re
5
+ from typing import List, Optional
6
+
7
+ import requests
8
+ import httpx
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ DEFAULT_MODELS = [
13
+ "deepseek/deepseek-v4-flash",
14
+ "google/gemini-2.5-flash-lite",
15
+ "x-ai/grok-4.1-fast",
16
+ "nvidia/nemotron-3-super-120b-a12b:free",
17
+ ]
18
+
19
+ # RAGAS judge model — chosen for instruction-following + low verbosity on strict
20
+ # "Score 0.0–1.0" tasks.
21
+ RAGAS_DEFAULT_MODELS = [
22
+ "google/gemini-2.0-flash",
23
+ "anthropic/claude-3-haiku",
24
+ ]
25
+
26
+
27
+ class AIClient:
28
+ """A thin wrapper for LLM calls with retry/fallback policy."""
29
+
30
+ def __init__(self, api_key: Optional[str] = None):
31
+ self.api_key = api_key or os.environ.get("OPENROUTER_API_KEY", "")
32
+ if not self.api_key:
33
+ logger.warning("OPENROUTER_API_KEY is not set. AI calls will fail.")
34
+ else:
35
+ logger.info("AIClient initialized with an API key.")
36
+ self._async_client: Optional[httpx.AsyncClient] = None
37
+
38
+ async def get_async_client(self) -> httpx.AsyncClient:
39
+ if self._async_client is None or self._async_client.is_closed:
40
+ self._async_client = httpx.AsyncClient(timeout=30.0)
41
+ return self._async_client
42
+
43
+ async def close(self):
44
+ if self._async_client and not self._async_client.is_closed:
45
+ await self._async_client.aclose()
46
+
47
+ def generate_answer(
48
+ self, query: str, context: str, model_list: Optional[List[str]] = None
49
+ ) -> str:
50
+ """
51
+ Generate an answer to the query based strictly on the provided context.
52
+ """
53
+ models = model_list if model_list is not None else DEFAULT_MODELS
54
+
55
+ for model in models:
56
+ try:
57
+ content = (
58
+ f"CONTEXT:\n{context}\n\n"
59
+ f"QUERY: {query}\n\n"
60
+ "Answer the query based ONLY on the provided context. "
61
+ "If the information is not present, say 'Information not found'."
62
+ )
63
+
64
+ payload = {
65
+ "model": model,
66
+ "messages": [{"role": "user", "content": content}],
67
+ "max_tokens": 500,
68
+ }
69
+
70
+ logger.debug(f"Sending request to model {model} (answer generation)")
71
+ response = requests.post(
72
+ url="https://openrouter.ai/api/v1/chat/completions",
73
+ headers={
74
+ "Authorization": f"Bearer {self.api_key}",
75
+ "Content-Type": "application/json",
76
+ },
77
+ data=json.dumps(payload),
78
+ timeout=20,
79
+ )
80
+ if response.status_code == 200:
81
+ data = response.json()
82
+ choices = data.get("choices")
83
+ if choices and "message" in choices[0]:
84
+ res = choices[0]["message"].get("content")
85
+ if res:
86
+ return res.strip()
87
+
88
+ logger.error(f"Model {model} returned status {response.status_code}")
89
+ except Exception as e:
90
+ logger.error(f"Answer Model {model} failed with exception: {e}")
91
+ continue
92
+
93
+ return "Error generating answer."
94
+
95
+ async def generate_description_async(
96
+ self, text: str, model_list: Optional[List[str]] = None
97
+ ) -> str:
98
+ """
99
+ Attempts to get a description using a tiered fallback system (Asynchronous).
100
+ """
101
+ if not text.strip():
102
+ return "File unreadable."
103
+
104
+ models = model_list if model_list is not None else DEFAULT_MODELS
105
+ client = await self.get_async_client()
106
+
107
+ for model in models:
108
+ try:
109
+ content = (
110
+ "Summarize the technical purpose of the following text "
111
+ "in exactly one concise sentence.\n\n" + text
112
+ )
113
+
114
+ payload = {
115
+ "model": model,
116
+ "messages": [{"role": "user", "content": content}],
117
+ "max_tokens": 100,
118
+ }
119
+
120
+ # Force DeepSeek provider for deepseek models
121
+ # to avoid slow providers like deepinfra
122
+ if "deepseek" in model:
123
+ payload["provider"] = {"order": ["DeepSeek"]}
124
+
125
+ response = await client.post(
126
+ url="https://openrouter.ai/api/v1/chat/completions",
127
+ headers={
128
+ "Authorization": f"Bearer {self.api_key}",
129
+ "Content-Type": "application/json",
130
+ },
131
+ json=payload,
132
+ )
133
+ if response.status_code == 200:
134
+ data = response.json()
135
+ choices = data.get("choices")
136
+ if choices and "message" in choices[0]:
137
+ res = choices[0]["message"].get("content")
138
+ if res:
139
+ return res.strip()
140
+
141
+ logger.error(f"Model {model} returned status {response.status_code}")
142
+ except Exception as e:
143
+ logger.error(f"Model {model} failed with exception: {e}")
144
+ continue
145
+
146
+ return "Description unavailable."
147
+
148
+ def generate_description(
149
+ self, text: str, model_list: Optional[List[str]] = None
150
+ ) -> str:
151
+ """
152
+ Attempts to get a description using a tiered fallback system.
153
+ """
154
+ if not text.strip():
155
+ return "File unreadable."
156
+
157
+ models = model_list if model_list is not None else DEFAULT_MODELS
158
+
159
+ logger.info(f"AIClient.generate_description called for text length {len(text)}")
160
+ for model in models:
161
+ try:
162
+ content = (
163
+ "Summarize the technical purpose of the following text "
164
+ "in exactly one concise sentence.\n\n" + text
165
+ )
166
+
167
+ payload = {
168
+ "model": model,
169
+ "messages": [{"role": "user", "content": content}],
170
+ "max_tokens": 100,
171
+ }
172
+
173
+ logger.info(f"Sending description request to model {model}")
174
+ response = requests.post(
175
+ url="https://openrouter.ai/api/v1/chat/completions",
176
+ headers={
177
+ "Authorization": f"Bearer {self.api_key}",
178
+ "Content-Type": "application/json",
179
+ },
180
+ data=json.dumps(payload),
181
+ timeout=15,
182
+ )
183
+ if response.status_code == 200:
184
+ data = response.json()
185
+ choices = data.get("choices")
186
+ if choices and "message" in choices[0]:
187
+ res = choices[0]["message"].get("content")
188
+ if res:
189
+ logger.info(
190
+ f"Successfully generated description using {model}"
191
+ )
192
+ return res.strip()
193
+
194
+ logger.error(f"Model {model} returned status {response.status_code}")
195
+ except Exception as e:
196
+ logger.error(f"Model {model} failed with exception: {e}")
197
+ continue
198
+
199
+ return "Description unavailable."
200
+
201
+ def evaluate_ragas_score(
202
+ self, prompt: str, model_list: Optional[List[str]] = None
203
+ ) -> float:
204
+ """
205
+ Evaluate a RAGAS metric prompt and return a score between 0.0 and 1.0.
206
+ Uses stricter instruction following for the judge model.
207
+ """
208
+ models = model_list if model_list is not None else RAGAS_DEFAULT_MODELS
209
+
210
+ for model in models:
211
+ try:
212
+ payload = {
213
+ "model": model,
214
+ "messages": [
215
+ {
216
+ "role": "system",
217
+ "content": (
218
+ "You are a precise evaluator. Output ONLY a single "
219
+ "float number between 0.0 and 1.0 representing the "
220
+ "score. No explanation, no extra text."
221
+ ),
222
+ },
223
+ {"role": "user", "content": prompt},
224
+ ],
225
+ "max_tokens": 10,
226
+ }
227
+
228
+ response = requests.post(
229
+ url="https://openrouter.ai/api/v1/chat/completions",
230
+ headers={
231
+ "Authorization": f"Bearer {self.api_key}",
232
+ "Content-Type": "application/json",
233
+ },
234
+ data=json.dumps(payload),
235
+ timeout=20,
236
+ )
237
+ if response.status_code == 200:
238
+ data = response.json()
239
+ choices = data.get("choices")
240
+ if choices and "message" in choices[0]:
241
+ msg = choices[0]["message"]
242
+ text = msg.get("content", "").strip()
243
+ # Try to find a float in the response
244
+ match = re.search(r"(\d?\.\d+)", text)
245
+ if match:
246
+ return float(match.group(1))
247
+ if text in ["0", "1"]:
248
+ return float(text)
249
+ else:
250
+ logger.debug(
251
+ f"RAGAS Model {model} returned status {response.status_code}"
252
+ )
253
+ except Exception as e:
254
+ logger.debug(f"RAGAS Model {model} failed with exception: {e}")
255
+ continue
256
+
257
+ return 0.0