revengelibrary 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.
- revengelibrary/__init__.py +4 -0
- revengelibrary/chat.py +76 -0
- revengelibrary/cli.py +73 -0
- revengelibrary-0.1.0.dist-info/METADATA +88 -0
- revengelibrary-0.1.0.dist-info/RECORD +9 -0
- revengelibrary-0.1.0.dist-info/WHEEL +5 -0
- revengelibrary-0.1.0.dist-info/entry_points.txt +2 -0
- revengelibrary-0.1.0.dist-info/licenses/LICENSE +21 -0
- revengelibrary-0.1.0.dist-info/top_level.txt +1 -0
revengelibrary/chat.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class APIError(RuntimeError):
|
|
10
|
+
"""Raised when the upstream API returns an invalid response."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class FreeNeuroChatClient:
|
|
15
|
+
"""Small wrapper around OpenRouter's OpenAI-compatible chat endpoint."""
|
|
16
|
+
|
|
17
|
+
api_key: str
|
|
18
|
+
model: str = "meta-llama/llama-3.1-8b-instruct:free"
|
|
19
|
+
base_url: str = "https://openrouter.ai/api/v1"
|
|
20
|
+
timeout: int = 60
|
|
21
|
+
system_prompt: str | None = "You are a helpful assistant."
|
|
22
|
+
messages: list[dict[str, str]] = field(default_factory=list)
|
|
23
|
+
|
|
24
|
+
def __post_init__(self) -> None:
|
|
25
|
+
if not self.api_key:
|
|
26
|
+
raise ValueError("api_key is required")
|
|
27
|
+
if self.system_prompt and not self.messages:
|
|
28
|
+
self.messages.append({"role": "system", "content": self.system_prompt})
|
|
29
|
+
|
|
30
|
+
def send(self, user_message: str) -> str:
|
|
31
|
+
"""Send user text and return assistant reply."""
|
|
32
|
+
user_message = user_message.strip()
|
|
33
|
+
if not user_message:
|
|
34
|
+
raise ValueError("user_message must not be empty")
|
|
35
|
+
|
|
36
|
+
self.messages.append({"role": "user", "content": user_message})
|
|
37
|
+
payload = {"model": self.model, "messages": self.messages}
|
|
38
|
+
|
|
39
|
+
response = requests.post(
|
|
40
|
+
f"{self.base_url}/chat/completions",
|
|
41
|
+
headers=self._headers(),
|
|
42
|
+
json=payload,
|
|
43
|
+
timeout=self.timeout,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
if response.status_code >= 400:
|
|
47
|
+
raise APIError(
|
|
48
|
+
f"API returned {response.status_code}: {response.text[:500]}"
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
data = response.json()
|
|
52
|
+
content = self._extract_content(data)
|
|
53
|
+
self.messages.append({"role": "assistant", "content": content})
|
|
54
|
+
return content
|
|
55
|
+
|
|
56
|
+
def reset(self) -> None:
|
|
57
|
+
"""Clear dialog history but keep initial system prompt."""
|
|
58
|
+
self.messages = []
|
|
59
|
+
if self.system_prompt:
|
|
60
|
+
self.messages.append({"role": "system", "content": self.system_prompt})
|
|
61
|
+
|
|
62
|
+
def _headers(self) -> dict[str, str]:
|
|
63
|
+
return {
|
|
64
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
65
|
+
"Content-Type": "application/json",
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def _extract_content(data: dict[str, Any]) -> str:
|
|
70
|
+
try:
|
|
71
|
+
content = data["choices"][0]["message"]["content"]
|
|
72
|
+
if not isinstance(content, str) or not content.strip():
|
|
73
|
+
raise KeyError
|
|
74
|
+
return content
|
|
75
|
+
except (KeyError, TypeError, IndexError):
|
|
76
|
+
raise APIError(f"Unexpected API response: {data}") from None
|
revengelibrary/cli.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
from .chat import APIError, FreeNeuroChatClient
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
10
|
+
parser = argparse.ArgumentParser(
|
|
11
|
+
prog="revengelibrary",
|
|
12
|
+
description="Interactive terminal chat with free OpenRouter models.",
|
|
13
|
+
)
|
|
14
|
+
parser.add_argument(
|
|
15
|
+
"--api-key",
|
|
16
|
+
default=os.getenv("OPENROUTER_API_KEY", ""),
|
|
17
|
+
help="OpenRouter API key. Fallback: OPENROUTER_API_KEY env var.",
|
|
18
|
+
)
|
|
19
|
+
parser.add_argument(
|
|
20
|
+
"--model",
|
|
21
|
+
default="meta-llama/llama-3.1-8b-instruct:free",
|
|
22
|
+
help="Model name on OpenRouter (default uses a free model).",
|
|
23
|
+
)
|
|
24
|
+
parser.add_argument(
|
|
25
|
+
"--system",
|
|
26
|
+
default="You are a helpful assistant.",
|
|
27
|
+
help="System prompt.",
|
|
28
|
+
)
|
|
29
|
+
return parser
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main() -> int:
|
|
33
|
+
parser = _build_parser()
|
|
34
|
+
args = parser.parse_args()
|
|
35
|
+
|
|
36
|
+
if not args.api_key:
|
|
37
|
+
parser.error("API key is required: pass --api-key or set OPENROUTER_API_KEY.")
|
|
38
|
+
|
|
39
|
+
client = FreeNeuroChatClient(
|
|
40
|
+
api_key=args.api_key,
|
|
41
|
+
model=args.model,
|
|
42
|
+
system_prompt=args.system,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
print("Interactive chat started. Type 'exit' to quit, 'reset' to clear history.")
|
|
46
|
+
while True:
|
|
47
|
+
try:
|
|
48
|
+
text = input("you> ").strip()
|
|
49
|
+
except (EOFError, KeyboardInterrupt):
|
|
50
|
+
print("\nbye")
|
|
51
|
+
return 0
|
|
52
|
+
|
|
53
|
+
if not text:
|
|
54
|
+
continue
|
|
55
|
+
if text.lower() in {"exit", "quit"}:
|
|
56
|
+
print("bye")
|
|
57
|
+
return 0
|
|
58
|
+
if text.lower() == "reset":
|
|
59
|
+
client.reset()
|
|
60
|
+
print("history reset")
|
|
61
|
+
continue
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
answer = client.send(text)
|
|
65
|
+
print(f"ai> {answer}")
|
|
66
|
+
except APIError as exc:
|
|
67
|
+
print(f"api error: {exc}")
|
|
68
|
+
except Exception as exc: # noqa: BLE001
|
|
69
|
+
print(f"unexpected error: {exc}")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
if __name__ == "__main__":
|
|
73
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: revengelibrary
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python chat library and CLI for free LLM models via OpenRouter.
|
|
5
|
+
Author: revengebibliotek contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/example/revengelibrary
|
|
8
|
+
Keywords: chat,llm,openrouter,api,cli
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: requests>=2.31.0
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# revengelibrary
|
|
19
|
+
|
|
20
|
+
Небольшая Python-библиотека и CLI для чата с нейросетью через бесплатные модели OpenRouter.
|
|
21
|
+
|
|
22
|
+
## Установка
|
|
23
|
+
|
|
24
|
+
Из PyPI (после публикации):
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install revengelibrary
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Локально из папки проекта:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install .
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Для разработки:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install -e .
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## Подготовка API ключа
|
|
43
|
+
|
|
44
|
+
1. Создай бесплатный API key в OpenRouter.
|
|
45
|
+
2. Экспортируй ключ:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
export OPENROUTER_API_KEY="your_key"
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Использование в Python
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from revengelibrary import FreeNeuroChatClient
|
|
55
|
+
|
|
56
|
+
client = FreeNeuroChatClient(api_key="your_key")
|
|
57
|
+
reply = client.send("Привет! Расскажи коротко анекдот.")
|
|
58
|
+
print(reply)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Запуск из терминала
|
|
62
|
+
|
|
63
|
+
После установки доступна команда:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
revengelibrary --model meta-llama/llama-3.1-8b-instruct:free
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Если ключ лежит в `OPENROUTER_API_KEY`, то `--api-key` можно не передавать.
|
|
70
|
+
|
|
71
|
+
## Минимальный API библиотеки
|
|
72
|
+
|
|
73
|
+
- `FreeNeuroChatClient.send(text: str) -> str`
|
|
74
|
+
- `FreeNeuroChatClient.reset() -> None`
|
|
75
|
+
|
|
76
|
+
## Публикация в PyPI
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
python3 -m pip install --upgrade build twine
|
|
80
|
+
python3 -m build
|
|
81
|
+
python3 -m twine upload dist/*
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
После этого любой человек сможет установить библиотеку:
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
pip install revengelibrary
|
|
88
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
revengelibrary/__init__.py,sha256=fTxpG-6tD8L7mRvBv19uO7mZUgI0VYdTe7NS0V7TFQY,117
|
|
2
|
+
revengelibrary/chat.py,sha256=tjwxG01Tg7FSp850px-15jP6Tuygo5U3w_oSLBrzZgE,2582
|
|
3
|
+
revengelibrary/cli.py,sha256=bXiwnGuJFChOT6cxBOkT8FGtFed0LIrCdc8yIND4oZk,1961
|
|
4
|
+
revengelibrary-0.1.0.dist-info/licenses/LICENSE,sha256=UgqQ8UtVfIOP8-clGkGAylmb9AUbT4-Ue49N_WjIpi4,1073
|
|
5
|
+
revengelibrary-0.1.0.dist-info/METADATA,sha256=pFHcFRcvos2tVXN0D7xGtgwz4-miIMryB1eBbkCVXSU,2137
|
|
6
|
+
revengelibrary-0.1.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
|
|
7
|
+
revengelibrary-0.1.0.dist-info/entry_points.txt,sha256=299WMDffRchuwIlqEIjW-DwHYkBvRZQwGjiASIVofYE,59
|
|
8
|
+
revengelibrary-0.1.0.dist-info/top_level.txt,sha256=gfUsAxA-IgliQakMoupLAAjrTEYtUJurH5n29eHhUBE,15
|
|
9
|
+
revengelibrary-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 revengebibliotek
|
|
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 @@
|
|
|
1
|
+
revengelibrary
|