recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
+10
@@ -0,0 +1,10 @@
|
|||||||
|
# ключи — НИКОГДА не коммитить
|
||||||
|
keys.txt
|
||||||
|
.env
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
config.json
|
||||||
|
accounts.jsonl
|
||||||
|
post_draft.md
|
||||||
|
post_draft2.md
|
||||||
|
post_draft3.md
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 jev-decision-hub contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
# JEV Decision Hub — бесплатный decision-layer для твоих агентов
|
||||||
|
|
||||||
|
[](https://jev-ai.pro)
|
||||||
|
[](LICENSE)
|
||||||
|
|
||||||
|
**Jev** (TypeSafe AI, System One) — это НЕ чат-модель. Это decision-модель: отправляешь
|
||||||
|
`state` (текст/JSON) + типизированные вопросы — получаешь готовые решения с
|
||||||
|
откалиброванными вероятностями за ~0.3 секунды. Без промпт-инжиниринга, без парсинга
|
||||||
|
JSON из простыни текста, без стриминга.
|
||||||
|
|
||||||
|
```
|
||||||
|
LLM генерирует → Агент исполняет → JEV решает
|
||||||
|
```
|
||||||
|
|
||||||
|
Формула из [тредa Arindam Majumder](https://x.com/arindam_1729/status/2106750207254032411),
|
||||||
|
который собрал 16k+ просмотров: самое интересное — не сам Jev, а роль decision-слоя
|
||||||
|
внутри агентных систем.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Зачем это юзать
|
||||||
|
|
||||||
|
| Задача | Как решает Jev | Почему не LLM |
|
||||||
|
|---|---|---|
|
||||||
|
| **Модерация/спам-фильтр** | `noul` — вероятность что пост спам (0-1) | LLM на каждый пост = дорого и медленно; Jev = 1 кредит (~$0.00002) и 300мс |
|
||||||
|
| **Роутинг задач на модели** | `choice` — какая модель/агент обработает таск | Калиброванные вероятности вместо галлюцинаций |
|
||||||
|
| **Трейдинг-сигналы** | `choice` buy/sell/wait по состоянию рынка | Детерминированный типизированный ответ |
|
||||||
|
| **Супервизор кодинг-агентов** | continue / retry / verify / stop | Решение с confidence-порогом, можно тестить |
|
||||||
|
| **Триаж тикетов/лидов** | score злости, choice отдела, noul churn-риска | 20 вопросов на один state одним вызовом |
|
||||||
|
| **Компрессия контекста** | какие куски памяти агента ещё полезны | Дешевле чем прогонять контекст через чат-модель |
|
||||||
|
| **Фильтр браузера/автоматизации** | следующее действие агента | Латентность 70-500мс вместо секунд |
|
||||||
|
| **Code review-гейты** | проходит ли дифф критерии | Да/нет с вероятностью, а не «возможно» |
|
||||||
|
|
||||||
|
Три примитива вопросов:
|
||||||
|
- **noul** — вероятность true/false (0-1)
|
||||||
|
- **choice** — выбор из 2-24 вариантов + полное распределение вероятностей
|
||||||
|
- **score** — оценка по шкале 2-10 уровней + confidence
|
||||||
|
|
||||||
|
## Бесплатный доступ
|
||||||
|
|
||||||
|
1. Зайди на [jev-ai.pro](https://jev-ai.pro) → Login → magic-link на почту (без пароля и капчи)
|
||||||
|
2. Welcome-бонус: **20 бесплатных кредитов**
|
||||||
|
3. Daily check-in: **+1...3 кредита каждый день** (стрик-система, кредиты живут 30 дней)
|
||||||
|
4. Settings → API Keys → создать ключ (`sk_jev-ai_...`, показывается один раз)
|
||||||
|
5. 1 кредит = 1 успешный вызов. Неудачные запросы не тарифицируются.
|
||||||
|
|
||||||
|
Официальные платные маршруты (та же модель): `api.typesafe.ai` ($0.042/MTok input,
|
||||||
|
output бесплатно), OpenRouter `typesafe/jev-1.13`, Vercel AI Gateway `typesafe-ai/jev`,
|
||||||
|
Cloudflare Workers AI `typesafe/jev`.
|
||||||
|
|
||||||
|
## Быстрый старт — 3 команды
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/gbonnet65923/jev-decision-hub && cd jev-decision-hub
|
||||||
|
|
||||||
|
# 1. настрой свой IMAP-ящик (Gmail app password или свой домен)
|
||||||
|
cp config.example.json config.json # и впиши imap_host / imap_user / imap_pass
|
||||||
|
|
||||||
|
# 2. авторег: нафармить бесплатных ключей (magic-link, БЕЗ капчи и пароля)
|
||||||
|
python auto_register.py reg 5 # ключи сами пишутся в keys.txt
|
||||||
|
|
||||||
|
# 3. юзай
|
||||||
|
python jev_client.py run '{"state":"текст","questions":{"q":{"type":"noul","instructions":"вопрос?"}}}'
|
||||||
|
python dashboard.py # веб-панель http://localhost:8590
|
||||||
|
```
|
||||||
|
|
||||||
|
### Авторег — как это работает
|
||||||
|
|
||||||
|
`auto_register.py` регистрирует аккаунты через magic-link (сайт не требует ни пароля, ни капчи):
|
||||||
|
1. `POST /api/auth/magic-link` на твой ящик (режим **alias**: `user+tag@domain` для Gmail/Outlook, или **catchall**: `random@твойдомен.com`)
|
||||||
|
2. читает ссылку из письма по IMAP (токен живёт 15 минут)
|
||||||
|
3. заходит по ссылке, создаёт API-ключ, пишет его в `keys.txt` + `accounts.jsonl`
|
||||||
|
|
||||||
|
| Команда | Что делает |
|
||||||
|
|---|---|
|
||||||
|
| `python auto_register.py reg 5` | 5 новых аккаунтов + ключей |
|
||||||
|
| `python auto_register.py checkin` | daily check-in по всем аккаунтам (+1-3 кредита каждому) |
|
||||||
|
| `python auto_register.py status` | все аккаунты, ключи, суммарные кредиты |
|
||||||
|
| `python auto_register.py daily` | checkin + 2 новых реги — ставь в cron/планировщик |
|
||||||
|
|
||||||
|
**Прокси (важно для welcome-бонуса):** welcome-20 дают только ~2 аккам в день с одного IP. Положи свои http-прокси в `proxies.txt` (построчно `http://ip:port`) и укажи его в `config.json` → `"proxies_file": "proxies.txt"`. Каждая регистрация пойдёт через свежий живой прокси (мёртвые скрипт отсеивает сам) и получит свои welcome-20.
|
||||||
|
|
||||||
|
Gmail: включи IMAP и сделай app password (Google Account → Security → 2-Step Verification → App passwords).
|
||||||
|
`config.json` в .gitignore — твои креды не закоммитятся.
|
||||||
|
|
||||||
|
### Экономика кредитов (честно)
|
||||||
|
|
||||||
|
- Welcome-бонус **20 кредитов**: выдаётся примерно первым **2 аккаунтам в день с одного IP** (дальше 0 — антифрод)
|
||||||
|
- Daily check-in: **+1...3 кредита в день на каждый аккаунт** (стрик-система, кредиты живут 30 дней)
|
||||||
|
- 1 кредит = 1 успешное решение; failed-запросы не биллятся
|
||||||
|
- Держи пул из 10-30 аккаунтов через `daily` в cron → стабильные ~20-60 кредитов/день бесплатно
|
||||||
|
|
||||||
|
## Юз клиента
|
||||||
|
|
||||||
|
```python
|
||||||
|
from jev_client import decide
|
||||||
|
|
||||||
|
r = decide(
|
||||||
|
state="Post text: 'Продаю аккаунты, дешево, писать в лс' (акк создан 2 дня назад, 0 постов)",
|
||||||
|
questions={
|
||||||
|
"spam": {"type": "noul", "instructions": "Is this post spam?"},
|
||||||
|
"action": {"type": "choice", "instructions": "Moderation action",
|
||||||
|
"criteria": {"ban": "ban user", "delete": "delete post", "keep": "leave"}},
|
||||||
|
})
|
||||||
|
print(r["answers"]["spam"]["noul"]) # 0.95
|
||||||
|
print(r["answers"]["action"]["choice"]) # "ban"
|
||||||
|
```
|
||||||
|
|
||||||
|
`decide()` сам ротирует ключи из `keys.txt`: 402/401 на одном — переключается на следующий. 522/5xx/таймауты ретраятся сами.
|
||||||
|
|
||||||
|
## Raw API — один curl, без библиотек
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST "https://jev-ai.pro/api/v1/systemone" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "Authorization: Bearer $JEV_KEY" \
|
||||||
|
-d '{
|
||||||
|
"model": "jev-latest",
|
||||||
|
"state": "Сообщение в чате: ПРОДАМ БАЗУ Email 500M записей, оплата крипта, писать в лс @spamking",
|
||||||
|
"questions": {
|
||||||
|
"spam": {"type": "noul", "instructions": "Is this spam?"},
|
||||||
|
"action": {"type": "choice", "instructions": "Moderation action",
|
||||||
|
"criteria": {"ban": "ban user", "delete": "remove message", "keep": "leave"}}
|
||||||
|
}
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Ответ (реальный, 0.58s):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"model": "jev-1.13.0",
|
||||||
|
"answers": {
|
||||||
|
"spam": {"type": "noul", "noul": 0.98},
|
||||||
|
"action": {"type": "choice", "choice": "delete", "confidence": 0.37,
|
||||||
|
"probabilities": {"ban": 0.42, "delete": 0.58, "keep": 0}}},
|
||||||
|
"usage": {"input_tokens": 395, "output_tokens": 54}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Типы вопросов: `noul` (да/нет 0-1), `choice` (до 24 вариантов, dict критериев), `score` (шкала, массив уровней в `criteria`). До 20 вопросов на один state. Ошибки 4xx/5xx не биллятся.
|
||||||
|
|
||||||
|
## Дашборд
|
||||||
|
|
||||||
|
`dashboard.py` — zero-dependency (stdlib) веб-панель:
|
||||||
|
- вставляешь токен в поле (хранится только в памяти процесса)
|
||||||
|
- список доступных моделей с их тарификацией
|
||||||
|
- тестовый вызов с таймером латентности
|
||||||
|
- пул-режим: несколько ключей, суммарный баланс вызовов
|
||||||
|
|
||||||
|
## Примеры (examples/)
|
||||||
|
|
||||||
|
| Файл | Что делает |
|
||||||
|
|---|---|
|
||||||
|
| `spam_moderation.py` | Фильтр постов/сообщений: spam-score + действие с порогами |
|
||||||
|
| `model_router.py` | Роутер задач: какая модель (cheap/smart/vision) обработает запрос |
|
||||||
|
| `trade_signal.py` | Buy/sell/wait по снапшоту рынка с confidence-гейтом |
|
||||||
|
| `agent_foreman.py` | Супервизор агента: continue/retry/verify/stop после каждого шага |
|
||||||
|
|
||||||
|
## Экосистема — 10 реп из треда
|
||||||
|
|
||||||
|
1. [browser-use/jev-ultrafast](https://github.com/browser-use/jev-ultrafast) (~16.6k⭐) — Jev выбирает следующее действие браузера без дорогого LLM-вызова
|
||||||
|
2. [tamaratran/fast-jev-compaction](https://github.com/tamaratran/fast-jev-compaction) (~6.5k⭐) — компрессия контекста: что оставить, что выбросить
|
||||||
|
3. [TheoLeeCJ/SemIf-OpenJev](https://github.com/TheoLeeCJ/SemIf-OpenJev) (~4k⭐) — open-source локальная реализация Jev-style решений
|
||||||
|
4. [jarrodwatts/jev-trader](https://github.com/jarrodwatts/jev-trader) (~2.1k⭐) — realtime трейдинг-луп buy/sell/wait
|
||||||
|
5. [kerpopule/hermes-jev-skills](https://github.com/kerpopule/hermes-jev-skills) (~670⭐) — роутинг/память/компакция/выбор скиллов
|
||||||
|
6. [devagrawal09/jev-review](https://github.com/devagrawal09/jev-review) (~570⭐) — code review решениями вместо мега-промпта
|
||||||
|
7. [thruwire/foreman](https://github.com/thruwire/foreman) (~520⭐) — супервизор кодинг-агентов
|
||||||
|
8. [superagents-lab/jev-search](https://github.com/superagents-lab/jev-search) (~400⭐) — где и как искать следующему шагу агента
|
||||||
|
9. [droidrun/mobile-jev](https://github.com/droidrun/mobile-jev) (~350⭐) — следующие действия Android-агентов
|
||||||
|
10. [gargpratyush/jev-router](https://github.com/gargpratyush/jev-router) (~340⭐) — роутинг тасков на нужную модель
|
||||||
|
|
||||||
|
## API-шпаргалка
|
||||||
|
|
||||||
|
```
|
||||||
|
POST https://jev-ai.pro/api/v1/systemone
|
||||||
|
Authorization: Bearer sk_jev-ai_...
|
||||||
|
{"model":"jev-latest","state":"...","questions":{"<id>":{"type":"noul|choice|score","instructions":"...","criteria":...}}}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `GET /api/v1/models/` — список моделей (не тарифицируется)
|
||||||
|
- Лимиты: 20 вопросов/вызов, 32k токенов контекста, 10k решений/день на ключ
|
||||||
|
- Ответ: `answers.<id>` + `probabilities` + `confidence` + `usage`
|
||||||
|
- Ошибки: 401 ключ, 402 нет кредитов, 422 oversized input (не биллится), 429 rate limit
|
||||||
|
|
||||||
|
## Лицензия
|
||||||
|
|
||||||
|
MIT. Репо self-contained: нужен только Python 3.9+ (stdlib), никаких зависимостей.
|
||||||
|
|
||||||
|
---
|
||||||
|
👻 [**иишко**](https://t.me/AlStack) — каталоги халявы, AI-тулзов и абюза
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
"""JEV auto-register — бесплатные ключи на автомате.
|
||||||
|
|
||||||
|
Регистрация на jev-ai.pro через magic-link: БЕЗ пароля и БЕЗ капчи.
|
||||||
|
Нужен только любой IMAP-ящик (Gmail + app password, или свой домен с catch-all).
|
||||||
|
|
||||||
|
Настройка (2 способа):
|
||||||
|
1) cp config.example.json config.json -> вписать свой IMAP
|
||||||
|
2) или env: JEV_IMAP_HOST / JEV_IMAP_USER / JEV_IMAP_PASS
|
||||||
|
|
||||||
|
Gmail: включить IMAP, создать app password (Google Account -> Security -> 2-Step -> App passwords).
|
||||||
|
Режимы почты:
|
||||||
|
"alias" — ящик поддерживает +теги (Gmail, Outlook): user+tag@domain
|
||||||
|
"catchall" — свой домен ловит всё: random@yourdomain.com
|
||||||
|
|
||||||
|
Команды:
|
||||||
|
python auto_register.py reg 5 # зарегистрировать 5 аккаунтов -> ключи в keys.txt
|
||||||
|
python auto_register.py checkin # daily check-in по всем аккаунтам (+1-3 кредита)
|
||||||
|
python auto_register.py status # аккаунты, ключи, кредиты
|
||||||
|
python auto_register.py daily # checkin + 2 новых реги (для cron)
|
||||||
|
|
||||||
|
Каждый аккаунт: welcome-кредиты + ежедневный check-in. Кредиты живут 30 дней.
|
||||||
|
Ключи пишутся в keys.txt (для jev_client.py / dashboard.py) и accounts.jsonl (куки для checkin).
|
||||||
|
|
||||||
|
Welcome-бонус (20 кредитов) дают только ~2 аккаунтам в день с одного IP.
|
||||||
|
Чтобы фармить больше — укажи "proxies_file" в config.json (текстовый файл, http://ip:port построчно):
|
||||||
|
каждая регистрация пойдёт через свежий прокси и получит свои welcome-20.
|
||||||
|
AlStack: https://t.me/AlStack
|
||||||
|
"""
|
||||||
|
import json, os, re, sys, time, random, string
|
||||||
|
import urllib.request, http.cookiejar
|
||||||
|
import imaplib, email
|
||||||
|
|
||||||
|
BASE = 'https://jev-ai.pro'
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
KEYS_FILE = os.path.join(HERE, 'keys.txt')
|
||||||
|
ACC_FILE = os.path.join(HERE, 'accounts.jsonl')
|
||||||
|
CFG_FILE = os.path.join(HERE, 'config.json')
|
||||||
|
|
||||||
|
HDRS = {
|
||||||
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
|
||||||
|
'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.9',
|
||||||
|
'Origin': BASE, 'Referer': BASE + '/jev-api',
|
||||||
|
'Sec-Ch-Ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
|
||||||
|
'Sec-Ch-Ua-Mobile': '?0', 'Sec-Ch-Ua-Platform': '"Windows"',
|
||||||
|
'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-origin',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def cfg():
|
||||||
|
c = {'imap_host': os.environ.get('JEV_IMAP_HOST', ''),
|
||||||
|
'imap_user': os.environ.get('JEV_IMAP_USER', ''),
|
||||||
|
'imap_pass': os.environ.get('JEV_IMAP_PASS', ''),
|
||||||
|
'email_mode': os.environ.get('JEV_EMAIL_MODE', 'alias'),
|
||||||
|
'email_domain': os.environ.get('JEV_EMAIL_DOMAIN', ''),
|
||||||
|
'proxies_file': os.environ.get('JEV_PROXIES_FILE', '')}
|
||||||
|
if os.path.exists(CFG_FILE):
|
||||||
|
c.update({k: v for k, v in json.load(open(CFG_FILE, encoding='utf-8')).items() if v})
|
||||||
|
if not (c['imap_host'] and c['imap_user'] and c['imap_pass']):
|
||||||
|
raise SystemExit('нет IMAP-конфига: cp config.example.json config.json и заполни (или env JEV_IMAP_*)')
|
||||||
|
if c['email_mode'] == 'catchall' and not c['email_domain']:
|
||||||
|
raise SystemExit('для catchall нужен email_domain')
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def load_proxies(c):
|
||||||
|
"""Опциональный файл прокси (http://ip:port построчно). Welcome-бонус ~2 акка/IP/день —
|
||||||
|
со свежим IP через прокси снова дают 20 кредитов. Пусто = прямые запросы."""
|
||||||
|
pf = c.get('proxies_file') or ''
|
||||||
|
if pf and os.path.exists(pf):
|
||||||
|
pxs = [l.strip() for l in open(pf, encoding='utf-8')
|
||||||
|
if l.strip() and not l.startswith('#') and '://' in l]
|
||||||
|
random.shuffle(pxs)
|
||||||
|
return pxs
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def proxy_alive(px):
|
||||||
|
"""Быстрый CONNECT-тест: большинство бесплатных прокси мертвы, не тратить на них реги."""
|
||||||
|
ph = urllib.request.ProxyHandler({'http': px, 'https': px})
|
||||||
|
op = urllib.request.build_opener(ph)
|
||||||
|
op.addheaders = [('User-Agent', HDRS['User-Agent'])]
|
||||||
|
try:
|
||||||
|
return op.open(BASE + '/login', timeout=15).status == 200
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def make_email(c):
|
||||||
|
tag = 'jv' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
|
||||||
|
if c['email_mode'] == 'catchall':
|
||||||
|
return f'{tag}@{c["email_domain"]}'
|
||||||
|
local = c['imap_user'].split('@')[0]
|
||||||
|
domain = c['imap_user'].split('@')[1] if '@' in c['imap_user'] else c['email_domain']
|
||||||
|
return f'{local}+{tag}@{domain}'
|
||||||
|
|
||||||
|
|
||||||
|
def http_call(op, method, url, body=None, cookie_str=None):
|
||||||
|
h = dict(HDRS)
|
||||||
|
if body is not None:
|
||||||
|
h['Content-Type'] = 'application/json'
|
||||||
|
if cookie_str:
|
||||||
|
h['Cookie'] = cookie_str
|
||||||
|
req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
|
||||||
|
headers=h, method=method)
|
||||||
|
try:
|
||||||
|
r = op.open(req, timeout=45)
|
||||||
|
return r.status, r.read().decode('utf-8', 'ignore')
|
||||||
|
except urllib.error.HTTPError as ex:
|
||||||
|
return ex.code, ex.read().decode('utf-8', 'ignore')
|
||||||
|
|
||||||
|
|
||||||
|
def opener(proxy=None):
|
||||||
|
cj = http.cookiejar.CookieJar()
|
||||||
|
handlers = [urllib.request.HTTPCookieProcessor(cj)]
|
||||||
|
if proxy:
|
||||||
|
handlers.append(urllib.request.ProxyHandler({'http': proxy, 'https': proxy}))
|
||||||
|
op = urllib.request.build_opener(*handlers)
|
||||||
|
op.addheaders = list(HDRS.items())
|
||||||
|
return op, cj
|
||||||
|
|
||||||
|
|
||||||
|
def wait_magic_token(c, mail_to, tries=18):
|
||||||
|
"""Ждём письмо с magic-ссылкой. ВАЖНО: m.noop() каждый цикл — иначе IMAP не видит новые письма."""
|
||||||
|
m = imaplib.IMAP4_SSL(c['imap_host'])
|
||||||
|
m.login(c['imap_user'], c['imap_pass'])
|
||||||
|
m.select('INBOX')
|
||||||
|
local = mail_to.split('@')[0].lower()
|
||||||
|
url = None
|
||||||
|
for _ in range(tries):
|
||||||
|
m.noop()
|
||||||
|
typ, data = m.search(None, '(FROM "no-reply@jev-ai.pro")')
|
||||||
|
ids = data[0].split()
|
||||||
|
for i in ids[::-1][:15]:
|
||||||
|
typ, msg = m.fetch(i, '(RFC822)')
|
||||||
|
e = email.message_from_bytes(msg[0][1])
|
||||||
|
to = str(e.get('To', '')).lower()
|
||||||
|
# alias: точный тег в To; catchall: весь local-part
|
||||||
|
needle = local.split('+')[-1] if '+' in local else local
|
||||||
|
if needle not in to:
|
||||||
|
continue
|
||||||
|
html = ''
|
||||||
|
for p in e.walk():
|
||||||
|
if p.get_content_type() == 'text/html':
|
||||||
|
html = (p.get_payload(decode=True) or b'').decode('utf-8', 'ignore')
|
||||||
|
mm = re.search(r'href="(https://jev-ai\.pro/auth/magic-link\?token=[^"]+)"', html)
|
||||||
|
if mm:
|
||||||
|
url = mm.group(1)
|
||||||
|
break
|
||||||
|
if url:
|
||||||
|
break
|
||||||
|
time.sleep(6)
|
||||||
|
m.logout()
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
def register_one(c, proxy=None):
|
||||||
|
mail = make_email(c)
|
||||||
|
op, cj = opener(proxy)
|
||||||
|
s, b = http_call(op, 'POST', BASE + '/api/auth/magic-link', {'email': mail, 'callbackUrl': '/'})
|
||||||
|
if s != 200:
|
||||||
|
return {'email': mail, 'error': f'magic-link {s} {b[:100]}'}
|
||||||
|
url = wait_magic_token(c, mail)
|
||||||
|
if not url:
|
||||||
|
return {'email': mail, 'error': 'письмо не пришло за ~2 мин'}
|
||||||
|
s, b = http_call(op, 'GET', url)
|
||||||
|
if s != 200:
|
||||||
|
return {'email': mail, 'error': f'verify {s}'}
|
||||||
|
ck = '; '.join(f'{k.name}={k.value}' for k in cj)
|
||||||
|
name = 'k' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
|
||||||
|
s, b = http_call(op, 'POST', BASE + '/api/api-keys', {'name': name}, cookie_str=ck)
|
||||||
|
if s != 200:
|
||||||
|
return {'email': mail, 'error': f'apikey {s} {b[:100]}'}
|
||||||
|
d = json.loads(b)
|
||||||
|
rec = {'email': mail, 'secret': d['key']['secret'], 'key_id': d['key']['id'],
|
||||||
|
'cookie': ck, 'proxy': proxy or '', 'created': time.time()}
|
||||||
|
with open(ACC_FILE, 'a', encoding='utf-8') as f:
|
||||||
|
f.write(json.dumps(rec) + '\n')
|
||||||
|
with open(KEYS_FILE, 'a', encoding='utf-8') as f:
|
||||||
|
f.write(d['key']['secret'] + '\n')
|
||||||
|
return rec
|
||||||
|
|
||||||
|
|
||||||
|
def load_accounts():
|
||||||
|
if not os.path.exists(ACC_FILE):
|
||||||
|
return []
|
||||||
|
return [json.loads(l) for l in open(ACC_FILE, encoding='utf-8') if l.strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def balance_of(a):
|
||||||
|
h = dict(HDRS)
|
||||||
|
h['Cookie'] = a.get('cookie', '')
|
||||||
|
h.pop('Origin', None)
|
||||||
|
req = urllib.request.Request(BASE + '/api/credit-balance', headers=h)
|
||||||
|
try:
|
||||||
|
r = urllib.request.urlopen(req, timeout=30)
|
||||||
|
return json.loads(r.read().decode()).get('balance')
|
||||||
|
except Exception:
|
||||||
|
return '?'
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_reg(n):
|
||||||
|
c = cfg()
|
||||||
|
pxs = load_proxies(c)
|
||||||
|
ok = 0
|
||||||
|
pi = 0
|
||||||
|
n = int(n)
|
||||||
|
for i in range(n):
|
||||||
|
rec = None
|
||||||
|
# до 3 попыток: каждая со своим прокси (или direct если пула нет)
|
||||||
|
for attempt in range(3):
|
||||||
|
px = None
|
||||||
|
if pxs:
|
||||||
|
# берём следующий прокси, скипая мёртвые (до 6 проверок)
|
||||||
|
for _ in range(6):
|
||||||
|
cand = pxs[pi % len(pxs)]
|
||||||
|
pi += 1
|
||||||
|
if proxy_alive(cand):
|
||||||
|
px = cand
|
||||||
|
break
|
||||||
|
if not px:
|
||||||
|
print(f'[{i+1}/{n}] нет живых прокси в пуле')
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
rec = register_one(c, proxy=px)
|
||||||
|
except Exception as e:
|
||||||
|
rec = {'error': f'EXC {str(e)[:60]} (proxy {px})'}
|
||||||
|
if 'secret' in rec:
|
||||||
|
break
|
||||||
|
if not pxs:
|
||||||
|
break # direct-режим: без пула не ротировать
|
||||||
|
if rec and 'secret' in rec:
|
||||||
|
ok += 1
|
||||||
|
cr = balance_of(rec)
|
||||||
|
print(f'[{i+1}/{n}] OK {rec["email"]} key={rec["secret"][:12]}... credits={cr} proxy={rec.get("proxy") or "direct"}')
|
||||||
|
else:
|
||||||
|
print(f'[{i+1}/{n}] FAIL {rec}')
|
||||||
|
time.sleep(random.uniform(3, 7))
|
||||||
|
print(f'готово: {ok}/{n} аккаунтов, ключи в keys.txt')
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_checkin():
|
||||||
|
total = 0
|
||||||
|
for a in load_accounts():
|
||||||
|
h = dict(HDRS)
|
||||||
|
h['Cookie'] = a.get('cookie', '')
|
||||||
|
h['Content-Type'] = 'application/json'
|
||||||
|
req = urllib.request.Request(BASE + '/api/daily-checkin', data=b'{}', headers=h, method='POST')
|
||||||
|
try:
|
||||||
|
r = urllib.request.urlopen(req, timeout=30)
|
||||||
|
got = json.loads(r.read().decode()).get('creditsAwarded', '?')
|
||||||
|
total += 1
|
||||||
|
print(f'{a["email"]}: +{got}')
|
||||||
|
except urllib.error.HTTPError as ex:
|
||||||
|
print(f'{a["email"]}: {ex.code} (уже заклеймлено сегодня)' if ex.code == 409 else f'{a["email"]}: {ex.code}')
|
||||||
|
except Exception as ex:
|
||||||
|
print(f'{a["email"]}: ERR {ex}')
|
||||||
|
print(f'check-in: {total} аккаунтов')
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_status():
|
||||||
|
accs = load_accounts()
|
||||||
|
tot = 0
|
||||||
|
for a in accs:
|
||||||
|
b = balance_of(a)
|
||||||
|
if isinstance(b, int):
|
||||||
|
tot += b
|
||||||
|
print(f'{a["email"]} | key {a["secret"][:12]}... | credits {b}')
|
||||||
|
print(f'ИТОГО: {len(accs)} аккаунтов, {tot} кредитов')
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_daily():
|
||||||
|
cmd_checkin()
|
||||||
|
cmd_reg(2)
|
||||||
|
cmd_status()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
cmd = sys.argv[1] if len(sys.argv) > 1 else 'status'
|
||||||
|
if cmd == 'reg':
|
||||||
|
cmd_reg(sys.argv[2] if len(sys.argv) > 2 else 1)
|
||||||
|
elif cmd == 'checkin':
|
||||||
|
cmd_checkin()
|
||||||
|
elif cmd == 'status':
|
||||||
|
cmd_status()
|
||||||
|
elif cmd == 'daily':
|
||||||
|
cmd_daily()
|
||||||
|
else:
|
||||||
|
print(__doc__)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"imap_host": "imap.gmail.com",
|
||||||
|
"imap_user": "yourmail@gmail.com",
|
||||||
|
"imap_pass": "your-16-char-app-password",
|
||||||
|
"email_mode": "alias",
|
||||||
|
"email_domain": "",
|
||||||
|
"proxies_file": ""
|
||||||
|
}
|
||||||
+196
@@ -0,0 +1,196 @@
|
|||||||
|
"""JEV Dashboard — zero-dependency web panel (Python stdlib only).
|
||||||
|
|
||||||
|
python dashboard.py # -> http://localhost:8590
|
||||||
|
|
||||||
|
Paste your sk_jev-ai_... token in the browser (kept in process memory only),
|
||||||
|
list models, run test decisions, bench latency, manage a key pool.
|
||||||
|
AlStack: https://t.me/AlStack
|
||||||
|
"""
|
||||||
|
import json, time, threading
|
||||||
|
from http.server import HTTPServer, BaseHTTPRequestHandler
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
PORT = 8590
|
||||||
|
BASE = 'https://jev-ai.pro/api/v1'
|
||||||
|
POOL = [] # keys added via dashboard (memory only)
|
||||||
|
POOL_LOCK = threading.Lock()
|
||||||
|
|
||||||
|
PAGE = """<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>JEV Decision Hub</title>
|
||||||
|
<style>
|
||||||
|
:root{--bg:#0d0b14;--card:#171326;--acc:#7c47ff;--txt:#e8e4f5;--mut:#8f899c;--ok:#3ddc84;--err:#ff5d5d}
|
||||||
|
*{box-sizing:border-box;margin:0;padding:0}
|
||||||
|
body{background:var(--bg);color:var(--txt);font:14px/1.6 'Segoe UI',system-ui,sans-serif;padding:24px}
|
||||||
|
.wrap{max-width:860px;margin:0 auto}
|
||||||
|
h1{font-size:22px;margin-bottom:4px}h1 b{color:var(--acc)}
|
||||||
|
.sub{color:var(--mut);margin-bottom:20px;font-size:13px}
|
||||||
|
.card{background:var(--card);border:1px solid #241d3d;border-radius:12px;padding:18px;margin-bottom:16px}
|
||||||
|
.card h2{font-size:15px;margin-bottom:10px;color:var(--acc)}
|
||||||
|
input,textarea,select{width:100%;background:#0f0c1a;border:1px solid #2d2450;color:var(--txt);border-radius:8px;padding:9px 11px;font:13px/1.5 'Consolas',monospace;margin-bottom:8px}
|
||||||
|
textarea{min-height:110px;resize:vertical}
|
||||||
|
button{background:var(--acc);color:#fff;border:0;border-radius:8px;padding:9px 18px;font-weight:600;cursor:pointer;margin-right:8px}
|
||||||
|
button:hover{filter:brightness(1.15)}
|
||||||
|
pre{background:#0f0c1a;border:1px solid #2d2450;border-radius:8px;padding:12px;overflow-x:auto;font-size:12px;white-space:pre-wrap;word-break:break-word}
|
||||||
|
.ok{color:var(--ok)}.err{color:var(--err)}.mut{color:var(--mut)}
|
||||||
|
.row{display:flex;gap:16px;flex-wrap:wrap}.row>.card{flex:1;min-width:260px}
|
||||||
|
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||||
|
td,th{padding:6px 8px;border-bottom:1px solid #241d3d;text-align:left}
|
||||||
|
.foot{text-align:center;color:var(--mut);margin-top:24px;font-size:13px}
|
||||||
|
.foot a{color:var(--acc);text-decoration:none;font-weight:700}
|
||||||
|
</style></head><body><div class="wrap">
|
||||||
|
<h1><b>JEV</b> Decision Hub</h1>
|
||||||
|
<div class="sub">decision-layer API: state + typed questions → calibrated answers in ~0.3s | free credits: <a href="https://jev-ai.pro" style="color:var(--acc)">jev-ai.pro</a> magic-link login</div>
|
||||||
|
|
||||||
|
<div class="card"><h2>1. Токен</h2>
|
||||||
|
<input id="tok" type="password" placeholder="sk_jev-ai_... (хранится только в памяти процесса)">
|
||||||
|
<button onclick="addPool()">+ в пул</button><button onclick="testTok()">проверить</button>
|
||||||
|
<div id="poolinfo" class="mut"></div></div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<div class="card"><h2>2. Модели</h2><button onclick="listModels()">GET /models</button><div id="models"></div></div>
|
||||||
|
<div class="card"><h2>3. Бенч</h2><button onclick="bench()">5 вызовов</button><div id="bench"></div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card"><h2>4. Тест решения</h2>
|
||||||
|
<label class="mut">state</label>
|
||||||
|
<textarea id="state">Клиент: мне пришло два списания за подписку, тикет без ответа 4 дня, хочу возврат или ухожу к конкурентам.</textarea>
|
||||||
|
<label class="mut">questions (JSON)</label>
|
||||||
|
<textarea id="qs">{"refund":{"type":"noul","instructions":"Просит ли клиент возврат?"},"team":{"type":"choice","instructions":"Куда маршрутизировать?","criteria":{"billing":"возвраты и списания","technical":"ошибки и интеграции","sales":"вопросы о планах"}},"anger":{"type":"score","instructions":"Насколько клиент зол?","criteria":["спокоен","раздражён","зол"]}}</textarea>
|
||||||
|
<button onclick="runDecision()">POST /systemone</button><span id="lat" class="mut"></span>
|
||||||
|
<pre id="out">ответ появится здесь</pre></div>
|
||||||
|
|
||||||
|
<div class="foot">👻 <a href="https://t.me/AlStack">иишко</a> — каталоги халявы, AI-тулзов и абюза</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
const $=id=>document.getElementById(id);
|
||||||
|
async function api(path,body){const r=await fetch(path,{method:body?'POST':'GET',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined});return r.json();}
|
||||||
|
async function testTok(){const d=await api('/test',{token:$('tok').value.trim()});$('out').innerHTML=d.ok?'<span class="ok">токен рабочий, моделей: '+d.models+'</span>':'<span class="err">'+d.error+'</span>';}
|
||||||
|
async function addPool(){const d=await api('/pool_add',{token:$('tok').value.trim()});$('poolinfo').innerHTML=d.info;$('tok').value='';}
|
||||||
|
async function listModels(){const d=await api('/models',{token:$('tok').value.trim()});if(!d.ok){$('models').innerHTML='<span class="err">'+d.error+'</span>';return;}
|
||||||
|
let h='<table><tr><th>модель</th><th>x</th></tr>';d.models.forEach(m=>h+='<tr><td>'+m.name+'</td><td>'+(m.billing?m.billing.multiplier:1)+'</td></tr>');$('models').innerHTML=h+'</table>';}
|
||||||
|
async function bench(){const d=await api('/bench',{token:$('tok').value.trim()});$('bench').innerHTML=d.ok?('<span class="ok">avg '+d.avg+'s</span><div class="mut">min '+d.min+'s / max '+d.max+'s / ключей в пуле: '+d.pool+'</div>'):'<span class="err">'+d.error+'</span>';}
|
||||||
|
async function runDecision(){let qs;try{qs=JSON.parse($('qs').value);}catch(e){$('out').innerHTML='<span class="err">questions: невалидный JSON</span>';return;}
|
||||||
|
$('lat').textContent='выполняется...';const t0=Date.now();
|
||||||
|
const d=await api('/decide',{token:$('tok').value.trim(),state:$('state').value,questions:qs});
|
||||||
|
$('lat').innerHTML='<span class="ok">'+((Date.now()-t0)/1000).toFixed(2)+'s</span>';
|
||||||
|
$('out').textContent=JSON.stringify(d,null,2);}
|
||||||
|
api('/pool_info').then(d=>$('poolinfo').innerHTML=d.info);
|
||||||
|
</script></body></html>"""
|
||||||
|
|
||||||
|
|
||||||
|
def jev_call(path, key, body=None):
|
||||||
|
h = {'Content-Type': 'application/json', 'Authorization': 'Bea' + 'rer ' + key}
|
||||||
|
req = urllib.request.Request(BASE + path,
|
||||||
|
data=json.dumps(body).encode() if body is not None else None,
|
||||||
|
headers=h, method='POST' if body is not None else 'GET')
|
||||||
|
try:
|
||||||
|
r = urllib.request.urlopen(req, timeout=60)
|
||||||
|
return r.status, json.loads(r.read().decode())
|
||||||
|
except urllib.error.HTTPError as ex:
|
||||||
|
return ex.code, {'error': ex.read().decode('utf-8', 'ignore')[:200]}
|
||||||
|
except Exception as ex:
|
||||||
|
return 0, {'error': str(ex)[:200]}
|
||||||
|
|
||||||
|
|
||||||
|
def pick_key(token):
|
||||||
|
if token:
|
||||||
|
return [token]
|
||||||
|
with POOL_LOCK:
|
||||||
|
return list(POOL)
|
||||||
|
|
||||||
|
|
||||||
|
class H(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, *a):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def _send(self, obj, code=200, html=False):
|
||||||
|
b = obj.encode() if isinstance(obj, str) else json.dumps(obj).encode()
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header('Content-Type', 'text/html; charset=utf-8' if html else 'application/json')
|
||||||
|
self.send_header('Content-Length', str(len(b)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(b)
|
||||||
|
|
||||||
|
def _body(self):
|
||||||
|
n = int(self.headers.get('Content-Length', 0))
|
||||||
|
return json.loads(self.rfile.read(n) or b'{}')
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
p = urlparse(self.path).path
|
||||||
|
if p == '/':
|
||||||
|
self._send(PAGE, html=True)
|
||||||
|
elif p == '/pool_info':
|
||||||
|
with POOL_LOCK:
|
||||||
|
n = len(POOL)
|
||||||
|
self._send({'info': f'ключей в пуле: {n}' + (f' ({", ".join(k[:12] + "..." for k in POOL)})' if n else ' — добавь токен выше')})
|
||||||
|
else:
|
||||||
|
self._send({'error': 'not found'}, 404)
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
p = urlparse(self.path).path
|
||||||
|
b = self._body()
|
||||||
|
tok = (b.get('token') or '').strip()
|
||||||
|
if p == '/test':
|
||||||
|
keys = pick_key(tok)
|
||||||
|
if not keys:
|
||||||
|
return self._send({'ok': False, 'error': 'нет токена'})
|
||||||
|
s, d = jev_call('/models/', keys[0])
|
||||||
|
return self._send({'ok': s == 200, 'models': len(d.get('models', [])) if s == 200 else 0,
|
||||||
|
'error': '' if s == 200 else f'{s}: {d}'})
|
||||||
|
if p == '/pool_add':
|
||||||
|
if not tok.startswith('sk_'):
|
||||||
|
return self._send({'ok': False, 'info': 'ключ должен начинаться с sk_'})
|
||||||
|
with POOL_LOCK:
|
||||||
|
if tok not in POOL:
|
||||||
|
POOL.append(tok)
|
||||||
|
info = f'ключей в пуле: {len(POOL)}'
|
||||||
|
return self._send({'ok': True, 'info': info})
|
||||||
|
if p == '/models':
|
||||||
|
keys = pick_key(tok)
|
||||||
|
if not keys:
|
||||||
|
return self._send({'ok': False, 'error': 'нет токена'})
|
||||||
|
s, d = jev_call('/models/', keys[0])
|
||||||
|
return self._send({'ok': s == 200, 'models': d.get('models', []),
|
||||||
|
'error': '' if s == 200 else f'{s}'})
|
||||||
|
if p == '/bench':
|
||||||
|
keys = pick_key(tok)
|
||||||
|
if not keys:
|
||||||
|
return self._send({'ok': False, 'error': 'нет токена'})
|
||||||
|
body = {'model': 'jev-latest', 'state': 'bench ping',
|
||||||
|
'questions': {'ok': {'type': 'noul', 'instructions': 'Is this a bench call?'}}}
|
||||||
|
ts, i = [], 0
|
||||||
|
for _ in range(5):
|
||||||
|
key = keys[i % len(keys)]
|
||||||
|
i += 1
|
||||||
|
t0 = time.time()
|
||||||
|
s, d = jev_call('/systemone', key, body)
|
||||||
|
if s == 200:
|
||||||
|
ts.append(time.time() - t0)
|
||||||
|
if not ts:
|
||||||
|
return self._send({'ok': False, 'error': f'все вызовы упали: {s} {d}'})
|
||||||
|
return self._send({'ok': True, 'avg': f'{sum(ts)/len(ts):.2f}', 'min': f'{min(ts):.2f}',
|
||||||
|
'max': f'{max(ts):.2f}', 'pool': len(keys)})
|
||||||
|
if p == '/decide':
|
||||||
|
keys = pick_key(tok)
|
||||||
|
if not keys:
|
||||||
|
return self._send({'ok': False, 'error': 'нет токена'})
|
||||||
|
body = {'model': b.get('model', 'jev-latest'), 'state': b.get('state', ''),
|
||||||
|
'questions': b.get('questions', {})}
|
||||||
|
last = None
|
||||||
|
for key in keys:
|
||||||
|
s, d = jev_call('/systemone', key, body)
|
||||||
|
if s == 200:
|
||||||
|
d['_key'] = key[:12] + '...'
|
||||||
|
return self._send(d)
|
||||||
|
last = f'{s}: {d}'
|
||||||
|
if s not in (401, 402, 403):
|
||||||
|
break
|
||||||
|
return self._send({'ok': False, 'error': last or 'нет ключей'})
|
||||||
|
self._send({'error': 'not found'}, 404)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print(f'JEV Dashboard -> http://localhost:{PORT} (AlStack: https://t.me/AlStack)')
|
||||||
|
HTTPServer(('127.0.0.1', PORT), H).serve_forever()
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Пример: супервизор кодинг-агента (паттерн thruwire/foreman).
|
||||||
|
После каждого шага агента Jev решает: continue / retry / verify / stop."""
|
||||||
|
import sys, os
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
from jev_client import decide
|
||||||
|
|
||||||
|
CRITERIA = {
|
||||||
|
'continue': 'Шаг успешен, план выполняется — давай агенту следующий шаг',
|
||||||
|
'retry': 'Шаг упал по исправимой причине (таймаут, синтаксис, flaky-тест) — повтори с корректировкой',
|
||||||
|
'verify': 'Результат неоднозначен — сначала проверь (тесты/линтер/запуск), потом решай',
|
||||||
|
'stop': 'Агент зациклился, исчерпал бюджет или задача не сходится — останови и эскалируй человеку',
|
||||||
|
}
|
||||||
|
|
||||||
|
def supervise(goal: str, step_log: str, attempt: int) -> dict:
|
||||||
|
r = decide(state=f"Agent goal: {goal}\nAttempt #{attempt}\nLatest step log:\n{step_log[-4000:]}",
|
||||||
|
questions={
|
||||||
|
'next': {'type': 'choice', 'instructions': 'What should the supervising layer do next?',
|
||||||
|
'criteria': CRITERIA},
|
||||||
|
'stuck': {'type': 'noul', 'instructions': 'Is the agent stuck in a loop (repeating same failing action)?'},
|
||||||
|
'progress': {'type': 'score', 'instructions': 'Rate overall progress toward the goal',
|
||||||
|
'criteria': ['no progress', 'minor', 'halfway', 'mostly done', 'done']},
|
||||||
|
})
|
||||||
|
a = r['answers']
|
||||||
|
return {'next': a['next']['choice'], 'stuck': a['stuck']['noul'] > 0.5,
|
||||||
|
'progress': a['progress']['score'], 'confidence': a['next'].get('confidence')}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
log = 'ran pytest: 3 failed, 12 passed. Failure: AssertionError in test_parse_config (same as attempt 1 and 2)'
|
||||||
|
print(supervise('починить парсер конфига', log, attempt=3))
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Пример: роутер задач на модели через Jev.
|
||||||
|
Дешёвая/умная/визуальная модель выбирается одним вызовом вместо прогона через LLM."""
|
||||||
|
import sys, os
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
from jev_client import decide
|
||||||
|
|
||||||
|
CRITERIA = {
|
||||||
|
'cheap': 'Простые запросы: перевод коротких текстов, классификация, извлечение, шаблоны, chitchat',
|
||||||
|
'smart': 'Сложные запросы: рассуждения, математика, код-ревью, планирование, многошаговые задачи',
|
||||||
|
'vision': 'Запрос содержит изображения, скриншоты, PDF со схемами, или требует визуального понимания',
|
||||||
|
}
|
||||||
|
|
||||||
|
def route(task: str) -> dict:
|
||||||
|
r = decide(state=f"User task: {task}", questions={
|
||||||
|
'model': {'type': 'choice', 'instructions': 'Which model tier should handle this task?',
|
||||||
|
'criteria': CRITERIA},
|
||||||
|
'needs_tools': {'type': 'noul', 'instructions': 'Does this task require tool/web access?'},
|
||||||
|
})
|
||||||
|
a = r['answers']
|
||||||
|
return {'model': a['model']['choice'],
|
||||||
|
'confidence': a['model'].get('confidence'),
|
||||||
|
'needs_tools': a['needs_tools']['noul'] > 0.5}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
for t in ['переведи hello world на русский',
|
||||||
|
'найди баг в этом async коде и объясни race condition',
|
||||||
|
'что на этом скриншоте ошибки? [image attached]']:
|
||||||
|
res = route(t)
|
||||||
|
print(f"{res['model']:7} conf={res['confidence']:.2f} tools={res['needs_tools']} | {t[:50]}")
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"""Пример: спам-модерация постов/сообщений через Jev.
|
||||||
|
Порог по noul + действие через choice. Один вызов на пост, ~1 кредит."""
|
||||||
|
import sys, os
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
from jev_client import decide
|
||||||
|
|
||||||
|
SPAM_THRESHOLD = 0.7
|
||||||
|
|
||||||
|
def moderate(post_text: str, author_meta: str = '') -> dict:
|
||||||
|
state = f"Post: {post_text}\nAuthor: {author_meta or 'unknown'}"
|
||||||
|
r = decide(state=state, questions={
|
||||||
|
'spam': {'type': 'noul', 'instructions': 'Is this post spam/scam/ads for grey services?'},
|
||||||
|
'nsfw': {'type': 'noul', 'instructions': 'Does this contain NSFW content?'},
|
||||||
|
'action': {'type': 'choice', 'instructions': 'Choose moderation action',
|
||||||
|
'criteria': {'ban': 'ban author and delete', 'delete': 'delete post only',
|
||||||
|
'flag': 'flag for human review', 'keep': 'leave as is'}},
|
||||||
|
})
|
||||||
|
a = r['answers']
|
||||||
|
verdict = 'BLOCK' if a['spam']['noul'] >= SPAM_THRESHOLD or a['nsfw']['noul'] >= SPAM_THRESHOLD else 'PASS'
|
||||||
|
return {'verdict': verdict, 'spam': a['spam']['noul'], 'nsfw': a['nsfw']['noul'],
|
||||||
|
'action': a['action']['choice'], 'confidence': a['action'].get('confidence')}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
samples = [
|
||||||
|
'Продаю аккаунты Telegram с историей, дешево, писать в лс @spamlord',
|
||||||
|
'Кто-нибудь пробовал jev-ai.pro? Как вам качество решений по сравнению с GPT?',
|
||||||
|
'СКАЧАЙ КРЯК БЕЗ СМС >>> http://bit.ly/fr3e-win',
|
||||||
|
]
|
||||||
|
for s in samples:
|
||||||
|
res = moderate(s)
|
||||||
|
print(f"{res['verdict']:5} spam={res['spam']:.2f} action={res['action']:7} | {s[:60]}")
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Пример: трейдинг-сигнал buy/sell/wait с confidence-гейтом.
|
||||||
|
НЕ финансовый совет — демонстрация паттерна (см. jarrodwatts/jev-trader)."""
|
||||||
|
import sys, os
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
from jev_client import decide
|
||||||
|
|
||||||
|
MIN_CONFIDENCE = 0.6 # ниже порога -> всегда wait
|
||||||
|
|
||||||
|
def signal(snapshot: dict) -> dict:
|
||||||
|
"""snapshot: {'pair':'BTC/USDT','price':...,'change_24h':...,'rsi':...,'news':'...'}"""
|
||||||
|
r = decide(state=f"Market snapshot: {snapshot}", questions={
|
||||||
|
'action': {'type': 'choice', 'instructions': 'Decide the next trade action for a short-term position',
|
||||||
|
'criteria': {'buy': 'momentum and sentiment favour entry now',
|
||||||
|
'sell': 'take profit / cut risk now',
|
||||||
|
'wait': 'not enough edge, stay flat'}},
|
||||||
|
'risk': {'type': 'score', 'instructions': 'How risky is entering right now?',
|
||||||
|
'criteria': ['low', 'medium', 'high', 'extreme']},
|
||||||
|
'volatile': {'type': 'noul', 'instructions': 'Is the market unusually volatile per this snapshot?'},
|
||||||
|
})
|
||||||
|
a = r['answers']
|
||||||
|
act = a['action']['choice'] if a['action'].get('confidence', 0) >= MIN_CONFIDENCE else 'wait'
|
||||||
|
return {'action': act, 'confidence': a['action'].get('confidence'),
|
||||||
|
'risk': a['risk']['score'], 'volatile': a['volatile']['noul']}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
snap = {'pair': 'BTC/USDT', 'price': 118420, 'change_24h': '-3.8%', 'rsi': 31,
|
||||||
|
'news': 'ETF outflows 2nd day, macro risk-off, no major liquidation cascade yet'}
|
||||||
|
print(signal(snap))
|
||||||
+123
@@ -0,0 +1,123 @@
|
|||||||
|
"""JEV decision client with key-pool rotation. Zero dependencies (stdlib only).
|
||||||
|
|
||||||
|
Setup:
|
||||||
|
echo "sk_jev-ai_XXXX" > keys.txt # one key per line
|
||||||
|
(or set env JEV_API_KEY for a single key)
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
from jev_client import decide
|
||||||
|
r = decide(state="...", questions={...})
|
||||||
|
|
||||||
|
CLI:
|
||||||
|
python jev_client.py models
|
||||||
|
python jev_client.py run '{"state":"...","questions":{...}}'
|
||||||
|
python jev_client.py bench [N]
|
||||||
|
|
||||||
|
Free credits: jev-ai.pro -> magic-link login -> 20 welcome credits + daily check-in.
|
||||||
|
Docs: README.md | AlStack: https://t.me/AlStack
|
||||||
|
"""
|
||||||
|
import json, os, sys, time, itertools, urllib.request
|
||||||
|
|
||||||
|
# Windows-консоль (cp866/cp1251): кириллица в print падает UnicodeEncodeError
|
||||||
|
try:
|
||||||
|
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
BASE = 'https://jev-ai.pro/api/v1'
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
KEYS_FILE = os.path.join(HERE, 'keys.txt')
|
||||||
|
_rr = itertools.count()
|
||||||
|
|
||||||
|
|
||||||
|
def load_keys():
|
||||||
|
keys = []
|
||||||
|
env = os.environ.get('JEV_API_KEY')
|
||||||
|
if env:
|
||||||
|
keys.append(env.strip())
|
||||||
|
if os.path.exists(KEYS_FILE):
|
||||||
|
for line in open(KEYS_FILE):
|
||||||
|
line = line.strip()
|
||||||
|
if line and not line.startswith('#'):
|
||||||
|
keys.append(line)
|
||||||
|
if not keys:
|
||||||
|
raise SystemExit('no keys: put sk_jev-ai_... into keys.txt or set JEV_API_KEY')
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def _req(path, key, body=None):
|
||||||
|
h = {'Content-Type': 'application/json',
|
||||||
|
'Authorization': 'Bea' + 'rer ' + key}
|
||||||
|
req = urllib.request.Request(BASE + path,
|
||||||
|
data=json.dumps(body).encode() if body is not None else None,
|
||||||
|
headers=h, method='POST' if body is not None else 'GET')
|
||||||
|
try:
|
||||||
|
r = urllib.request.urlopen(req, timeout=60)
|
||||||
|
return r.status, json.loads(r.read().decode())
|
||||||
|
except urllib.error.HTTPError as ex:
|
||||||
|
raw = ex.read().decode('utf-8', 'ignore')
|
||||||
|
try:
|
||||||
|
return ex.code, json.loads(raw)
|
||||||
|
except Exception:
|
||||||
|
return ex.code, {'error': raw[:300]}
|
||||||
|
except (urllib.error.URLError, TimeoutError, OSError) as ex:
|
||||||
|
return 599, {'error': f'network: {str(ex)[:180]}'} # таймаут/сеть -> retryable
|
||||||
|
|
||||||
|
|
||||||
|
def decide(state, questions, model='jev-latest', max_tries=None):
|
||||||
|
"""Один вызов-решение. Ротация ключей на 401/402/403; ретраи на 5xx/522/599 (транзиент)."""
|
||||||
|
keys = load_keys()
|
||||||
|
n = max_tries or len(keys)
|
||||||
|
start = next(_rr) % len(keys)
|
||||||
|
last = None
|
||||||
|
retries = 0
|
||||||
|
k = 0
|
||||||
|
while k < n:
|
||||||
|
key = keys[(start + k) % len(keys)]
|
||||||
|
s, d = _req('/systemone', key, {'model': model, 'state': state, 'questions': questions})
|
||||||
|
if s == 200:
|
||||||
|
d['_key'] = key[:12] + '...'
|
||||||
|
return d
|
||||||
|
last = (s, d)
|
||||||
|
if s in (401, 402, 403): # мёртвый/пустой ключ -> следующий
|
||||||
|
k += 1
|
||||||
|
continue
|
||||||
|
if (s >= 500 or s == 599) and retries < 2: # 522/5xx/таймаут -> повторить этим же ключом
|
||||||
|
retries += 1
|
||||||
|
time.sleep(3)
|
||||||
|
continue
|
||||||
|
raise RuntimeError(f'jev error {s}: {json.dumps(d)[:300]}')
|
||||||
|
raise RuntimeError(f'all {n} keys exhausted; last={last}')
|
||||||
|
|
||||||
|
|
||||||
|
def models():
|
||||||
|
s, d = _req('/models/', load_keys()[0])
|
||||||
|
if s != 200:
|
||||||
|
raise RuntimeError(f'models {s}: {d}')
|
||||||
|
return d.get('models', d)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
cmd = sys.argv[1] if len(sys.argv) > 1 else 'models'
|
||||||
|
if cmd == 'models':
|
||||||
|
for m in models():
|
||||||
|
bill = m.get('billing', {})
|
||||||
|
print(f"- {m['name']}: {m.get('description','')[:90]} (x{bill.get('multiplier',1)})")
|
||||||
|
elif cmd == 'run':
|
||||||
|
d = json.loads(sys.argv[2])
|
||||||
|
t0 = time.time()
|
||||||
|
r = decide(d['state'], d['questions'], d.get('model', 'jev-latest'))
|
||||||
|
print(json.dumps(r, indent=2, ensure_ascii=False))
|
||||||
|
print(f'latency: {time.time()-t0:.2f}s | key: {r.get("_key")}')
|
||||||
|
elif cmd == 'bench':
|
||||||
|
n = int(sys.argv[2]) if len(sys.argv) > 2 else 5
|
||||||
|
body = {'state': 'Customer: billed twice, no reply for 4 days, wants refund or leaves.',
|
||||||
|
'questions': {'refund': {'type': 'noul', 'instructions': 'Asking for money back?'}}}
|
||||||
|
ts = []
|
||||||
|
for i in range(n):
|
||||||
|
t0 = time.time()
|
||||||
|
decide(body['state'], body['questions'])
|
||||||
|
ts.append(time.time() - t0)
|
||||||
|
print(f'{n} calls: min {min(ts):.2f}s / avg {sum(ts)/len(ts):.2f}s / max {max(ts):.2f}s')
|
||||||
|
else:
|
||||||
|
print(__doc__)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# Скопируй в keys.txt (один ключ на строку). Ключ создается на jev-ai.pro -> Settings -> API Keys
|
||||||
|
# sk_jev-ai_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# один http-прокси на строку, например из бесплатных списков:
|
||||||
|
# http://1.2.3.4:8080
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# jev-decision-hub — stdlib only (urllib/imaplib/http.server). No pip deps required.
|
||||||
Reference in New Issue
Block a user