klyuchora 0.2.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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Klyuchora
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.
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.4
2
+ Name: klyuchora
3
+ Version: 0.2.0
4
+ Summary: SDK Ключоры для Python: все модели, стриминг, лимиты ключей, баланс кабинета. Сайт: https://klyuchora.ru
5
+ Home-page: https://klyuchora.ru
6
+ Author: Klyuchora
7
+ License: MIT
8
+ Project-URL: Homepage, https://klyuchora.ru
9
+ Project-URL: Documentation, https://klyuchora.ru/sdk
10
+ Keywords: klyuchora,ключора,llm,api,sdk,ai
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # klyuchora
21
+
22
+ Официальный SDK сервиса [Ключора](https://klyuchora.ru) для Python. Без зависимостей, Python 3.8+.
23
+ Чат и стриминг, все типы моделей, список доступных моделей, лимиты ключа, баланс кабинета, оценка стоимости запроса, async и командная строка.
24
+
25
+ Сайт: https://klyuchora.ru · Документация: https://klyuchora.ru/sdk
26
+
27
+ ## Установка
28
+
29
+ pip install klyuchora
30
+
31
+ ## Быстрый старт
32
+
33
+ Ключ создаётся в кабинете на https://klyuchora.ru (раздел «Ключи API»). Положите его в переменную окружения `KLYUCHORA_API_KEY`.
34
+
35
+ ```python
36
+ from klyuchora import Klyuchora
37
+
38
+ client = Klyuchora() # ключ берётся из KLYUCHORA_API_KEY
39
+ reply = client.chat.completions.create(
40
+ model="gpt-4o-mini",
41
+ messages=[{"role": "user", "content": "Привет!"}],
42
+ )
43
+ print(reply.choices[0].message.content)
44
+
45
+ # стриминг
46
+ with client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Расскажи шутку"}], stream=True) as stream:
47
+ for text in stream.text_deltas():
48
+ print(text, end="", flush=True)
49
+
50
+ print(client.models.ids()) # модели, доступные вашему ключу
51
+ print(client.key.usage()) # лимиты и расход ключа
52
+ print(client.account.balance()) # баланс кабинета (нужен KLYUCHORA_ACCESS_TOKEN)
53
+ print(client.estimate_cost("gpt-4o-mini", input_tokens=1000, output_tokens=500))
54
+ ```
55
+
56
+ Асинхронный клиент: `AsyncKlyuchora`. Командная строка:
57
+ `klyuchora models | price МОДЕЛЬ | usage | balance | keys | rate | chat МОДЕЛЬ "текст"`.
58
+
59
+ Полная документация с примерами для всех методов: https://klyuchora.ru/sdk
60
+
61
+ ## Лицензия
62
+
63
+ MIT
@@ -0,0 +1,44 @@
1
+ # klyuchora
2
+
3
+ Официальный SDK сервиса [Ключора](https://klyuchora.ru) для Python. Без зависимостей, Python 3.8+.
4
+ Чат и стриминг, все типы моделей, список доступных моделей, лимиты ключа, баланс кабинета, оценка стоимости запроса, async и командная строка.
5
+
6
+ Сайт: https://klyuchora.ru · Документация: https://klyuchora.ru/sdk
7
+
8
+ ## Установка
9
+
10
+ pip install klyuchora
11
+
12
+ ## Быстрый старт
13
+
14
+ Ключ создаётся в кабинете на https://klyuchora.ru (раздел «Ключи API»). Положите его в переменную окружения `KLYUCHORA_API_KEY`.
15
+
16
+ ```python
17
+ from klyuchora import Klyuchora
18
+
19
+ client = Klyuchora() # ключ берётся из KLYUCHORA_API_KEY
20
+ reply = client.chat.completions.create(
21
+ model="gpt-4o-mini",
22
+ messages=[{"role": "user", "content": "Привет!"}],
23
+ )
24
+ print(reply.choices[0].message.content)
25
+
26
+ # стриминг
27
+ with client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Расскажи шутку"}], stream=True) as stream:
28
+ for text in stream.text_deltas():
29
+ print(text, end="", flush=True)
30
+
31
+ print(client.models.ids()) # модели, доступные вашему ключу
32
+ print(client.key.usage()) # лимиты и расход ключа
33
+ print(client.account.balance()) # баланс кабинета (нужен KLYUCHORA_ACCESS_TOKEN)
34
+ print(client.estimate_cost("gpt-4o-mini", input_tokens=1000, output_tokens=500))
35
+ ```
36
+
37
+ Асинхронный клиент: `AsyncKlyuchora`. Командная строка:
38
+ `klyuchora models | price МОДЕЛЬ | usage | balance | keys | rate | chat МОДЕЛЬ "текст"`.
39
+
40
+ Полная документация с примерами для всех методов: https://klyuchora.ru/sdk
41
+
42
+ ## Лицензия
43
+
44
+ MIT
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "klyuchora"
7
+ version = "0.2.0"
8
+ description = "SDK Ключоры для Python: все модели, стриминг, лимиты ключей, баланс кабинета. Сайт: https://klyuchora.ru"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Klyuchora" }]
13
+ keywords = ["klyuchora", "ключора", "llm", "api", "sdk", "ai"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Typing :: Typed",
19
+ ]
20
+ dependencies = []
21
+
22
+ [project.urls]
23
+ Homepage = "https://klyuchora.ru"
24
+ Documentation = "https://klyuchora.ru/sdk"
25
+
26
+ [project.scripts]
27
+ klyuchora = "klyuchora.cli:main"
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+
32
+ [tool.setuptools.package-data]
33
+ klyuchora = ["py.typed"]
@@ -0,0 +1,41 @@
1
+ [metadata]
2
+ name = klyuchora
3
+ version = attr: klyuchora._version.__version__
4
+ description = SDK Ключоры для Python: все модели, стриминг, лимиты ключей, баланс кабинета. Сайт: https://klyuchora.ru
5
+ long_description = file: README.md
6
+ long_description_content_type = text/markdown
7
+ keywords = klyuchora, ключора, llm, api, sdk, ai
8
+ url = https://klyuchora.ru
9
+ project_urls =
10
+ Документация = https://klyuchora.ru/sdk
11
+ Сайт = https://klyuchora.ru
12
+ author = Klyuchora
13
+ license = MIT
14
+ license_files = LICENSE
15
+ classifiers =
16
+ Programming Language :: Python :: 3
17
+ License :: OSI Approved :: MIT License
18
+ Operating System :: OS Independent
19
+ Typing :: Typed
20
+
21
+ [options]
22
+ package_dir = =src
23
+ packages = find:
24
+ python_requires = >=3.8
25
+ zip_safe = False
26
+ include_package_data = True
27
+
28
+ [options.packages.find]
29
+ where = src
30
+
31
+ [options.package_data]
32
+ klyuchora = py.typed
33
+
34
+ [options.entry_points]
35
+ console_scripts =
36
+ klyuchora = klyuchora.cli:main
37
+
38
+ [egg_info]
39
+ tag_build =
40
+ tag_date = 0
41
+
@@ -0,0 +1,2 @@
1
+ from setuptools import setup
2
+ setup()
@@ -0,0 +1,22 @@
1
+ """Klyuchora SDK: one client for chat, responses, embeddings, images, audio, models, key limits and balance."""
2
+ from ._client import Klyuchora
3
+ from ._errors import (APIError, AuthenticationError, BadRequestError, ConnectionFailed,
4
+ InsufficientBalanceError, KlyuchoraError, NotFoundError, PermissionDeniedError,
5
+ RateLimitError, RequestTimeout, ServerError)
6
+ from ._obj import Obj
7
+ from ._stream import ChatStream, Stream
8
+ from ._version import __version__
9
+
10
+ __all__ = [
11
+ "Klyuchora", "AsyncKlyuchora", "Stream", "ChatStream", "Obj", "__version__",
12
+ "KlyuchoraError", "APIError", "AuthenticationError", "BadRequestError", "ConnectionFailed",
13
+ "InsufficientBalanceError", "NotFoundError", "PermissionDeniedError", "RateLimitError",
14
+ "RequestTimeout", "ServerError",
15
+ ]
16
+
17
+
18
+ def __getattr__(name): # lazy: asyncio is only imported when needed
19
+ if name == "AsyncKlyuchora":
20
+ from ._async import AsyncKlyuchora
21
+ return AsyncKlyuchora
22
+ raise AttributeError(name)
@@ -0,0 +1,3 @@
1
+ import sys
2
+ from .cli import main
3
+ sys.exit(main())
@@ -0,0 +1,99 @@
1
+ """Async interface. Calls run in worker threads, so it works on any asyncio loop with no extra packages."""
2
+ import asyncio
3
+ import functools
4
+ from typing import Any, AsyncIterator, Optional
5
+
6
+ from ._client import Klyuchora
7
+ from ._stream import ChatStream, Stream
8
+
9
+
10
+ async def _run(fn, *args, **kwargs):
11
+ loop = asyncio.get_running_loop()
12
+ return await loop.run_in_executor(None, functools.partial(fn, *args, **kwargs))
13
+
14
+
15
+ class AsyncStream:
16
+ """``async for`` over a :class:`Stream`."""
17
+
18
+ def __init__(self, stream: Stream):
19
+ self._stream = stream
20
+ self.request_id = stream.request_id
21
+
22
+ def __aiter__(self) -> "AsyncStream":
23
+ return self
24
+
25
+ async def __anext__(self) -> Any:
26
+ def step():
27
+ try:
28
+ return next(self._stream), False
29
+ except StopIteration:
30
+ return None, True
31
+ item, done = await _run(step)
32
+ if done:
33
+ raise StopAsyncIteration
34
+ return item
35
+
36
+ async def text_deltas(self) -> AsyncIterator[str]:
37
+ async for chunk in self:
38
+ for choice in chunk.get("choices") or []:
39
+ piece = (choice.get("delta") or {}).get("content")
40
+ if piece:
41
+ yield piece
42
+
43
+ async def collect(self) -> Any:
44
+ if isinstance(self._stream, ChatStream):
45
+ return await _run(self._stream.collect)
46
+ return [event async for event in self]
47
+
48
+ async def aclose(self) -> None:
49
+ await _run(self._stream.close)
50
+
51
+ async def __aenter__(self) -> "AsyncStream":
52
+ return self
53
+
54
+ async def __aexit__(self, *exc: Any) -> None:
55
+ await self.aclose()
56
+
57
+
58
+ class _AsyncProxy:
59
+ def __init__(self, target: Any):
60
+ self._target = target
61
+
62
+ def __getattr__(self, name: str) -> Any:
63
+ attr = getattr(self._target, name)
64
+ if callable(attr):
65
+ @functools.wraps(attr)
66
+ async def call(*args: Any, **kwargs: Any) -> Any:
67
+ result = await _run(attr, *args, **kwargs)
68
+ return AsyncStream(result) if isinstance(result, Stream) else result
69
+ return call
70
+ if hasattr(attr, "__dict__") and not isinstance(attr, (str, int, float, bool, list, dict)):
71
+ return _AsyncProxy(attr)
72
+ return attr
73
+
74
+
75
+ class AsyncKlyuchora:
76
+ """Same API as :class:`Klyuchora`, every method is awaited:
77
+
78
+ client = AsyncKlyuchora()
79
+ reply = await client.chat.completions.create(model="...", messages=[...])
80
+ stream = await client.chat.completions.create(model="...", messages=[...], stream=True)
81
+ async for text in stream.text_deltas(): ...
82
+ """
83
+
84
+ def __init__(self, *args: Any, **kwargs: Any):
85
+ self._sync = Klyuchora(*args, **kwargs)
86
+ for name in ("chat", "completions", "responses", "messages", "embeddings", "images", "audio",
87
+ "rerank", "moderations", "models", "key", "account", "rates"):
88
+ setattr(self, name, _AsyncProxy(getattr(self._sync, name)))
89
+
90
+ @property
91
+ def base_url(self) -> str:
92
+ return self._sync.base_url
93
+
94
+ async def estimate_cost(self, *args: Any, **kwargs: Any) -> Any:
95
+ return await _run(self._sync.estimate_cost, *args, **kwargs)
96
+
97
+ async def request(self, *args: Any, **kwargs: Any) -> Any:
98
+ result = await _run(self._sync.request, *args, **kwargs)
99
+ return AsyncStream(result) if isinstance(result, Stream) else result