shinapi 0.1.1__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
+ __pycache__/
2
+ .venv/
3
+ dist/
shinapi-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ShinAPI
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.
shinapi-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.5
2
+ Name: shinapi
3
+ Version: 0.1.1
4
+ Summary: Search what high-authority Japanese sites say now. The Python client of ShinAPI.
5
+ Project-URL: Homepage, https://shinapi.com
6
+ Project-URL: Documentation, https://docs.shinapi.com
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: agents,japan,japanese,llm,rag,search
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+
13
+ # shinapi
14
+
15
+ Search what high-authority Japanese sites say now. The Python client of [ShinAPI](https://shinapi.com).
16
+
17
+ ```sh
18
+ pip install shinapi
19
+ ```
20
+
21
+ ```python
22
+ from shinapi import ShinAPI
23
+
24
+ shinapi = ShinAPI()
25
+ answer = shinapi.search("2026年の年収の壁はいくらですか")
26
+
27
+ if answer["outcome"] == "answered":
28
+ for passage in answer["results"]:
29
+ print(passage["url"], passage["text"])
30
+ ```
31
+
32
+ Get a key in the [console](https://console.shinapi.com), and read the [docs](https://docs.shinapi.com).
@@ -0,0 +1,20 @@
1
+ # shinapi
2
+
3
+ Search what high-authority Japanese sites say now. The Python client of [ShinAPI](https://shinapi.com).
4
+
5
+ ```sh
6
+ pip install shinapi
7
+ ```
8
+
9
+ ```python
10
+ from shinapi import ShinAPI
11
+
12
+ shinapi = ShinAPI()
13
+ answer = shinapi.search("2026年の年収の壁はいくらですか")
14
+
15
+ if answer["outcome"] == "answered":
16
+ for passage in answer["results"]:
17
+ print(passage["url"], passage["text"])
18
+ ```
19
+
20
+ Get a key in the [console](https://console.shinapi.com), and read the [docs](https://docs.shinapi.com).
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "shinapi"
7
+ version = "0.1.1"
8
+ description = "Search what high-authority Japanese sites say now. The Python client of ShinAPI."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ keywords = ["search", "japan", "japanese", "llm", "rag", "agents"]
13
+
14
+ [project.urls]
15
+ Homepage = "https://shinapi.com"
16
+ Documentation = "https://docs.shinapi.com"
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["shinapi"]
20
+
21
+ [tool.hatch.build.targets.sdist]
22
+ only-include = ["shinapi", "README.md", "LICENSE"]
@@ -0,0 +1,212 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import time
6
+ from typing import Any, Callable, Literal, Optional, Sequence, TypedDict
7
+ from urllib.error import HTTPError
8
+ from urllib.request import Request, urlopen
9
+
10
+ __all__ = [
11
+ "SEARCH_DESCRIPTION",
12
+ "SEARCH_INPUT",
13
+ "ErrorCode",
14
+ "Licence",
15
+ "Outcome",
16
+ "SearchResponse",
17
+ "SearchResult",
18
+ "ShinAPI",
19
+ "ShinAPIError",
20
+ ]
21
+
22
+ Outcome = Literal["answered", "no_match_in_scope", "out_of_scope"]
23
+
24
+ Licence = Literal["pdl-1.0", "gjstu-2.0", "cc-by-4.0", "cc0-1.0", "publisher-terms"]
25
+
26
+ ErrorCode = Literal[
27
+ "invalid_request",
28
+ "unauthorized",
29
+ "payment_required",
30
+ "forbidden",
31
+ "rate_limited",
32
+ "not_found",
33
+ "internal",
34
+ "unavailable",
35
+ ]
36
+
37
+ SEARCH_DESCRIPTION = " ".join(
38
+ [
39
+ "Search what high-authority Japanese sites say now, and get the passages as published, with the publisher, the URL,",
40
+ "the dates and the credit line to show. Only pages written in Japanese are indexed, so ask in Japanese, translating",
41
+ "a question asked in another language first.",
42
+ "The outcome is answered, no_match_in_scope (the index holds the words but no passage answers) or out_of_scope (the",
43
+ "index holds nothing on it, so ask a general search instead). When incomplete is true, ask again before concluding.",
44
+ ]
45
+ )
46
+
47
+ SEARCH_INPUT: dict[str, Any] = {
48
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
49
+ "type": "object",
50
+ "properties": {
51
+ "query": {
52
+ "type": "string",
53
+ "minLength": 1,
54
+ "maxLength": 512,
55
+ "description": "The question or keywords, in Japanese.",
56
+ },
57
+ "max_results": {
58
+ "default": 8,
59
+ "description": "The most passages to return.",
60
+ "type": "integer",
61
+ "minimum": 1,
62
+ "maximum": 32,
63
+ },
64
+ "exclude_domains": {
65
+ "default": [],
66
+ "description": "Sites to leave out, each a host such as example.co.jp: "
67
+ "no passage of that host or of a host under it is returned.",
68
+ "maxItems": 64,
69
+ "type": "array",
70
+ "items": {
71
+ "type": "string",
72
+ "minLength": 1,
73
+ "maxLength": 256,
74
+ "pattern": "^[^/?#@:\\s]+$",
75
+ },
76
+ },
77
+ "exclude_text": {
78
+ "default": [],
79
+ "description": "Phrases to leave out: no passage whose title or text holds one is returned, "
80
+ "whatever its width or case.",
81
+ "maxItems": 8,
82
+ "type": "array",
83
+ "items": {"type": "string", "minLength": 1, "maxLength": 64},
84
+ },
85
+ },
86
+ "required": ["query"],
87
+ }
88
+
89
+ BASE_URL = "https://api.shinapi.com"
90
+ TIMEOUT_S = 30.0
91
+ RETRIES = 2
92
+ WAIT_S = 0.5
93
+ WAIT_CEILING_S = 8.0
94
+ RETRIED = frozenset({429, 500, 503})
95
+
96
+
97
+ class SearchResult(TypedDict):
98
+ title: str
99
+ url: str
100
+ publisher: str
101
+ published_at: Optional[str]
102
+ author: Optional[str]
103
+ image: Optional[str]
104
+ favicon: Optional[str]
105
+ last_changed_at: str
106
+ licence: Licence
107
+ attribution: str
108
+ score: Optional[float]
109
+ text: str
110
+
111
+
112
+ class SearchResponse(TypedDict):
113
+ outcome: Outcome
114
+ incomplete: bool
115
+ results: list[SearchResult]
116
+ request_id: str
117
+
118
+
119
+ class ShinAPIError(Exception):
120
+ def __init__(
121
+ self, message: str, status: int, code: str, request_id: Optional[str] = None
122
+ ) -> None:
123
+ super().__init__(message)
124
+ self.status = status
125
+ self.code = code
126
+ self.request_id = request_id
127
+
128
+
129
+ def _json_in(text: bytes) -> Any:
130
+ try:
131
+ return json.loads(text)
132
+ except ValueError:
133
+ return None
134
+
135
+
136
+ def _waited_for(header: Optional[str], attempt: int) -> float:
137
+ try:
138
+ asked = float(header or 0)
139
+ except ValueError:
140
+ asked = 0.0
141
+ waited = asked if asked > 0 else WAIT_S * 2**attempt
142
+ return min(waited, WAIT_CEILING_S)
143
+
144
+
145
+ class ShinAPI:
146
+ def __init__(
147
+ self,
148
+ key: Optional[str] = None,
149
+ *,
150
+ base_url: str = BASE_URL,
151
+ timeout: float = TIMEOUT_S,
152
+ retries: int = RETRIES,
153
+ opener: Callable[..., Any] = urlopen,
154
+ sleep: Callable[[float], None] = time.sleep,
155
+ ) -> None:
156
+ held = key or os.environ.get("SHINAPI_KEY")
157
+ if not held:
158
+ raise ValueError("ShinAPI needs a key: pass key or set SHINAPI_KEY")
159
+ self._key = held
160
+ self._url = base_url.rstrip("/") + "/v1/search"
161
+ self._timeout = timeout
162
+ self._retries = retries
163
+ self._opener = opener
164
+ self._sleep = sleep
165
+
166
+ def search(
167
+ self,
168
+ query: str,
169
+ *,
170
+ max_results: Optional[int] = None,
171
+ exclude_domains: Optional[Sequence[str]] = None,
172
+ exclude_text: Optional[Sequence[str]] = None,
173
+ ) -> SearchResponse:
174
+ asked: dict[str, Any] = {"query": query}
175
+ if max_results is not None:
176
+ asked["max_results"] = max_results
177
+ if exclude_domains is not None:
178
+ asked["exclude_domains"] = list(exclude_domains)
179
+ if exclude_text is not None:
180
+ asked["exclude_text"] = list(exclude_text)
181
+ attempt = 0
182
+ while True:
183
+ request = Request(
184
+ self._url,
185
+ data=json.dumps(asked).encode(),
186
+ headers={
187
+ "Authorization": f"Bearer {self._key}",
188
+ "Content-Type": "application/json",
189
+ "User-Agent": "shinapi-python",
190
+ },
191
+ method="POST",
192
+ )
193
+ try:
194
+ with self._opener(request, timeout=self._timeout) as response:
195
+ status = response.status
196
+ answer = _json_in(response.read())
197
+ except HTTPError as error:
198
+ if error.code not in RETRIED or attempt >= self._retries:
199
+ body = _json_in(error.read())
200
+ said = body if isinstance(body, dict) else {}
201
+ raise ShinAPIError(
202
+ said.get("error") or f"ShinAPI answered {error.code}",
203
+ error.code,
204
+ said.get("code") or "unreadable",
205
+ said.get("request_id"),
206
+ ) from None
207
+ self._sleep(_waited_for(error.headers.get("Retry-After"), attempt))
208
+ attempt += 1
209
+ continue
210
+ if not isinstance(answer, dict):
211
+ raise ShinAPIError("ShinAPI's answer was not JSON", status, "unreadable")
212
+ return answer # type: ignore[return-value]
File without changes