vigimod 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,3 @@
1
+ dist/
2
+ *.tgz
3
+ index.cjs
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-16)
4
+
5
+ First release: `VigiMod` and `AsyncVigiMod` with `moderate`, `moderate_batch`, `events` and `status`; typed results;
6
+ retries on 429 and 5xx; no dependencies.
vigimod-0.1.0/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VigiMod
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
vigimod-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.5
2
+ Name: vigimod
3
+ Version: 0.1.0
4
+ Summary: Official Python client for the VigiMod content moderation API: toxicity, hate, spam and custom rules in 26 languages.
5
+ Project-URL: Homepage, https://www.vigimod.com
6
+ Project-URL: Documentation, https://www.vigimod.com/en/docs
7
+ Project-URL: API reference, https://api.vigimod.com/openapi.json
8
+ Author-email: VigiMod <support@vigimod.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: chat moderation,content moderation,discord,hate speech,moderation,perspective api,profanity,spam,toxicity
12
+ Classifier: Framework :: AsyncIO
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Communications :: Chat
17
+ Classifier: Topic :: Internet :: WWW/HTTP
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+
22
+ # VigiMod for Python
23
+
24
+ Official Python client for the [VigiMod](https://www.vigimod.com) content moderation API: toxicity, insults, hate, threats, sexual content, self-harm, advertising and per-user spam, plus rules you write in plain language, reading the conversation, in 26 languages. No dependencies.
25
+
26
+ ```bash
27
+ pip install vigimod
28
+ ```
29
+
30
+ Get a free API key (free during the beta) at [my.vigimod.com](https://my.vigimod.com) and set `VIGIMOD_API_KEY`.
31
+
32
+ ## Moderate a message
33
+
34
+ ```python
35
+ from vigimod import VigiMod
36
+
37
+ client = VigiMod() # reads VIGIMOD_API_KEY
38
+
39
+ result = client.moderate("you are an idiot", categories=["toxic", "insult"])
40
+ result.flagged # True
41
+ result.flags # {"toxic": True, "insult": True}
42
+ result.scores["toxic"] # 0.9999
43
+ ```
44
+
45
+ ## In a Discord bot (asyncio)
46
+
47
+ `AsyncVigiMod` has the same methods, awaitable, so the bot never blocks:
48
+
49
+ ```python
50
+ import discord
51
+ from vigimod import AsyncVigiMod
52
+
53
+ vigimod = AsyncVigiMod()
54
+ intents = discord.Intents.default()
55
+ intents.message_content = True
56
+ bot = discord.Client(intents=intents)
57
+
58
+ @bot.event
59
+ async def on_message(message):
60
+ if message.author.bot:
61
+ return
62
+ result = await vigimod.moderate(
63
+ message.content,
64
+ user_id=str(message.author.id), # per-user spam score
65
+ scope=str(message.guild.id), # one spam history per server
66
+ rules={"no-ads": "No advertising other Discord servers"},
67
+ )
68
+ if result.flagged:
69
+ await message.delete()
70
+ ```
71
+
72
+ ## Context and your own rules
73
+
74
+ ```python
75
+ result = client.moderate(
76
+ "lmao the dog dies at the end",
77
+ context=["anyone watched the finale last night?", "not yet, tonight!"],
78
+ rules={"no-spoilers": "No spoilers about movies or series"},
79
+ )
80
+ result.flags["rule:no-spoilers"] # True
81
+ ```
82
+
83
+ ## Per-user spam, slurs and policies
84
+
85
+ ```python
86
+ client.moderate(text, user_id=author_id, scope=server_id) # spam score from repeated messages
87
+ client.moderate(text, block_slurs=True) # slur lists in six languages
88
+ client.moderate(text, policy="pol_0123456789abcdef") # a policy made in the dashboard
89
+ result.action # "review", "delete", "warn", "timeout" or "ban"
90
+ ```
91
+
92
+ ## Many messages at once
93
+
94
+ ```python
95
+ results = client.moderate_batch(["first message", {"text": "second", "categories": ["hate"]}])
96
+ ```
97
+
98
+ ## Errors and limits
99
+
100
+ `RateLimitError` (429) and server errors are retried twice with a pause; after that the error is raised. `APIError` has `.status` and `.body`.
101
+
102
+ ```python
103
+ from vigimod import RateLimitError
104
+
105
+ try:
106
+ client.moderate(text)
107
+ except RateLimitError as e:
108
+ print("slow down, retry in", e.retry_after)
109
+ ```
110
+
111
+ ## Coming from Perspective API?
112
+
113
+ VigiMod also answers Perspective's `comments:analyze` requests: change the host and the key. See the [migration guide](https://www.vigimod.com/en/perspective-api-alternative).
114
+
115
+ ## Links
116
+
117
+ - [Documentation](https://www.vigimod.com/en/docs) · [Pricing](https://www.vigimod.com/en/pricing) · [Benchmark](https://www.vigimod.com/en/benchmark) · [Free toxicity checker](https://www.vigimod.com/en/tools/toxicity-checker)
118
+ - Questions: support@vigimod.com
119
+
120
+ MIT licence.
@@ -0,0 +1,99 @@
1
+ # VigiMod for Python
2
+
3
+ Official Python client for the [VigiMod](https://www.vigimod.com) content moderation API: toxicity, insults, hate, threats, sexual content, self-harm, advertising and per-user spam, plus rules you write in plain language, reading the conversation, in 26 languages. No dependencies.
4
+
5
+ ```bash
6
+ pip install vigimod
7
+ ```
8
+
9
+ Get a free API key (free during the beta) at [my.vigimod.com](https://my.vigimod.com) and set `VIGIMOD_API_KEY`.
10
+
11
+ ## Moderate a message
12
+
13
+ ```python
14
+ from vigimod import VigiMod
15
+
16
+ client = VigiMod() # reads VIGIMOD_API_KEY
17
+
18
+ result = client.moderate("you are an idiot", categories=["toxic", "insult"])
19
+ result.flagged # True
20
+ result.flags # {"toxic": True, "insult": True}
21
+ result.scores["toxic"] # 0.9999
22
+ ```
23
+
24
+ ## In a Discord bot (asyncio)
25
+
26
+ `AsyncVigiMod` has the same methods, awaitable, so the bot never blocks:
27
+
28
+ ```python
29
+ import discord
30
+ from vigimod import AsyncVigiMod
31
+
32
+ vigimod = AsyncVigiMod()
33
+ intents = discord.Intents.default()
34
+ intents.message_content = True
35
+ bot = discord.Client(intents=intents)
36
+
37
+ @bot.event
38
+ async def on_message(message):
39
+ if message.author.bot:
40
+ return
41
+ result = await vigimod.moderate(
42
+ message.content,
43
+ user_id=str(message.author.id), # per-user spam score
44
+ scope=str(message.guild.id), # one spam history per server
45
+ rules={"no-ads": "No advertising other Discord servers"},
46
+ )
47
+ if result.flagged:
48
+ await message.delete()
49
+ ```
50
+
51
+ ## Context and your own rules
52
+
53
+ ```python
54
+ result = client.moderate(
55
+ "lmao the dog dies at the end",
56
+ context=["anyone watched the finale last night?", "not yet, tonight!"],
57
+ rules={"no-spoilers": "No spoilers about movies or series"},
58
+ )
59
+ result.flags["rule:no-spoilers"] # True
60
+ ```
61
+
62
+ ## Per-user spam, slurs and policies
63
+
64
+ ```python
65
+ client.moderate(text, user_id=author_id, scope=server_id) # spam score from repeated messages
66
+ client.moderate(text, block_slurs=True) # slur lists in six languages
67
+ client.moderate(text, policy="pol_0123456789abcdef") # a policy made in the dashboard
68
+ result.action # "review", "delete", "warn", "timeout" or "ban"
69
+ ```
70
+
71
+ ## Many messages at once
72
+
73
+ ```python
74
+ results = client.moderate_batch(["first message", {"text": "second", "categories": ["hate"]}])
75
+ ```
76
+
77
+ ## Errors and limits
78
+
79
+ `RateLimitError` (429) and server errors are retried twice with a pause; after that the error is raised. `APIError` has `.status` and `.body`.
80
+
81
+ ```python
82
+ from vigimod import RateLimitError
83
+
84
+ try:
85
+ client.moderate(text)
86
+ except RateLimitError as e:
87
+ print("slow down, retry in", e.retry_after)
88
+ ```
89
+
90
+ ## Coming from Perspective API?
91
+
92
+ VigiMod also answers Perspective's `comments:analyze` requests: change the host and the key. See the [migration guide](https://www.vigimod.com/en/perspective-api-alternative).
93
+
94
+ ## Links
95
+
96
+ - [Documentation](https://www.vigimod.com/en/docs) · [Pricing](https://www.vigimod.com/en/pricing) · [Benchmark](https://www.vigimod.com/en/benchmark) · [Free toxicity checker](https://www.vigimod.com/en/tools/toxicity-checker)
97
+ - Questions: support@vigimod.com
98
+
99
+ MIT licence.
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "vigimod"
7
+ dynamic = ["version"]
8
+ description = "Official Python client for the VigiMod content moderation API: toxicity, hate, spam and custom rules in 26 languages."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "VigiMod", email = "support@vigimod.com" }]
13
+ keywords = ["moderation", "content moderation", "toxicity", "hate speech", "profanity", "spam", "perspective api", "chat moderation", "discord"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ "Topic :: Communications :: Chat",
18
+ "Topic :: Internet :: WWW/HTTP",
19
+ "Intended Audience :: Developers",
20
+ "Framework :: AsyncIO",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = []
24
+
25
+ [project.urls]
26
+ Homepage = "https://www.vigimod.com"
27
+ Documentation = "https://www.vigimod.com/en/docs"
28
+ "API reference" = "https://api.vigimod.com/openapi.json"
29
+
30
+ [tool.hatch.version]
31
+ path = "src/vigimod/_version.py"
32
+ pattern = "VERSION = \"(?P<version>[^\"]+)\""
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["src/vigimod"]
36
+
37
+ [tool.pytest.ini_options]
38
+ pythonpath = ["src"]
@@ -0,0 +1,18 @@
1
+ """Official Python client for the VigiMod content moderation API (https://www.vigimod.com).
2
+
3
+ from vigimod import VigiMod
4
+
5
+ client = VigiMod() # reads VIGIMOD_API_KEY
6
+ result = client.moderate("you are an idiot", categories=["toxic", "insult"])
7
+ if result.flagged:
8
+ print(result.flags, result.scores)
9
+
10
+ In asyncio code (discord.py, FastAPI) use AsyncVigiMod: the same methods, awaitable.
11
+ """
12
+
13
+ from .aio import AsyncVigiMod
14
+ from .client import APIError, RateLimitError, VigiMod, VigiModError
15
+ from .types import ModerationResult
16
+
17
+ __all__ = ["VigiMod", "AsyncVigiMod", "ModerationResult", "VigiModError", "APIError", "RateLimitError"]
18
+ from ._version import VERSION as __version__
@@ -0,0 +1 @@
1
+ VERSION = "0.1.0"
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ from typing import Any, Iterable, Mapping
5
+
6
+ from .client import DEFAULT_BASE_URL, VigiMod
7
+ from .types import ModerationResult
8
+
9
+
10
+ class AsyncVigiMod:
11
+ """The same client for asyncio code (discord.py, FastAPI, aiohttp bots): every method is awaitable and runs the
12
+ request in a worker thread, so the event loop never blocks. Same arguments as VigiMod."""
13
+
14
+ def __init__(self, api_key: str | None = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0, max_retries: int = 2):
15
+ self._sync = VigiMod(api_key, base_url=base_url, timeout=timeout, max_retries=max_retries)
16
+
17
+ async def moderate(self, text: str, **options: Any) -> ModerationResult:
18
+ return await asyncio.to_thread(self._sync.moderate, text, **options)
19
+
20
+ async def moderate_batch(self, items: Iterable[Mapping[str, Any] | str]) -> list[ModerationResult]:
21
+ return await asyncio.to_thread(self._sync.moderate_batch, list(items))
22
+
23
+ async def events(self, after: int = 0, limit: int = 100) -> dict[str, Any]:
24
+ return await asyncio.to_thread(self._sync.events, after, limit)
25
+
26
+ async def status(self) -> dict[str, Any]:
27
+ return await asyncio.to_thread(self._sync.status)
@@ -0,0 +1,139 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import time
6
+ import urllib.error
7
+ import urllib.parse
8
+ import urllib.request
9
+ from typing import Any, Iterable, Mapping
10
+
11
+ from .types import ModerationResult
12
+
13
+ DEFAULT_BASE_URL = "https://api.vigimod.com"
14
+ from . import _version
15
+
16
+ _USER_AGENT = f"vigimod-python/{_version.VERSION}"
17
+
18
+
19
+ class VigiModError(Exception):
20
+ """Base error of this package."""
21
+
22
+
23
+ class APIError(VigiModError):
24
+ """The API answered with an error (4xx or 5xx)."""
25
+
26
+ def __init__(self, status: int, message: str, body: Any = None):
27
+ super().__init__(f"{status}: {message}")
28
+ self.status = status
29
+ self.body = body
30
+
31
+
32
+ class RateLimitError(APIError):
33
+ """429: too many messages for this key. retry_after is in seconds, when the API says it."""
34
+
35
+ def __init__(self, status: int, message: str, body: Any = None, retry_after: float | None = None):
36
+ super().__init__(status, message, body)
37
+ self.retry_after = retry_after
38
+
39
+
40
+ class VigiMod:
41
+ """Client for the VigiMod API.
42
+
43
+ api_key: your key (default: the VIGIMOD_API_KEY environment variable). Create one at https://my.vigimod.com.
44
+ base_url: the API address (default https://api.vigimod.com).
45
+ timeout: seconds per request.
46
+ max_retries: retries on 429 and 5xx answers and on network errors, with a growing pause.
47
+ """
48
+
49
+ def __init__(self, api_key: str | None = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0, max_retries: int = 2):
50
+ key = api_key or os.environ.get("VIGIMOD_API_KEY")
51
+ if not key:
52
+ raise VigiModError("No API key: pass api_key=... or set VIGIMOD_API_KEY (get one free at https://my.vigimod.com)")
53
+ self._key = key
54
+ self.base_url = base_url.rstrip("/")
55
+ self.timeout = timeout
56
+ self.max_retries = max_retries
57
+
58
+ # ---- endpoints ----
59
+
60
+ def moderate(self, text: str, *, categories: Iterable[str] | None = None, rules: Mapping[str, Any] | None = None,
61
+ context: Iterable[str] | None = None, thresholds: Mapping[str, float] | None = None,
62
+ user_id: str | None = None, scope: str | None = None, block_slurs: bool | None = None,
63
+ policy: str | None = None, ref: str | None = None) -> ModerationResult:
64
+ """Score one message. Every argument but text is optional; see https://www.vigimod.com/en/docs."""
65
+ body = _clean({"text": text, "categories": _list(categories), "rules": _dict(rules), "context": _list(context),
66
+ "thresholds": _dict(thresholds), "user_id": user_id, "scope": scope, "block_slurs": block_slurs,
67
+ "policy": policy, "ref": ref})
68
+ return ModerationResult.from_json(self._request("POST", "/moderate", body))
69
+
70
+ def moderate_batch(self, items: Iterable[Mapping[str, Any] | str]) -> list[ModerationResult]:
71
+ """Score several messages in one call. Each item is a text or a dict with the same fields as moderate()."""
72
+ payload = [{"text": i} if isinstance(i, str) else _clean(dict(i)) for i in items]
73
+ data = self._request("POST", "/moderate/batch", {"items": payload})
74
+ return [ModerationResult.from_json(r) for r in data.get("results", [])]
75
+
76
+ def events(self, after: int = 0, limit: int = 100) -> dict[str, Any]:
77
+ """The account's events of the last 7 days (the same as the webhooks), oldest first."""
78
+ return self._request("GET", "/events?" + urllib.parse.urlencode({"after": after, "limit": limit}))
79
+
80
+ def status(self) -> dict[str, Any]:
81
+ """The model version, its categories and what the options support."""
82
+ return self._request("GET", "/status")
83
+
84
+ # ---- transport ----
85
+
86
+ def _request(self, method: str, path: str, body: Any = None) -> Any:
87
+ data = json.dumps(body).encode() if body is not None else None
88
+ headers = {"X-API-Key": self._key, "Accept": "application/json", "User-Agent": _USER_AGENT}
89
+ if data is not None:
90
+ headers["Content-Type"] = "application/json"
91
+ attempt = 0
92
+ while True:
93
+ req = urllib.request.Request(self.base_url + path, data=data, method=method, headers=headers)
94
+ try:
95
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
96
+ return json.loads(res.read() or b"null")
97
+ except urllib.error.HTTPError as e:
98
+ err = _error(e)
99
+ if attempt < self.max_retries and (e.code == 429 or e.code >= 500):
100
+ wait = err.retry_after if isinstance(err, RateLimitError) and err.retry_after else 0.5 * 2 ** attempt
101
+ time.sleep(min(wait, 30))
102
+ attempt += 1
103
+ continue
104
+ raise err from None
105
+ except (urllib.error.URLError, TimeoutError) as e:
106
+ if attempt < self.max_retries:
107
+ time.sleep(0.5 * 2 ** attempt)
108
+ attempt += 1
109
+ continue
110
+ raise VigiModError(f"Could not reach {self.base_url}: {e}") from e
111
+
112
+
113
+ def _error(e: urllib.error.HTTPError) -> APIError:
114
+ raw = e.read()
115
+ try:
116
+ body = json.loads(raw)
117
+ except ValueError:
118
+ body = raw.decode(errors="replace")
119
+ message = body.get("detail") or body.get("error") if isinstance(body, dict) else body
120
+ if e.code == 429:
121
+ ra = e.headers.get("Retry-After")
122
+ try:
123
+ retry = float(ra) if ra else None
124
+ except ValueError:
125
+ retry = None
126
+ return RateLimitError(e.code, str(message or "rate limited"), body, retry)
127
+ return APIError(e.code, str(message or e.reason), body)
128
+
129
+
130
+ def _clean(d: dict[str, Any]) -> dict[str, Any]:
131
+ return {k: v for k, v in d.items() if v is not None}
132
+
133
+
134
+ def _list(x: Iterable[str] | None) -> list[str] | None:
135
+ return None if x is None else list(x)
136
+
137
+
138
+ def _dict(x: Mapping[str, Any] | None) -> dict[str, Any] | None:
139
+ return None if x is None else dict(x)
File without changes
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from typing import Any
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class ModerationResult:
9
+ """The answer for one message.
10
+
11
+ scores: 0 to 1 per category and per rule ("rule:<name>"); spam is None without user_id.
12
+ flags: True where the score passed its threshold.
13
+ flagged: True if any category or rule is flagged.
14
+ raw: the full JSON answer (spam_info, blocklist_matches, policy, action, ref, review_id, model_version).
15
+ """
16
+
17
+ scores: dict[str, float | None]
18
+ flags: dict[str, bool]
19
+ flagged: bool
20
+ raw: dict[str, Any] = field(repr=False)
21
+
22
+ @property
23
+ def action(self) -> str | None:
24
+ """The policy action decided for this message (e.g. "review", "delete", "warn", "timeout", "ban"), if any."""
25
+ a = self.raw.get("action")
26
+ return a.get("type") if isinstance(a, dict) else a
27
+
28
+ @property
29
+ def model_version(self) -> str | None:
30
+ return self.raw.get("model_version")
31
+
32
+ @classmethod
33
+ def from_json(cls, data: dict[str, Any]) -> "ModerationResult":
34
+ return cls(scores=dict(data.get("scores") or {}), flags=dict(data.get("flags") or {}),
35
+ flagged=bool(data.get("flagged")), raw=data)
@@ -0,0 +1,100 @@
1
+ import json
2
+ import threading
3
+ from http.server import BaseHTTPRequestHandler, HTTPServer
4
+
5
+ import pytest
6
+
7
+ from vigimod import APIError, RateLimitError, VigiMod, VigiModError
8
+
9
+ CALLS = []
10
+
11
+
12
+ class Handler(BaseHTTPRequestHandler):
13
+ def log_message(self, *a):
14
+ pass
15
+
16
+ def _send(self, code, body, headers=None):
17
+ raw = json.dumps(body).encode()
18
+ self.send_response(code)
19
+ self.send_header("Content-Type", "application/json")
20
+ for k, v in (headers or {}).items():
21
+ self.send_header(k, v)
22
+ self.send_header("Content-Length", str(len(raw)))
23
+ self.end_headers()
24
+ self.wfile.write(raw)
25
+
26
+ def do_POST(self):
27
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
28
+ CALLS.append((self.path, self.headers.get("X-API-Key"), body))
29
+ if self.headers.get("X-API-Key") != "k":
30
+ return self._send(401, {"detail": "Invalid or missing X-API-Key"})
31
+ if body.get("text") == "rate":
32
+ return self._send(429, {"detail": "Rate limit exceeded"}, {"Retry-After": "0"})
33
+ if self.path == "/moderate":
34
+ return self._send(200, {"scores": {"toxic": 0.99}, "flags": {"toxic": True}, "flagged": True,
35
+ "action": {"type": "warn"}, "model_version": "vigimod-1.2.1"})
36
+ if self.path == "/moderate/batch":
37
+ return self._send(200, {"results": [{"scores": {}, "flags": {}, "flagged": False} for _ in body["items"]],
38
+ "model_version": "vigimod-1.2.1"})
39
+
40
+ def do_GET(self):
41
+ CALLS.append((self.path, self.headers.get("X-API-Key"), None))
42
+ self._send(200, {"events": [], "next": 0} if self.path.startswith("/events") else {"model_version": "vigimod-1.2.1"})
43
+
44
+
45
+ @pytest.fixture(scope="module")
46
+ def base():
47
+ srv = HTTPServer(("127.0.0.1", 0), Handler)
48
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
49
+ yield f"http://127.0.0.1:{srv.server_port}"
50
+ srv.shutdown()
51
+
52
+
53
+ def test_moderate_sends_only_given_fields(base):
54
+ r = VigiMod("k", base_url=base).moderate("hi", categories=("toxic",), context=["a"], user_id="u1")
55
+ path, key, body = CALLS[-1]
56
+ assert (path, key) == ("/moderate", "k")
57
+ assert body == {"text": "hi", "categories": ["toxic"], "context": ["a"], "user_id": "u1"}
58
+ assert r.flagged and r.flags["toxic"] and r.scores["toxic"] == 0.99
59
+ assert r.action == "warn" and r.model_version == "vigimod-1.2.1"
60
+
61
+
62
+ def test_batch_accepts_texts_and_dicts(base):
63
+ out = VigiMod("k", base_url=base).moderate_batch(["a", {"text": "b", "categories": ["hate"], "scope": None}])
64
+ assert CALLS[-1][2] == {"items": [{"text": "a"}, {"text": "b", "categories": ["hate"]}]}
65
+ assert len(out) == 2 and not out[0].flagged
66
+
67
+
68
+ def test_errors(base):
69
+ with pytest.raises(APIError) as e:
70
+ VigiMod("wrong", base_url=base).moderate("hi")
71
+ assert e.value.status == 401 and "X-API-Key" in str(e.value)
72
+ n = len(CALLS)
73
+ with pytest.raises(RateLimitError) as e:
74
+ VigiMod("k", base_url=base, max_retries=1).moderate("rate")
75
+ assert e.value.retry_after == 0 and len(CALLS) - n == 2 # one retry
76
+
77
+
78
+ def test_get_endpoints_and_missing_key(base, monkeypatch):
79
+ c = VigiMod("k", base_url=base)
80
+ c.events(after=5, limit=10)
81
+ assert CALLS[-1][0] == "/events?after=5&limit=10"
82
+ assert c.status()["model_version"] == "vigimod-1.2.1"
83
+ monkeypatch.delenv("VIGIMOD_API_KEY", raising=False)
84
+ with pytest.raises(VigiModError):
85
+ VigiMod()
86
+
87
+
88
+ def test_async_client(base):
89
+ import asyncio
90
+
91
+ from vigimod import AsyncVigiMod
92
+
93
+ async def run():
94
+ c = AsyncVigiMod("k", base_url=base)
95
+ r = await c.moderate("hi", categories=["toxic"])
96
+ b = await c.moderate_batch(["a", "b"])
97
+ return r, b
98
+
99
+ r, b = asyncio.run(run())
100
+ assert r.flagged and len(b) == 2