sarnai 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.
- sarnai-0.1.0/.github/workflows/publish.yml +35 -0
- sarnai-0.1.0/.github/workflows/test.yml +23 -0
- sarnai-0.1.0/.gitignore +220 -0
- sarnai-0.1.0/CLAUDE.md +20 -0
- sarnai-0.1.0/LICENSE +21 -0
- sarnai-0.1.0/PKG-INFO +80 -0
- sarnai-0.1.0/README.md +54 -0
- sarnai-0.1.0/pyproject.toml +41 -0
- sarnai-0.1.0/src/sarnai/__init__.py +8 -0
- sarnai-0.1.0/src/sarnai/_tools.py +74 -0
- sarnai-0.1.0/src/sarnai/_version.py +1 -0
- sarnai-0.1.0/src/sarnai/client.py +192 -0
- sarnai-0.1.0/src/sarnai/crewai.py +47 -0
- sarnai-0.1.0/src/sarnai/langchain.py +32 -0
- sarnai-0.1.0/src/sarnai/py.typed +0 -0
- sarnai-0.1.0/tests/test_live.py +54 -0
- sarnai-0.1.0/tests/test_offline.py +87 -0
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
name: publish
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
jobs:
|
|
8
|
+
build:
|
|
9
|
+
runs-on: ubuntu-latest
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
steps:
|
|
13
|
+
- uses: actions/checkout@v4
|
|
14
|
+
- uses: actions/setup-python@v5
|
|
15
|
+
with:
|
|
16
|
+
python-version: "3.12"
|
|
17
|
+
- run: python -m pip install build
|
|
18
|
+
- run: python -m build
|
|
19
|
+
- uses: actions/upload-artifact@v4
|
|
20
|
+
with:
|
|
21
|
+
name: dist
|
|
22
|
+
path: dist/
|
|
23
|
+
|
|
24
|
+
publish:
|
|
25
|
+
needs: build
|
|
26
|
+
runs-on: ubuntu-latest
|
|
27
|
+
environment: pypi
|
|
28
|
+
permissions:
|
|
29
|
+
id-token: write
|
|
30
|
+
steps:
|
|
31
|
+
- uses: actions/download-artifact@v4
|
|
32
|
+
with:
|
|
33
|
+
name: dist
|
|
34
|
+
path: dist/
|
|
35
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
name: test
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
pull_request:
|
|
6
|
+
|
|
7
|
+
permissions:
|
|
8
|
+
contents: read
|
|
9
|
+
|
|
10
|
+
jobs:
|
|
11
|
+
pytest:
|
|
12
|
+
runs-on: ubuntu-latest
|
|
13
|
+
strategy:
|
|
14
|
+
fail-fast: false
|
|
15
|
+
matrix:
|
|
16
|
+
python-version: ["3.10", "3.12"]
|
|
17
|
+
steps:
|
|
18
|
+
- uses: actions/checkout@v4
|
|
19
|
+
- uses: actions/setup-python@v5
|
|
20
|
+
with:
|
|
21
|
+
python-version: ${{ matrix.python-version }}
|
|
22
|
+
- run: python -m pip install -e ".[dev]"
|
|
23
|
+
- run: python -m pytest -m "not live"
|
sarnai-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[codz]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# C extensions
|
|
7
|
+
*.so
|
|
8
|
+
|
|
9
|
+
# Distribution / packaging
|
|
10
|
+
.Python
|
|
11
|
+
build/
|
|
12
|
+
develop-eggs/
|
|
13
|
+
dist/
|
|
14
|
+
downloads/
|
|
15
|
+
eggs/
|
|
16
|
+
.eggs/
|
|
17
|
+
lib/
|
|
18
|
+
lib64/
|
|
19
|
+
parts/
|
|
20
|
+
sdist/
|
|
21
|
+
var/
|
|
22
|
+
wheels/
|
|
23
|
+
share/python-wheels/
|
|
24
|
+
*.egg-info/
|
|
25
|
+
.installed.cfg
|
|
26
|
+
*.egg
|
|
27
|
+
MANIFEST
|
|
28
|
+
|
|
29
|
+
# PyInstaller
|
|
30
|
+
# Usually these files are written by a python script from a template
|
|
31
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
32
|
+
*.manifest
|
|
33
|
+
*.spec
|
|
34
|
+
|
|
35
|
+
# Installer logs
|
|
36
|
+
pip-log.txt
|
|
37
|
+
pip-delete-this-directory.txt
|
|
38
|
+
|
|
39
|
+
# Unit test / coverage reports
|
|
40
|
+
htmlcov/
|
|
41
|
+
.tox/
|
|
42
|
+
.nox/
|
|
43
|
+
.coverage
|
|
44
|
+
.coverage.*
|
|
45
|
+
.cache
|
|
46
|
+
nosetests.xml
|
|
47
|
+
coverage.xml
|
|
48
|
+
*.cover
|
|
49
|
+
*.py.cover
|
|
50
|
+
*.lcov
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
cover/
|
|
54
|
+
|
|
55
|
+
# Translations
|
|
56
|
+
*.mo
|
|
57
|
+
*.pot
|
|
58
|
+
|
|
59
|
+
# Django stuff:
|
|
60
|
+
*.log
|
|
61
|
+
local_settings.py
|
|
62
|
+
db.sqlite3
|
|
63
|
+
db.sqlite3-journal
|
|
64
|
+
|
|
65
|
+
# Flask stuff:
|
|
66
|
+
instance/
|
|
67
|
+
.webassets-cache
|
|
68
|
+
|
|
69
|
+
# Scrapy stuff:
|
|
70
|
+
.scrapy
|
|
71
|
+
|
|
72
|
+
# Sphinx documentation
|
|
73
|
+
docs/_build/
|
|
74
|
+
|
|
75
|
+
# PyBuilder
|
|
76
|
+
.pybuilder/
|
|
77
|
+
target/
|
|
78
|
+
|
|
79
|
+
# Jupyter Notebook
|
|
80
|
+
.ipynb_checkpoints
|
|
81
|
+
|
|
82
|
+
# IPython
|
|
83
|
+
profile_default/
|
|
84
|
+
ipython_config.py
|
|
85
|
+
|
|
86
|
+
# pyenv
|
|
87
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
88
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
89
|
+
# .python-version
|
|
90
|
+
|
|
91
|
+
# pipenv
|
|
92
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
93
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
94
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
95
|
+
# install all needed dependencies.
|
|
96
|
+
# Pipfile.lock
|
|
97
|
+
|
|
98
|
+
# uv
|
|
99
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
100
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
101
|
+
# commonly ignored for libraries.
|
|
102
|
+
# uv.lock
|
|
103
|
+
|
|
104
|
+
# poetry
|
|
105
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
106
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
107
|
+
# commonly ignored for libraries.
|
|
108
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
109
|
+
# poetry.lock
|
|
110
|
+
# poetry.toml
|
|
111
|
+
|
|
112
|
+
# pdm
|
|
113
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
114
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
115
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
116
|
+
# pdm.lock
|
|
117
|
+
# pdm.toml
|
|
118
|
+
.pdm-python
|
|
119
|
+
.pdm-build/
|
|
120
|
+
|
|
121
|
+
# pixi
|
|
122
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
123
|
+
# pixi.lock
|
|
124
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
125
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
126
|
+
.pixi/*
|
|
127
|
+
!.pixi/config.toml
|
|
128
|
+
|
|
129
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
130
|
+
__pypackages__/
|
|
131
|
+
|
|
132
|
+
# Celery stuff
|
|
133
|
+
celerybeat-schedule*
|
|
134
|
+
celerybeat.pid
|
|
135
|
+
|
|
136
|
+
# Redis
|
|
137
|
+
*.rdb
|
|
138
|
+
*.aof
|
|
139
|
+
*.pid
|
|
140
|
+
|
|
141
|
+
# RabbitMQ
|
|
142
|
+
mnesia/
|
|
143
|
+
rabbitmq/
|
|
144
|
+
rabbitmq-data/
|
|
145
|
+
|
|
146
|
+
# ActiveMQ
|
|
147
|
+
activemq-data/
|
|
148
|
+
|
|
149
|
+
# SageMath parsed files
|
|
150
|
+
*.sage.py
|
|
151
|
+
|
|
152
|
+
# Environments
|
|
153
|
+
.env
|
|
154
|
+
.envrc
|
|
155
|
+
.venv
|
|
156
|
+
env/
|
|
157
|
+
venv/
|
|
158
|
+
ENV/
|
|
159
|
+
env.bak/
|
|
160
|
+
venv.bak/
|
|
161
|
+
|
|
162
|
+
# Spyder project settings
|
|
163
|
+
.spyderproject
|
|
164
|
+
.spyproject
|
|
165
|
+
|
|
166
|
+
# Rope project settings
|
|
167
|
+
.ropeproject
|
|
168
|
+
|
|
169
|
+
# mkdocs/Zensical documentation
|
|
170
|
+
/site
|
|
171
|
+
|
|
172
|
+
# mypy
|
|
173
|
+
.mypy_cache/
|
|
174
|
+
.dmypy.json
|
|
175
|
+
dmypy.json
|
|
176
|
+
|
|
177
|
+
# Pyre type checker
|
|
178
|
+
.pyre/
|
|
179
|
+
|
|
180
|
+
# pytype static type analyzer
|
|
181
|
+
.pytype/
|
|
182
|
+
|
|
183
|
+
# Cython debug symbols
|
|
184
|
+
cython_debug/
|
|
185
|
+
|
|
186
|
+
# PyCharm
|
|
187
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
188
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
189
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
190
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
191
|
+
# .idea/
|
|
192
|
+
|
|
193
|
+
# Abstra
|
|
194
|
+
# Abstra is an AI-powered process automation framework.
|
|
195
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
196
|
+
# Learn more at https://abstra.io/docs
|
|
197
|
+
.abstra/
|
|
198
|
+
|
|
199
|
+
# Visual Studio Code
|
|
200
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
|
|
201
|
+
# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
202
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer, you
|
|
203
|
+
# could uncomment the following to ignore the entire vscode folder
|
|
204
|
+
# .vscode/
|
|
205
|
+
# Temporary file for partial code execution
|
|
206
|
+
tempCodeRunnerFile.py
|
|
207
|
+
|
|
208
|
+
# Ruff stuff:
|
|
209
|
+
.ruff_cache/
|
|
210
|
+
|
|
211
|
+
# PyPI configuration file
|
|
212
|
+
.pypirc
|
|
213
|
+
|
|
214
|
+
# Marimo
|
|
215
|
+
marimo/_static/
|
|
216
|
+
marimo/_lsp/
|
|
217
|
+
__marimo__/
|
|
218
|
+
|
|
219
|
+
# Streamlit
|
|
220
|
+
.streamlit/secrets.toml
|
sarnai-0.1.0/CLAUDE.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
Project: the official SarnAI Python package, published to PyPI as `sarnai`.
|
|
4
|
+
The brand is always written "SarnAI"; code names (package, modules, functions) are lowercase.
|
|
5
|
+
|
|
6
|
+
## Prompt rules
|
|
7
|
+
|
|
8
|
+
- One goal per prompt. Do that goal, then report and stop.
|
|
9
|
+
- The user approves every push. Commit locally on a branch; never push without explicit approval.
|
|
10
|
+
- No secrets in chat. Never ask for, print, or commit API keys or tokens; read them from the environment.
|
|
11
|
+
- Give results in copy-paste format: plain text or commands in fenced code blocks.
|
|
12
|
+
|
|
13
|
+
## API sources
|
|
14
|
+
|
|
15
|
+
Learn the public SarnAI APIs only from:
|
|
16
|
+
|
|
17
|
+
- https://board.sarnai.dev/llms.txt
|
|
18
|
+
- https://verify.sarnai.dev/llms.txt
|
|
19
|
+
|
|
20
|
+
Do not read other repos to infer API behavior, and do not guess endpoints.
|
sarnai-0.1.0/LICENSE
ADDED
|
@@ -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.
|
sarnai-0.1.0/PKG-INFO
ADDED
|
@@ -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
|
sarnai-0.1.0/README.md
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# sarnai
|
|
2
|
+
|
|
3
|
+
Official SarnAI Python package: find agent services on the
|
|
4
|
+
[Agent Discovery Board](https://board.sarnai.dev) and verify agent output with the
|
|
5
|
+
[Agent Output Verifier](https://verify.sarnai.dev). No account or secrets needed.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
pip install sarnai # client only (httpx)
|
|
9
|
+
pip install sarnai[langchain] # + LangChain tools
|
|
10
|
+
pip install sarnai[crewai] # + CrewAI tools
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## LangChain in 10 lines
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from langchain.agents import create_agent
|
|
17
|
+
from sarnai.langchain import find_service, verify_output
|
|
18
|
+
|
|
19
|
+
agent = create_agent("anthropic:claude-sonnet-5-5", tools=[find_service, verify_output])
|
|
20
|
+
reply = agent.invoke({"messages": [
|
|
21
|
+
{"role": "user", "content": "Find a service that extracts invoice data, "
|
|
22
|
+
"then check this output against {\"type\":\"object\",\"required\":[\"total\"]}: {\"total\": 42}"}]})
|
|
23
|
+
print(reply["messages"][-1].content)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
CrewAI: `from sarnai.crewai import find_service, verify_output`.
|
|
27
|
+
|
|
28
|
+
## Client
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from sarnai import SarnAIClient
|
|
32
|
+
|
|
33
|
+
with SarnAIClient() as sarnai:
|
|
34
|
+
page = sarnai.search_listings("invoice extraction", limit=5) # GET /listings
|
|
35
|
+
listing = sarnai.get_listing(page["listings"][0]["id"]) # GET /listings/{id}
|
|
36
|
+
result = sarnai.verify_output( # POST /verify/schema
|
|
37
|
+
{"type": "object", "required": ["total"]}, {"total": 42})
|
|
38
|
+
print(result.passed, result.hints)
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Verification is free during launch (daily allowance per caller, see the
|
|
42
|
+
[verifier docs](https://verify.sarnai.dev/llms.txt)); beyond it the service answers 402 and the
|
|
43
|
+
client raises `PaymentRequiredError`. Errors raise `SarnAIError` with `status` and `code`.
|
|
44
|
+
|
|
45
|
+
## Tests
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
pytest # everything, including live calls to the SarnAI services
|
|
49
|
+
pytest -m "not live" # offline only
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## License
|
|
53
|
+
|
|
54
|
+
MIT
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sarnai"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Official SarnAI Python package: find agent services on the Agent Discovery Board and verify agent output."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
dependencies = ["httpx>=0.27"]
|
|
14
|
+
keywords = ["sarnai", "agents", "ai-agents", "verification", "x402", "langchain", "crewai"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"License :: OSI Approved :: MIT License",
|
|
19
|
+
"Programming Language :: Python :: 3",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[tool.hatch.version]
|
|
24
|
+
path = "src/sarnai/_version.py"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
langchain = ["langchain-core>=0.3"]
|
|
28
|
+
crewai = ["crewai>=0.100"]
|
|
29
|
+
dev = ["pytest>=8", "langchain-core>=0.3"]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://github.com/sarnai-dev/sarnai-python"
|
|
33
|
+
Board = "https://board.sarnai.dev"
|
|
34
|
+
Verifier = "https://verify.sarnai.dev"
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.wheel]
|
|
37
|
+
packages = ["src/sarnai"]
|
|
38
|
+
|
|
39
|
+
[tool.pytest.ini_options]
|
|
40
|
+
testpaths = ["tests"]
|
|
41
|
+
markers = ["live: calls the live SarnAI services (skip with: pytest -m 'not live')"]
|
|
@@ -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__"]
|
|
@@ -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
|
+
})
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -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)
|
|
@@ -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"]
|
|
@@ -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"]
|
|
File without changes
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Tests against the live SarnAI services. Skip with: pytest -m "not live"."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from sarnai import SarnAIClient, SarnAIError
|
|
8
|
+
|
|
9
|
+
pytestmark = pytest.mark.live
|
|
10
|
+
|
|
11
|
+
SCHEMA = {"type": "object", "required": ["total"], "properties": {"total": {"type": "number"}}}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.fixture
|
|
15
|
+
def client():
|
|
16
|
+
with SarnAIClient() as c:
|
|
17
|
+
yield c
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def test_search_and_get_listing(client):
|
|
21
|
+
page = client.search_listings("verify", limit=2)
|
|
22
|
+
assert page["listings"] and "next_cursor" in page
|
|
23
|
+
listing = client.get_listing(page["listings"][0]["id"])
|
|
24
|
+
assert listing["id"] == page["listings"][0]["id"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_get_missing_listing(client):
|
|
28
|
+
with pytest.raises(SarnAIError) as info:
|
|
29
|
+
client.get_listing("00000000-0000-0000-0000-000000000000")
|
|
30
|
+
assert info.value.status in (404, 422)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_verify_pass_and_fail(client):
|
|
34
|
+
# agent_id with the reserved 'test-' prefix is never recorded.
|
|
35
|
+
ok = client.verify_output(SCHEMA, {"total": 3}, agent_id="test-sarnai-python")
|
|
36
|
+
bad = client.verify_output(SCHEMA, {"total": "x"}, agent_id="test-sarnai-python")
|
|
37
|
+
assert ok.passed and not bad.passed
|
|
38
|
+
assert bad.attestation["algorithm"] == "Ed25519"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_tools_end_to_end():
|
|
42
|
+
from sarnai import _tools
|
|
43
|
+
|
|
44
|
+
found = json.loads(_tools.find_service("verification", 2))
|
|
45
|
+
assert found["listings"]
|
|
46
|
+
res = json.loads(_tools.verify_output(SCHEMA, {"total": 1}))
|
|
47
|
+
assert res["result"] == "pass"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_compact_detail(client):
|
|
51
|
+
res = client.verify_output(SCHEMA, {"total": "x"}, agent_id="test-sarnai-python",
|
|
52
|
+
compact=True)
|
|
53
|
+
assert not res.passed and "errors" not in res.raw
|
|
54
|
+
assert res.attestation["algorithm"] == "Ed25519"
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from sarnai import PaymentRequiredError, SarnAIClient, SarnAIError
|
|
7
|
+
from sarnai import _tools
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_client(handler):
|
|
11
|
+
return SarnAIClient(transport=httpx.MockTransport(handler))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_search_builds_query():
|
|
15
|
+
seen = {}
|
|
16
|
+
|
|
17
|
+
def handler(request):
|
|
18
|
+
seen["url"] = request.url
|
|
19
|
+
return httpx.Response(200, json={"listings": [], "total": 0})
|
|
20
|
+
|
|
21
|
+
make_client(handler).search_listings("invoice", task_category=["a", "b"], limit=3)
|
|
22
|
+
assert seen["url"].path == "/listings"
|
|
23
|
+
assert seen["url"].params["q"] == "invoice"
|
|
24
|
+
assert seen["url"].params.get_list("task_category") == ["a", "b"]
|
|
25
|
+
assert seen["url"].params["limit"] == "3"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def test_board_error_code():
|
|
29
|
+
client = make_client(lambda r: httpx.Response(
|
|
30
|
+
404, json={"error_code": "not_found", "message": "No such listing"}))
|
|
31
|
+
with pytest.raises(SarnAIError) as info:
|
|
32
|
+
client.get_listing("x")
|
|
33
|
+
assert info.value.code == "not_found" and info.value.status == 404
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_verify_402_and_body():
|
|
37
|
+
seen = {}
|
|
38
|
+
|
|
39
|
+
def handler(request):
|
|
40
|
+
seen["body"] = json.loads(request.content)
|
|
41
|
+
return httpx.Response(402, json={"error_code": "no_payment", "message": "pay"})
|
|
42
|
+
|
|
43
|
+
with pytest.raises(PaymentRequiredError):
|
|
44
|
+
make_client(handler).verify_output({"type": "object"}, None, compact=True)
|
|
45
|
+
assert "submitted_output" in seen["body"] and seen["body"]["detail"] == "compact"
|
|
46
|
+
assert seen["body"]["task_id"]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def test_verify_result():
|
|
50
|
+
client = make_client(lambda r: httpx.Response(200, json={
|
|
51
|
+
"result": "pass", "verification_id": "v", "task_id": "t"}))
|
|
52
|
+
assert client.verify_output({"type": "object"}, {}).passed
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_tool_helpers_accept_json_strings():
|
|
56
|
+
def handler(request):
|
|
57
|
+
return httpx.Response(200, json={"result": "fail", "verification_id": "v",
|
|
58
|
+
"task_id": "t", "errors": ["e"], "hints": []})
|
|
59
|
+
|
|
60
|
+
out = json.loads(_tools.verify_output('{"type": "object"}', '{"a": 1}',
|
|
61
|
+
client=make_client(handler)))
|
|
62
|
+
assert out["result"] == "fail" and out["errors"] == ["e"]
|
|
63
|
+
assert "error" in json.loads(_tools.verify_output("nope", {}))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_langchain_tool_names():
|
|
67
|
+
pytest.importorskip("langchain_core")
|
|
68
|
+
from sarnai.langchain import tools
|
|
69
|
+
|
|
70
|
+
assert [t.name for t in tools] == ["find_service", "verify_output"]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def test_user_agent_on_every_request():
|
|
74
|
+
import sarnai
|
|
75
|
+
|
|
76
|
+
agents = []
|
|
77
|
+
|
|
78
|
+
def handler(request):
|
|
79
|
+
agents.append(request.headers["user-agent"])
|
|
80
|
+
return httpx.Response(200, json={"result": "pass"})
|
|
81
|
+
|
|
82
|
+
client = make_client(handler)
|
|
83
|
+
client.search_listings("x")
|
|
84
|
+
client.get_listing("id")
|
|
85
|
+
client.verify_output({"type": "object"}, {})
|
|
86
|
+
client.reputation("agent")
|
|
87
|
+
assert agents == [f"sarnai-python/{sarnai.__version__}"] * 4
|