sarnai 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.
sarnai/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """SarnAI: find agent services and verify agent output."""
2
+
3
+ from ._version import __version__
4
+ from .client import (BOARD_URL, VERIFY_URL, PaymentRequiredError, SarnAIClient,
5
+ SarnAIError, VerifyResult)
6
+
7
+ __all__ = ["SarnAIClient", "SarnAIError", "PaymentRequiredError", "VerifyResult",
8
+ "BOARD_URL", "VERIFY_URL", "__version__"]
sarnai/_tools.py ADDED
@@ -0,0 +1,74 @@
1
+ """Framework-neutral logic shared by the LangChain and CrewAI tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from .client import SarnAIClient, SarnAIError
9
+
10
+ FIND_SERVICE_DESCRIPTION = (
11
+ "Find AI agent services on the SarnAI Agent Discovery Board (MCP servers, x402 "
12
+ "services, REST APIs). Input: plain-words query. Returns JSON with matching "
13
+ "listings: id, name, description, endpoint_url, connection types, payment types."
14
+ )
15
+
16
+ VERIFY_OUTPUT_DESCRIPTION = (
17
+ "Verify an agent's JSON output against a JSON Schema with the SarnAI Agent Output "
18
+ "Verifier (free REST check). Input: expected_schema (JSON Schema, object or JSON "
19
+ "string) and submitted_output (the output to check, as JSON). Returns JSON with "
20
+ "result pass/fail, errors, and fix hints."
21
+ )
22
+
23
+ _LISTING_KEYS = ("id", "name", "description", "listing_type", "task_categories",
24
+ "endpoint_url", "pricing_amount", "stale")
25
+
26
+
27
+ def _load(value: Any) -> Any:
28
+ """Models often pass JSON as a string; accept both."""
29
+ if isinstance(value, str):
30
+ try:
31
+ return json.loads(value)
32
+ except ValueError:
33
+ return value
34
+ return value
35
+
36
+
37
+ def find_service(query: str, limit: int = 5, *, client: SarnAIClient | None = None) -> str:
38
+ own = client or SarnAIClient()
39
+ try:
40
+ page = own.search_listings(query, limit=limit)
41
+ except SarnAIError as exc:
42
+ return json.dumps({"error": str(exc)})
43
+ finally:
44
+ if client is None:
45
+ own.close()
46
+ listings = []
47
+ for item in page.get("listings", []):
48
+ row = {k: item.get(k) for k in _LISTING_KEYS}
49
+ row["connection_types"] = [c.get("type") for c in item.get("connections") or []]
50
+ row["payment_types"] = [p.get("type") for p in item.get("payment_methods") or []]
51
+ listings.append(row)
52
+ return json.dumps({"total": page.get("total"), "listings": listings})
53
+
54
+
55
+ def verify_output(expected_schema: Any, submitted_output: Any, *,
56
+ client: SarnAIClient | None = None) -> str:
57
+ schema = _load(expected_schema)
58
+ if not isinstance(schema, dict):
59
+ return json.dumps({"error": "expected_schema must be a JSON Schema object"})
60
+ own = client or SarnAIClient()
61
+ try:
62
+ result = own.verify_output(schema, _load(submitted_output))
63
+ except SarnAIError as exc:
64
+ return json.dumps({"error": str(exc)})
65
+ finally:
66
+ if client is None:
67
+ own.close()
68
+ return json.dumps({
69
+ "result": result.result,
70
+ "verification_id": result.verification_id,
71
+ "errors": result.errors,
72
+ "hints": result.hints,
73
+ "next_actions": result.raw.get("next_actions", []),
74
+ })
sarnai/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
sarnai/client.py ADDED
@@ -0,0 +1,192 @@
1
+ """HTTP client for the SarnAI Agent Discovery Board and Agent Output Verifier."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Iterable
8
+
9
+ import httpx
10
+
11
+ from ._version import __version__
12
+
13
+ BOARD_URL = "https://board.sarnai.dev"
14
+ VERIFY_URL = "https://verify.sarnai.dev"
15
+ USER_AGENT = f"sarnai-python/{__version__}"
16
+
17
+
18
+ class SarnAIError(Exception):
19
+ """A SarnAI service returned an error (or an unreadable response)."""
20
+
21
+ def __init__(self, message: str, *, status: int | None = None,
22
+ code: str | None = None, payload: Any = None):
23
+ super().__init__(message)
24
+ self.status = status
25
+ self.code = code
26
+ self.payload = payload
27
+
28
+
29
+ class PaymentRequiredError(SarnAIError):
30
+ """HTTP 402: the free allowance is used up and x402 payment is needed."""
31
+
32
+
33
+ @dataclass
34
+ class VerifyResult:
35
+ """Outcome of a verification. `raw` is the full signed response."""
36
+
37
+ result: str
38
+ verification_id: str
39
+ task_id: str
40
+ raw: dict[str, Any] = field(repr=False)
41
+
42
+ @property
43
+ def passed(self) -> bool:
44
+ return self.result == "pass"
45
+
46
+ @property
47
+ def errors(self) -> list[Any]:
48
+ return self.raw.get("errors") or []
49
+
50
+ @property
51
+ def hints(self) -> list[Any]:
52
+ return self.raw.get("hints") or []
53
+
54
+ @property
55
+ def attestation(self) -> dict[str, Any]:
56
+ return self.raw.get("attestation") or {}
57
+
58
+
59
+ def _clean(params: dict[str, Any]) -> dict[str, Any]:
60
+ return {k: v for k, v in params.items() if v is not None}
61
+
62
+
63
+ class SarnAIClient:
64
+ """Find services on the board and verify outputs. No secrets needed.
65
+
66
+ >>> with SarnAIClient() as sarnai:
67
+ ... page = sarnai.search_listings("invoice extraction", limit=5)
68
+ """
69
+
70
+ def __init__(self, *, board_url: str = BOARD_URL, verify_url: str = VERIFY_URL,
71
+ timeout: float = 30.0, client: httpx.Client | None = None,
72
+ transport: httpx.BaseTransport | None = None):
73
+ self.board_url = board_url.rstrip("/")
74
+ self.verify_url = verify_url.rstrip("/")
75
+ self._owns_client = client is None
76
+ self._http = client or httpx.Client(timeout=timeout, transport=transport)
77
+
78
+ def close(self) -> None:
79
+ if self._owns_client:
80
+ self._http.close()
81
+
82
+ def __enter__(self) -> "SarnAIClient":
83
+ return self
84
+
85
+ def __exit__(self, *exc: object) -> None:
86
+ self.close()
87
+
88
+ # -- board ---------------------------------------------------------------
89
+
90
+ def search_listings(
91
+ self,
92
+ q: str | None = None,
93
+ *,
94
+ listing_type: str | None = None,
95
+ task_category: str | Iterable[str] | None = None,
96
+ connection_type: str | Iterable[str] | None = None,
97
+ payment_type: str | Iterable[str] | None = None,
98
+ status: str | None = None,
99
+ limit: int | None = None,
100
+ cursor: str | None = None,
101
+ ) -> dict[str, Any]:
102
+ """GET /listings. Returns {listings, total, limit, offset, next_cursor}.
103
+
104
+ Without `q`, newest activity first; with `q`, ranked full-text search.
105
+ Pass `next_cursor` back as `cursor` for the next page (with the same `q`).
106
+ """
107
+ params: dict[str, Any] = _clean({
108
+ "q": q, "listing_type": listing_type, "status": status,
109
+ "limit": limit, "cursor": cursor,
110
+ })
111
+ for key, value in (("task_category", task_category),
112
+ ("connection_type", connection_type),
113
+ ("payment_type", payment_type)):
114
+ if value is not None:
115
+ params[key] = [value] if isinstance(value, str) else list(value)
116
+ return self._request("GET", f"{self.board_url}/listings", params=params)
117
+
118
+ def get_listing(self, listing_id: str) -> dict[str, Any]:
119
+ """GET /listings/{id}."""
120
+ return self._request("GET", f"{self.board_url}/listings/{listing_id}")
121
+
122
+ # -- verifier ------------------------------------------------------------
123
+
124
+ def verify_output(
125
+ self,
126
+ expected_schema: dict[str, Any],
127
+ submitted_output: Any,
128
+ *,
129
+ task_id: str | None = None,
130
+ agent_id: str | None = None,
131
+ rules: list[dict[str, Any]] | None = None,
132
+ bounds: dict[str, Any] | None = None,
133
+ enforce_rules: bool | None = None,
134
+ strict_content_check: bool | None = None,
135
+ compact: bool = False,
136
+ endpoint: str = "schema",
137
+ ) -> VerifyResult:
138
+ """POST /verify/schema (or /verify/deliverable with endpoint="deliverable").
139
+
140
+ Free during launch (see the verifier's llms.txt for the daily allowance).
141
+ Beyond it the service answers 402 and this raises PaymentRequiredError.
142
+ """
143
+ if endpoint not in ("schema", "deliverable"):
144
+ raise ValueError("endpoint must be 'schema' or 'deliverable'")
145
+ body = _clean({
146
+ "task_id": task_id or str(uuid.uuid4()),
147
+ "expected_schema": expected_schema,
148
+ "submitted_output": submitted_output,
149
+ "agent_id": agent_id,
150
+ "rules": rules,
151
+ "bounds": bounds,
152
+ "enforce_rules": enforce_rules,
153
+ "strict_content_check": strict_content_check,
154
+ "detail": "compact" if compact else None,
155
+ })
156
+ # submitted_output may legitimately be null; _clean would drop it.
157
+ body["submitted_output"] = submitted_output
158
+ data = self._request("POST", f"{self.verify_url}/verify/{endpoint}", json=body)
159
+ return VerifyResult(
160
+ result=data["result"],
161
+ verification_id=data.get("verification_id", ""),
162
+ task_id=data.get("task_id", body["task_id"]),
163
+ raw=data,
164
+ )
165
+
166
+ def reputation(self, agent_id: str) -> dict[str, Any]:
167
+ """GET /reputation/{agent_id}: free pass/fail call history."""
168
+ return self._request("GET", f"{self.verify_url}/reputation/{agent_id}")
169
+
170
+ # -- internals -----------------------------------------------------------
171
+
172
+ def _request(self, method: str, url: str, **kwargs: Any) -> Any:
173
+ try:
174
+ response = self._http.request(
175
+ method, url, headers={"User-Agent": USER_AGENT}, **kwargs)
176
+ except httpx.HTTPError as exc:
177
+ raise SarnAIError(f"request to {url} failed: {exc}") from exc
178
+ try:
179
+ payload = response.json()
180
+ except ValueError:
181
+ payload = None
182
+ if response.is_success:
183
+ if payload is None:
184
+ raise SarnAIError("response was not JSON", status=response.status_code)
185
+ return payload
186
+ # Board errors use `error_code`, the verifier uses `code`.
187
+ info = payload if isinstance(payload, dict) else {}
188
+ code = info.get("error_code") or info.get("code")
189
+ message = info.get("message") or response.text[:200] or "request failed"
190
+ cls = PaymentRequiredError if response.status_code == 402 else SarnAIError
191
+ raise cls(f"{response.status_code} {code or ''}: {message}".replace(" ", " "),
192
+ status=response.status_code, code=code, payload=payload)
sarnai/crewai.py ADDED
@@ -0,0 +1,47 @@
1
+ """CrewAI tools. Install with: pip install sarnai[crewai]"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ try:
8
+ from crewai.tools import BaseTool
9
+ except ImportError as exc: # pragma: no cover
10
+ raise ImportError("Install the extra: pip install sarnai[crewai]") from exc
11
+ from pydantic import BaseModel, Field
12
+
13
+ from . import _tools
14
+
15
+
16
+ class _FindServiceArgs(BaseModel):
17
+ query: str = Field(description="What you need, in plain words")
18
+ limit: int = Field(default=5, description="Maximum listings to return")
19
+
20
+
21
+ class _VerifyOutputArgs(BaseModel):
22
+ expected_schema: Any = Field(description="JSON Schema the output must satisfy")
23
+ submitted_output: Any = Field(description="The output to verify, as JSON")
24
+
25
+
26
+ class FindServiceTool(BaseTool):
27
+ name: str = "find_service"
28
+ description: str = _tools.FIND_SERVICE_DESCRIPTION
29
+ args_schema: type[BaseModel] = _FindServiceArgs
30
+
31
+ def _run(self, query: str, limit: int = 5) -> str:
32
+ return _tools.find_service(query, limit)
33
+
34
+
35
+ class VerifyOutputTool(BaseTool):
36
+ name: str = "verify_output"
37
+ description: str = _tools.VERIFY_OUTPUT_DESCRIPTION
38
+ args_schema: type[BaseModel] = _VerifyOutputArgs
39
+
40
+ def _run(self, expected_schema: Any, submitted_output: Any) -> str:
41
+ return _tools.verify_output(expected_schema, submitted_output)
42
+
43
+
44
+ find_service = FindServiceTool()
45
+ verify_output = VerifyOutputTool()
46
+ tools = [find_service, verify_output]
47
+ __all__ = ["FindServiceTool", "VerifyOutputTool", "find_service", "verify_output", "tools"]
sarnai/langchain.py ADDED
@@ -0,0 +1,32 @@
1
+ """LangChain tools. Install with: pip install sarnai[langchain]"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ try:
8
+ from langchain_core.tools import StructuredTool
9
+ except ImportError as exc: # pragma: no cover
10
+ raise ImportError("Install the extra: pip install sarnai[langchain]") from exc
11
+
12
+ from . import _tools
13
+
14
+ find_service = StructuredTool.from_function(
15
+ func=lambda query, limit=5: _tools.find_service(query, limit),
16
+ name="find_service",
17
+ description=_tools.FIND_SERVICE_DESCRIPTION,
18
+ )
19
+
20
+
21
+ def _verify(expected_schema: Any, submitted_output: Any) -> str:
22
+ return _tools.verify_output(expected_schema, submitted_output)
23
+
24
+
25
+ verify_output = StructuredTool.from_function(
26
+ func=_verify,
27
+ name="verify_output",
28
+ description=_tools.VERIFY_OUTPUT_DESCRIPTION,
29
+ )
30
+
31
+ tools = [find_service, verify_output]
32
+ __all__ = ["find_service", "verify_output", "tools"]
sarnai/py.typed ADDED
File without changes
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.5
2
+ Name: sarnai
3
+ Version: 0.1.0
4
+ Summary: Official SarnAI Python package: find agent services on the Agent Discovery Board and verify agent output.
5
+ Project-URL: Homepage, https://github.com/sarnai-dev/sarnai-python
6
+ Project-URL: Board, https://board.sarnai.dev
7
+ Project-URL: Verifier, https://verify.sarnai.dev
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,ai-agents,crewai,langchain,sarnai,verification,x402
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: httpx>=0.27
18
+ Provides-Extra: crewai
19
+ Requires-Dist: crewai>=0.100; extra == 'crewai'
20
+ Provides-Extra: dev
21
+ Requires-Dist: langchain-core>=0.3; extra == 'dev'
22
+ Requires-Dist: pytest>=8; extra == 'dev'
23
+ Provides-Extra: langchain
24
+ Requires-Dist: langchain-core>=0.3; extra == 'langchain'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # sarnai
28
+
29
+ Official SarnAI Python package: find agent services on the
30
+ [Agent Discovery Board](https://board.sarnai.dev) and verify agent output with the
31
+ [Agent Output Verifier](https://verify.sarnai.dev). No account or secrets needed.
32
+
33
+ ```
34
+ pip install sarnai # client only (httpx)
35
+ pip install sarnai[langchain] # + LangChain tools
36
+ pip install sarnai[crewai] # + CrewAI tools
37
+ ```
38
+
39
+ ## LangChain in 10 lines
40
+
41
+ ```python
42
+ from langchain.agents import create_agent
43
+ from sarnai.langchain import find_service, verify_output
44
+
45
+ agent = create_agent("anthropic:claude-sonnet-5-5", tools=[find_service, verify_output])
46
+ reply = agent.invoke({"messages": [
47
+ {"role": "user", "content": "Find a service that extracts invoice data, "
48
+ "then check this output against {\"type\":\"object\",\"required\":[\"total\"]}: {\"total\": 42}"}]})
49
+ print(reply["messages"][-1].content)
50
+ ```
51
+
52
+ CrewAI: `from sarnai.crewai import find_service, verify_output`.
53
+
54
+ ## Client
55
+
56
+ ```python
57
+ from sarnai import SarnAIClient
58
+
59
+ with SarnAIClient() as sarnai:
60
+ page = sarnai.search_listings("invoice extraction", limit=5) # GET /listings
61
+ listing = sarnai.get_listing(page["listings"][0]["id"]) # GET /listings/{id}
62
+ result = sarnai.verify_output( # POST /verify/schema
63
+ {"type": "object", "required": ["total"]}, {"total": 42})
64
+ print(result.passed, result.hints)
65
+ ```
66
+
67
+ Verification is free during launch (daily allowance per caller, see the
68
+ [verifier docs](https://verify.sarnai.dev/llms.txt)); beyond it the service answers 402 and the
69
+ client raises `PaymentRequiredError`. Errors raise `SarnAIError` with `status` and `code`.
70
+
71
+ ## Tests
72
+
73
+ ```
74
+ pytest # everything, including live calls to the SarnAI services
75
+ pytest -m "not live" # offline only
76
+ ```
77
+
78
+ ## License
79
+
80
+ MIT
@@ -0,0 +1,11 @@
1
+ sarnai/__init__.py,sha256=Vradio4W3kvrO3XZNkMe2PKc1TdzFfAUcwdDUGf3m9k,358
2
+ sarnai/_tools.py,sha256=BNTHSoV4n5L3bZDRjR_ffDhzO2L0H874VM56nL2vlKI,2712
3
+ sarnai/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
4
+ sarnai/client.py,sha256=tt-O1jdMdYIG49r7s0Q9POzvEoq3gXqJo0qmSrEPjas,7138
5
+ sarnai/crewai.py,sha256=k8R3KS8_EMFcICHVKre-3wgn40anRvo468wxhAUl3ss,1533
6
+ sarnai/langchain.py,sha256=YcwooXvMgXssidLt9xgyNsytLhqKQj706sW9KiJhNrY,896
7
+ sarnai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ sarnai-0.1.0.dist-info/METADATA,sha256=tWpMPmyaPW3i4q4gmbJBNSQy_lr3bOrGtzwPy_AR9o8,2846
9
+ sarnai-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
10
+ sarnai-0.1.0.dist-info/licenses/LICENSE,sha256=DZX5mmhScozvQJp-RS_dbA_t5FjG8HN4wyJ8IVIosAg,1064
11
+ sarnai-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mglbagi
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.