Skip to content

Create, Evaluate, and Connect AI Skills

fix(search): default to relevance and align public query limits

Icarus-Chen5f70e1680cdc
diff --git a/README.md b/README.md
index 23389a5..02bc811 100644
--- a/README.md
+++ b/README.md
@@ -147,7 +147,8 @@ The client reads environment variables and saved settings. See
### Search
Search the hosted SkillNet catalog by keyword or semantic intent. Keyword search
-defaults to sorting by stars; vector search uses the search service's embeddings.
+uses BM25 and ranks results by relevance by default; vector search uses the
+search service's embeddings.
```python
results = client.search(
@@ -338,7 +339,7 @@ for complete examples. `skillnet configure --interactive` saves settings locally
The SkillNet search API is public and requires no authentication.
```bash
-curl "http://api-skillnet.openkg.cn/v1/search?q=pdf&sort_by=stars&limit=5"
+curl "http://api-skillnet.openkg.cn/v1/search?q=pdf&limit=5"
curl "http://api-skillnet.openkg.cn/v1/search?q=reading%20charts&mode=vector&threshold=0.8"
```
@@ -355,8 +356,7 @@ curl "http://api-skillnet.openkg.cn/v1/search?q=reading%20charts&mode=vector&thr
| `limit` | int | `10` | Results per page, max 50 |
| `page` | int | `1` | Page number, keyword mode only |
| `min_stars` | int | `0` | Minimum star count, keyword mode only |
-| `sort_by` | string | `stars` | `stars` or `recent`, keyword mode only |
-| `sort_order` | string | `desc` | `desc` or `asc`, keyword mode only; REST API only |
+| `sort_by` | string | `relevance` | `relevance`, `stars` or `recent`, descending; keyword mode only |
| `threshold` | float | `0.8` | Similarity threshold, vector mode only |
</details>
diff --git a/skillnet-ai/README.md b/skillnet-ai/README.md
index d17aa20..55f9c3f 100644
--- a/skillnet-ai/README.md
+++ b/skillnet-ai/README.md
@@ -116,7 +116,9 @@ endpoints are configured separately.
### Search
Query the hosted SkillNet catalog and return a list of skill records. Keyword
-search works with short names/keywords and defaults to sorting by repository stars.
+search uses BM25 across skill names, descriptions, and tags, ranked by relevance
+by default. Use `sort_by="stars"` or `sort_by="recent"` to change the order.
+
For natural-language tasks, use vector search, which returns results in similarity
order using the hosted service's embeddings. `EMBEDDING_*` settings apply to local
analysis and routing.
@@ -152,7 +154,7 @@ includes both fields. Source metadata is `None` when unavailable.
| `limit` | `int` | `20` | Results requested; the public service accepts 1–50 |
| `page` | `int` | `1` | Page number for keyword search |
| `min_stars` | `int` | `0` | Minimum star count for keyword search |
-| `sort_by` | `str` | `"stars"` | `"stars"` or `"recent"` for keyword search |
+| `sort_by` | `str` | `"relevance"` | `"relevance"`, `"stars"` or `"recent"`, descending; keyword only |
| `threshold` | `float` | `0.8` | Similarity threshold for vector search |
</details>
diff --git a/skillnet-ai/src/skillnet_ai/core/models.py b/skillnet-ai/src/skillnet_ai/core/models.py
index c643a14..726ceeb 100644
--- a/skillnet-ai/src/skillnet_ai/core/models.py
+++ b/skillnet-ai/src/skillnet_ai/core/models.py
@@ -44,7 +44,6 @@ class MetaModel(BaseModel):
page: int | None = None
min_stars: int | None = None
sort_by: str | None = None
- sort_order: str | None = None
# Vector mode specific fields (may be None in Keyword mode)
threshold: float | None = None
diff --git a/skillnet-ai/src/skillnet_ai/interfaces/cli.py b/skillnet-ai/src/skillnet_ai/interfaces/cli.py
index e602dfa..c3d2c0a 100644
--- a/skillnet-ai/src/skillnet_ai/interfaces/cli.py
+++ b/skillnet-ai/src/skillnet_ai/interfaces/cli.py
@@ -106,10 +106,10 @@ def search(
q: str = typer.Argument(...),
mode: str = typer.Option("keyword", help="keyword or vector"),
category: str | None = typer.Option(None),
- limit: int = typer.Option(20, min=1, max=100),
+ limit: int = typer.Option(20, min=1, max=50),
page: int = typer.Option(1, min=1),
min_stars: int = typer.Option(0, min=0),
- sort_by: str = typer.Option("stars"),
+ sort_by: str = typer.Option("relevance", help="relevance, stars or recent; descending"),
threshold: float = typer.Option(0.8, min=0, max=1),
json_output: bool = typer.Option(False, "--json"),
):
diff --git a/skillnet-ai/src/skillnet_ai/interfaces/client.py b/skillnet-ai/src/skillnet_ai/interfaces/client.py
index 05e1fa7..9a93bb8 100644
--- a/skillnet-ai/src/skillnet_ai/interfaces/client.py
+++ b/skillnet-ai/src/skillnet_ai/interfaces/client.py
@@ -9,6 +9,7 @@ from skillnet_ai.core.models import (
Endpoint,
RouteOptions,
RouteResult,
+ SkillModel,
)
from skillnet_ai.creator import SkillCreator
from skillnet_ai.downloader import GitHubAPIError, SkillDownloader
@@ -64,14 +65,14 @@ class SkillNetClient:
def search(
self,
q: str,
- mode: str = "keyword",
+ mode: Literal["keyword", "vector"] = "keyword",
category: str | None = None,
limit: int = 20,
page: int = 1,
min_stars: int = 0,
- sort_by: str = "stars",
+ sort_by: str = "relevance",
threshold: float = 0.8,
- ) -> list[Any]:
+ ) -> list[SkillModel]:
"""
Search for skills on SkillNet.
@@ -82,7 +83,7 @@ class SkillNetClient:
limit: Max results.
page: Page number (keyword mode only).
min_stars: Filter by stars (keyword mode only).
- sort_by: 'stars' or 'recent' (keyword mode only).
+ sort_by: 'relevance', 'stars' or 'recent', descending (keyword mode only).
threshold: Similarity threshold (vector mode only).
Returns:
diff --git a/skillnet-ai/src/skillnet_ai/searcher.py b/skillnet-ai/src/skillnet_ai/searcher.py
index 27eb8c4..b0976ba 100644
--- a/skillnet-ai/src/skillnet_ai/searcher.py
+++ b/skillnet-ai/src/skillnet_ai/searcher.py
@@ -1,101 +1,106 @@
-import requests
import logging
-from typing import Optional, List, Dict, Any, Literal
-from skillnet_ai.core.models import SearchResponse
+from typing import Literal
+
+import requests
+
from skillnet_ai.core.config import resolve_settings
+from skillnet_ai.core.models import SearchResponse, SkillModel
# Configure logger
logger = logging.getLogger(__name__)
+
class SkillNetSearcher:
"""
- Skiil Searcher for interacting with the SkillNet Search API.
+ Skill searcher for interacting with the SkillNet Search API.
"""
-
- def __init__(self, skillnet_api_url: Optional[str] = None):
- self.skillnet_api_url = resolve_settings(skillnet_api_url=skillnet_api_url).skillnet_api_url.rstrip("/")
+
+ def __init__(self, skillnet_api_url: str | None = None) -> None:
+ self.skillnet_api_url = resolve_settings(
+ skillnet_api_url=skillnet_api_url
+ ).skillnet_api_url.rstrip("/")
self.session = requests.Session()
- self.session.headers.update({
- "User-Agent": "SkillNet-Python-SDK/0.1.3"
- })
+ self.session.headers.update({"User-Agent": "SkillNet-Python-SDK/0.1.3"})
def search(
- self,
- q: str,
+ self,
+ q: str,
mode: Literal["keyword", "vector"] = "keyword",
- category: Optional[str] = None,
+ category: str | None = None,
limit: int = 20,
# --- Keyword mode ---
page: int = 1,
- min_stars: int = 0,
- sort_by: str = "stars",
+ min_stars: int = 0,
+ sort_by: str = "relevance",
# --- Vector mode ---
- threshold: float = 0.8
- ) -> List[Dict[str, Any]]:
+ threshold: float = 0.8,
+ ) -> list[SkillModel]:
"""
Unified search for skills (supports both Keyword and AI Vector search).
-
+
Args:
q: Search query (Keywords or Natural Language).
- mode: 'keyword' for exact/fuzzy match, 'vector' for semantic AI search.
+ mode: 'keyword' for BM25 matching, 'vector' for semantic AI search.
category: Filter by category (e.g., 'Development').
limit: Items per page (keyword) or Match count (vector).
-
+
# Keyword specific:
page: Page number.
min_stars: Minimum stars filter.
- sort_by: Sort field ('stars' or 'recent').
-
+ sort_by: Sort field ('relevance', 'stars' or 'recent'), descending.
+
# Vector specific:
threshold: Similarity threshold (0.0 to 1.0).
Returns:
- A list of skill dictionaries.
+ A list of skill records.
"""
if mode not in {"keyword", "vector"}:
raise ValueError("Search mode must be keyword or vector.")
- if not 1 <= limit <= 100 or page < 1 or not 0 <= threshold <= 1:
- raise ValueError("Use limit 1–100, page >= 1 and threshold 0–1.")
+ if not 1 <= limit <= 50 or page < 1 or not 0 <= threshold <= 1:
+ raise ValueError("Use limit 1–50, page >= 1 and threshold 0–1.")
endpoint = f"{self.skillnet_api_url}/v1/search"
-
+
# 1. Construct base parameters
- params = {
+ params: dict[str, str | int | float | None] = {
"q": q,
"mode": mode,
"category": category,
- "limit": limit
+ "limit": limit,
}
# 2. Add mode-specific parameters
if mode == "keyword":
- params.update({
- "page": page,
- "min_stars": min_stars,
- "sort_by": sort_by,
- })
+ params.update(
+ {
+ "page": page,
+ "min_stars": min_stars,
+ "sort_by": sort_by,
+ }
+ )
elif mode == "vector":
- params.update({
- "threshold": threshold
- })
+ params.update({"threshold": threshold})
# 3. Clean None values
params = {k: v for k, v in params.items() if v is not None}
try:
logger.debug(f"Searching skills ({mode} mode) with params: {params}")
-
+
# Make the request
response = self.session.get(endpoint, params=params, timeout=15)
response.raise_for_status()
-
+
# Parse response
search_res = SearchResponse(**response.json())
-
+
if not search_res.success:
- raise RuntimeError("Search API returned success=False; this is not an empty result.")
+ raise RuntimeError(
+ "Search API returned success=False; this is not an empty result."
+ )
return search_res.data
-
+
except requests.exceptions.RequestException as e:
logger.error(f"Search request failed: {e}")
raise
diff --git a/skillnet-ai/tests/test_sdk_search_sources.py b/skillnet-ai/tests/test_sdk_search_sources.py
index f444bb3..cad6e1d 100644
--- a/skillnet-ai/tests/test_sdk_search_sources.py
+++ b/skillnet-ai/tests/test_sdk_search_sources.py
@@ -10,7 +10,7 @@ from typer.testing import CliRunner
from skillnet_ai.core.models import SkillModel
from skillnet_ai.interfaces import cli
-from skillnet_ai.interfaces.client import SkillNetClient
+from skillnet_ai.interfaces.client import SkillNetClient, SkillNetError
@pytest.fixture
@@ -44,6 +44,8 @@ def test_sdk_and_cli_json_preserve_source_identity(search_response):
(r.get("repo_name"), r.get("skill_dir")) for r in rows
]
assert get.call_count == 1
+ assert get.call_args.kwargs["params"]["sort_by"] == "relevance"
+ assert "sort_order" not in get.call_args.kwargs["params"]
assert "repo_name" not in get.call_args.kwargs["params"]
assert "skill_dir" not in get.call_args.kwargs["params"]
output = CliRunner().invoke(cli.app, ["search", "example", "--json"])
@@ -55,6 +57,88 @@ def test_sdk_and_cli_json_preserve_source_identity(search_response):
assert [r["skill_url"] for r in data] == [r.get("skill_url") for r in rows]
[email protected]("mode", ["keyword", "vector"])
+def test_both_modes_keep_the_existing_sdk_and_cli_output(search_response, monkeypatch, mode):
+ rows, get = search_response
+ response = get.return_value
+ response._content = json.dumps(
+ {
+ "success": True,
+ "data": [
+ {
+ **row,
+ "relevance_score": 3.25 if mode == "keyword" else None,
+ "similarity": 0.9 if mode == "vector" else None,
+ }
+ for row in rows
+ ],
+ "meta": {},
+ }
+ ).encode()
+ expected = [SkillModel(**row).model_dump() for row in rows]
+ results = SkillNetClient().search("example", mode=mode)
+ assert [row.model_dump() for row in results] == expected
+ params = get.call_args.kwargs["params"]
+ assert "sort_order" not in params
+ if mode == "keyword":
+ assert params["sort_by"] == "relevance"
+ else:
+ assert "sort_by" not in params
+
+ output = CliRunner().invoke(cli.app, ["search", "example", "--mode", mode, "--json"])
+ assert output.exit_code == 0, output.output
+ assert json.loads(output.stdout)["data"] == expected
+
+ monkeypatch.setattr(cli, "console", Console(width=180, force_terminal=False, highlight=False))
+ output = CliRunner().invoke(cli.app, ["search", "example", "--mode", mode])
+ assert output.exit_code == 0, output.output
+ assert "Repo Stars" in output.stdout and "Description" in output.stdout
+ assert "relevance_score" not in output.stdout and "similarity" not in output.stdout
+
+
[email protected]("sort_by", ["stars", "recent"])
+def test_explicit_keyword_sorts_remain_available(search_response, sort_by):
+ _, get = search_response
+ result = CliRunner().invoke(cli.app, ["search", "example", "--sort-by", sort_by])
+ assert result.exit_code == 0, result.output
+ assert get.call_args.kwargs["params"]["sort_by"] == sort_by
+ assert "sort_order" not in get.call_args.kwargs["params"]
+
+
+def test_cli_has_no_sort_order_option():
+ help_result = CliRunner().invoke(cli.app, ["search", "--help"])
+ assert help_result.exit_code == 0
+ assert "--sort-order" not in help_result.stdout
+ result = CliRunner().invoke(cli.app, ["search", "example", "--sort-order", "asc"])
+ assert result.exit_code == 2
+
+
[email protected]("mode", ["keyword", "vector"])
[email protected]("limit", [0, 51, 100])
+def test_invalid_limit_is_rejected_before_http(search_response, mode, limit):
+ _, get = search_response
+ with pytest.raises(SkillNetError, match="limit 1–50"):
+ SkillNetClient().search("example", mode=mode, limit=limit)
+ result = CliRunner().invoke(
+ cli.app, ["search", "example", "--mode", mode, "--limit", str(limit)]
+ )
+ assert result.exit_code == 2
+ get.assert_not_called()
+
+
[email protected]("mode", ["keyword", "vector"])
[email protected]("limit", [1, 50])
+def test_public_limit_boundaries_reach_the_service(search_response, mode, limit):
+ _, get = search_response
+ SkillNetClient().search("example", mode=mode, limit=limit)
+ assert get.call_args.kwargs["params"]["limit"] == limit
+ result = CliRunner().invoke(
+ cli.app, ["search", "example", "--mode", mode, "--limit", str(limit)]
+ )
+ assert result.exit_code == 0, result.output
+ assert get.call_args.kwargs["params"]["limit"] == limit
+
+
def test_cli_displays_sources_without_changing_download_urls(search_response, monkeypatch):
monkeypatch.setattr(cli, "console", Console(width=180, force_terminal=False, highlight=False))
output = CliRunner().invoke(cli.app, ["search", "example"])