hifay 1.0.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.
hifay/__init__.py ADDED
@@ -0,0 +1,39 @@
1
+ """
2
+ hifay - oficiálna knižnica pre HiFay AI.
3
+
4
+ import hifay
5
+
6
+ client = hifay.Client(api_key="hf-...")
7
+ print(client.chat("Aká je hlavná mesto Slovenska?"))
8
+
9
+ Rovnaká knižnica sa pripája buď na centrálny hosting (chat.hifay.co,
10
+ predvolené), alebo priamo na server konkrétnej firmy - stačí zadať jej
11
+ adresu ako base_url:
12
+
13
+ client = hifay.Client(api_key="hf-...", base_url="https://server-firmy.example:8080")
14
+
15
+ Kľúč (tvaru "hf-...") si každý používateľ vygeneruje sám v aplikácii,
16
+ v sekcii "Moje API kľúče".
17
+ """
18
+
19
+ from .client import (
20
+ Client,
21
+ HifayError,
22
+ AuthenticationError,
23
+ RateLimitError,
24
+ WrongServerError,
25
+ APIError,
26
+ TimeoutError,
27
+ )
28
+
29
+ __version__ = "1.0.0"
30
+ __all__ = [
31
+ "Client",
32
+ "HifayError",
33
+ "AuthenticationError",
34
+ "RateLimitError",
35
+ "WrongServerError",
36
+ "APIError",
37
+ "TimeoutError",
38
+ "__version__",
39
+ ]
hifay/client.py ADDED
@@ -0,0 +1,251 @@
1
+ """
2
+ Skutočný HTTP klient pre HiFay API (v1). Zámerne bez cudzích závislostí -
3
+ funguje s obyčajným "pip install hifay" kdekoľvek, kde beží Python 3.8+,
4
+ bez toho, aby si so sebou ťahal requests/httpx.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import urllib.error
11
+ import urllib.request
12
+ from typing import Any, Dict, List, Optional
13
+
14
+ DEFAULT_BASE_URL = "https://chat.hifay.co/api.php"
15
+ DEFAULT_TIMEOUT = 90.0
16
+
17
+
18
+ class HifayError(Exception):
19
+ """Základná chyba knižnice - všetky ostatné z nej dedia."""
20
+
21
+ def __init__(self, message: str, *, status: Optional[int] = None, type: Optional[str] = None):
22
+ super().__init__(message)
23
+ self.message = message
24
+ self.status = status
25
+ self.type = type
26
+
27
+
28
+ class AuthenticationError(HifayError):
29
+ """Kľúč chýba, je neplatný alebo bol zrušený."""
30
+
31
+
32
+ class RateLimitError(HifayError):
33
+ """Prekročený limit požiadaviek za minútu pre tento kľúč."""
34
+
35
+
36
+ class WrongServerError(HifayError):
37
+ """Kľúč patrí firme na vlastnom serveri - treba nastaviť base_url na jej adresu."""
38
+
39
+
40
+ class TimeoutError(HifayError):
41
+ """Server neodpovedal do timeoutu (dlhá odpoveď alebo preťaženie)."""
42
+
43
+
44
+ class APIError(HifayError):
45
+ """Iná chyba na strane servera."""
46
+
47
+
48
+ def _vyvolaj_chybu(status: int, telo: Dict[str, Any]) -> None:
49
+ chyba = telo.get("error")
50
+ if isinstance(chyba, dict):
51
+ sprava = chyba.get("message", "Neznáma chyba HiFay API.")
52
+ typ = chyba.get("type", "")
53
+ else:
54
+ sprava = str(chyba or "Neznáma chyba HiFay API.")
55
+ typ = ""
56
+
57
+ if status == 401 or typ == "authentication_error":
58
+ raise AuthenticationError(sprava, status=status, type=typ)
59
+ if status == 429 or typ == "rate_limit_error":
60
+ raise RateLimitError(sprava, status=status, type=typ)
61
+ if status == 504 or typ == "timeout_error":
62
+ raise TimeoutError(sprava, status=status, type=typ)
63
+ if typ == "wrong_server":
64
+ raise WrongServerError(sprava, status=status, type=typ)
65
+ raise APIError(sprava, status=status, type=typ)
66
+
67
+
68
+ class ChatCompletionMessage:
69
+ """Napodobňuje tvar, na aký sú vývojári zvyknutí z iných AI knižníc."""
70
+
71
+ def __init__(self, role: str, content: str):
72
+ self.role = role
73
+ self.content = content
74
+
75
+ def __repr__(self) -> str:
76
+ return f"ChatCompletionMessage(role={self.role!r}, content={self.content!r})"
77
+
78
+
79
+ class ChatCompletionChoice:
80
+ def __init__(self, index: int, message: ChatCompletionMessage, finish_reason: str):
81
+ self.index = index
82
+ self.message = message
83
+ self.finish_reason = finish_reason
84
+
85
+
86
+ class ChatCompletion:
87
+ """Výsledok client.chat.completions.create(...) - aj ako objekt (.choices[0].message.content),
88
+ aj ako obyčajný dict (self.raw / rozbaľovanie ako slovník)."""
89
+
90
+ def __init__(self, data: Dict[str, Any]):
91
+ self.raw = data
92
+ self.id = data.get("id", "")
93
+ self.model = data.get("model", "hifay")
94
+ self.created = data.get("created", 0)
95
+ self.choices = [
96
+ ChatCompletionChoice(
97
+ c.get("index", 0),
98
+ ChatCompletionMessage(
99
+ c.get("message", {}).get("role", "assistant"),
100
+ c.get("message", {}).get("content", ""),
101
+ ),
102
+ c.get("finish_reason", "stop"),
103
+ )
104
+ for c in data.get("choices", [])
105
+ ]
106
+
107
+ @property
108
+ def text(self) -> str:
109
+ """Skratka pre najčastejší prípad - len text odpovede."""
110
+ return self.choices[0].message.content if self.choices else self.raw.get("response", "")
111
+
112
+ def __repr__(self) -> str:
113
+ return f"ChatCompletion(text={self.text!r})"
114
+
115
+
116
+ class _CompletionsResource:
117
+ def __init__(self, client: "Client"):
118
+ self._client = client
119
+
120
+ def create(
121
+ self,
122
+ messages: Optional[List[Dict[str, str]]] = None,
123
+ *,
124
+ prompt: Optional[str] = None,
125
+ system: str = "",
126
+ remember: bool = False,
127
+ chat_id: Optional[str] = None,
128
+ language: str = "sk",
129
+ ) -> ChatCompletion:
130
+ telo: Dict[str, Any] = {"system": system, "pamatatSi": remember, "jazyk": language}
131
+ if chat_id:
132
+ telo["cet_id"] = chat_id
133
+ if messages is not None:
134
+ telo["messages"] = messages
135
+ else:
136
+ telo["prompt"] = prompt or ""
137
+ data = self._client._poziadavka("v1_chat", telo)
138
+ return ChatCompletion(data)
139
+
140
+
141
+ class _ChatResource:
142
+ """client.chat("otázka") je najkratšia cesta; client.chat.completions.create(...)
143
+ je tvar, na aký sú zvyknutí ľudia z iných AI knižníc."""
144
+
145
+ def __init__(self, client: "Client"):
146
+ self._client = client
147
+ self.completions = _CompletionsResource(client)
148
+
149
+ def __call__(
150
+ self,
151
+ prompt: str,
152
+ *,
153
+ system: str = "",
154
+ remember: bool = False,
155
+ chat_id: Optional[str] = None,
156
+ language: str = "sk",
157
+ ) -> str:
158
+ vysledok = self.completions.create(
159
+ prompt=prompt, system=system, remember=remember, chat_id=chat_id, language=language
160
+ )
161
+ return vysledok.text
162
+
163
+
164
+ class Client:
165
+ """
166
+ Hlavná trieda knižnice.
167
+
168
+ client = hifay.Client(api_key="hf-...")
169
+ odpoved = client.chat("Aká je zmluvná pokuta za omeškanie?")
170
+
171
+ Parametre:
172
+ api_key: kľúč vygenerovaný v aplikácii ("Moje API kľúče"), tvaru "hf-...".
173
+ base_url: kam sa má knižnica pripájať.
174
+ - vynechajte pre bežný účet -> centrálny hosting HiFay (chat.hifay.co)
175
+ - zadajte adresu servera firmy (napr. "https://ai.firma.sk" alebo
176
+ "http://192.168.1.50:8080") pre firmu, ktorá beží na VLASTNOM
177
+ serveri - vtedy ide všetka komunikácia priamo tam, nie cez
178
+ chat.hifay.co (presne podľa toho, ako firma AI prevádzkuje).
179
+ timeout: najdlhší čas čakania na odpoveď, v sekundách (predvolené 90).
180
+ """
181
+
182
+ def __init__(
183
+ self,
184
+ api_key: str,
185
+ base_url: Optional[str] = None,
186
+ timeout: float = DEFAULT_TIMEOUT,
187
+ ):
188
+ if not api_key or not isinstance(api_key, str):
189
+ raise AuthenticationError("Chýba api_key. Vygenerujte si ho v aplikácii, v sekcii \"Moje API kľúče\".")
190
+
191
+ adresa = (base_url or DEFAULT_BASE_URL).rstrip("/")
192
+ self.api_key = api_key
193
+ self.base_url = adresa
194
+ self.timeout = timeout
195
+ self.chat = _ChatResource(self)
196
+
197
+ # ------------------------------------------------------------------
198
+
199
+ def models(self) -> List[Dict[str, Any]]:
200
+ """Zoznam dostupných modelov (v HiFay je zatiaľ jeden spoločný - "hifay")."""
201
+ data = self._poziadavka("v1_models", None, method="GET")
202
+ return data.get("data", [])
203
+
204
+ # ------------------------------------------------------------------
205
+
206
+ def _plna_adresa(self, akcia: str) -> str:
207
+ if self.base_url.endswith(".php"):
208
+ spojka = "&" if "?" in self.base_url else "?"
209
+ return f"{self.base_url}{spojka}action={akcia}"
210
+ # Firemný server: http://adresa:port/?action=...
211
+ spojka = "&" if "?" in self.base_url else "/?"
212
+ return f"{self.base_url}{spojka}action={akcia}"
213
+
214
+ def _poziadavka(self, akcia: str, telo: Optional[Dict[str, Any]], method: str = "POST") -> Dict[str, Any]:
215
+ url = self._plna_adresa(akcia)
216
+ data = json.dumps(telo).encode("utf-8") if telo is not None else None
217
+ hlavicky = {
218
+ "Authorization": f"Bearer {self.api_key}",
219
+ "Content-Type": "application/json",
220
+ "User-Agent": "hifay-python/1.0",
221
+ }
222
+ req = urllib.request.Request(url, data=data, headers=hlavicky, method=method if data is None else "POST")
223
+
224
+ try:
225
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
226
+ surove = resp.read()
227
+ status = resp.status
228
+ except urllib.error.HTTPError as e:
229
+ surove = e.read()
230
+ status = e.code
231
+ except urllib.error.URLError as e:
232
+ # "timed out" prichádza, keď server neodpovie do self.timeout -
233
+ # to je vecne iná chyba (skúsiť znova) ako nedostupný server.
234
+ if "timed out" in str(e.reason).lower():
235
+ raise TimeoutError(f"Server neodpovedal do {self.timeout}s.")
236
+ raise APIError(f"Server sa nepodarilo dosiahnuť ({self.base_url}): {e.reason}")
237
+ except Exception:
238
+ raise TimeoutError(f"Server neodpovedal do {self.timeout}s.")
239
+
240
+ try:
241
+ telo_odpovede = json.loads(surove.decode("utf-8")) if surove else {}
242
+ except Exception:
243
+ raise APIError(f"Server vrátil neplatnú odpoveď (stav {status}).", status=status)
244
+
245
+ if status >= 400 or "error" in telo_odpovede:
246
+ _vyvolaj_chybu(status, telo_odpovede)
247
+
248
+ return telo_odpovede
249
+
250
+ def __repr__(self) -> str:
251
+ return f"hifay.Client(base_url={self.base_url!r})"
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.4
2
+ Name: hifay
3
+ Version: 1.0.0
4
+ Summary: Oficiálna Python knižnica pre HiFay AI (chat.hifay.co aj firemné on-premise servery)
5
+ Author: HiFay / Vestral
6
+ License: Proprietary
7
+ Project-URL: Homepage, https://chat.hifay.co
8
+ Keywords: hifay,ai,chat,llm
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+
12
+ # hifay
13
+
14
+ Oficiálna Python knižnica pre HiFay AI. Žiadne cudzie závislosti - funguje
15
+ všade, kde beží Python 3.8+.
16
+
17
+ ## Inštalácia
18
+
19
+ ```bash
20
+ pip install hifay
21
+ ```
22
+
23
+ (alebo lokálne, priamo z tohto priečinka: `pip install -e .`)
24
+
25
+ ## API kľúč
26
+
27
+ Kľúč (tvaru `hf-...`) si vygenerujete v aplikácii, v sekcii **Moje API kľúče**.
28
+ Zobrazí sa len raz - hneď po vytvorení si ho uložte.
29
+
30
+ ## Použitie - bežný účet (centrálny hosting HiFay)
31
+
32
+ ```python
33
+ import hifay
34
+
35
+ client = hifay.Client(api_key="hf-...")
36
+ print(client.chat("Aká je hlavná mesto Slovenska?"))
37
+ ```
38
+
39
+ ## Použitie - firma na vlastnom serveri
40
+
41
+ Ak firma prevádzkuje HiFay na **vlastnom serveri** (nie cez chat.hifay.co),
42
+ knižnica sa musí pripájať priamo tam - inak sa k firemným dátam
43
+ z centrálneho servera vôbec nedostane (a ani nemá, z bezpečnostných dôvodov).
44
+ Stačí zadať adresu servera firmy:
45
+
46
+ ```python
47
+ import hifay
48
+
49
+ client = hifay.Client(
50
+ api_key="hf-...",
51
+ base_url="https://server-firmy.example:8080", # alebo http://192.168.1.50:8080
52
+ )
53
+ print(client.chat("Aká je zmluvná pokuta za omeškanie dodávky?"))
54
+ ```
55
+
56
+ Kľúč vygenerovaný na centrálnom hostingu funguje len tam; kľúč vygenerovaný
57
+ na serveri firmy funguje len na jej serveri - kľúče sa medzi sebou nemiešajú.
58
+
59
+ ## Ďalšie možnosti
60
+
61
+ ```python
62
+ # systémový pokyn, pamätanie kontextu, vlastné id konverzácie
63
+ client.chat(
64
+ "Zhrň mi túto zmluvu.",
65
+ system="Si právny asistent, odpovedaj stručne.",
66
+ remember=True,
67
+ chat_id="zmluva-2026-09",
68
+ )
69
+
70
+ # tvar bližší iným AI knižniciam (napr. OpenAI)
71
+ odpoved = client.chat.completions.create(
72
+ messages=[{"role": "user", "content": "Ahoj!"}]
73
+ )
74
+ print(odpoved.text) # skratka
75
+ print(odpoved.choices[0].message.content) # plný tvar
76
+
77
+ # zoznam modelov
78
+ client.models()
79
+ ```
80
+
81
+ ## Chyby
82
+
83
+ ```python
84
+ from hifay import AuthenticationError, RateLimitError, WrongServerError, APIError
85
+
86
+ try:
87
+ client.chat("...")
88
+ except AuthenticationError:
89
+ print("Neplatný alebo zrušený kľúč.")
90
+ except RateLimitError:
91
+ print("Príliš veľa požiadaviek za minútu.")
92
+ except WrongServerError:
93
+ print("Tento kľúč patrí firme na vlastnom serveri - nastavte base_url.")
94
+ except APIError as e:
95
+ print("Chyba servera:", e.message)
96
+ ```
@@ -0,0 +1,6 @@
1
+ hifay/__init__.py,sha256=dmsg37Scdo26kwZ0YFaan6hyqo4inEdh0ZbI8cQWwYM,896
2
+ hifay/client.py,sha256=alQro6p9U9KAJyfQbnLm1LhZgfnLmkBE5isQMNpVXWI,9066
3
+ hifay-1.0.0.dist-info/METADATA,sha256=oMmqBwObFY_CHT9s-bi4qJvemXA5dcubKL8UHsGec7M,2704
4
+ hifay-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ hifay-1.0.0.dist-info/top_level.txt,sha256=mXqkPP08-hEusTil5uUB17vQCGPFKdTfJNZfimxH_tc,6
6
+ hifay-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ hifay