fix(ai-review): tool_choice=none, безопасное извлечение content, убран env-блок (20.09.2026)
This commit is contained in:
@@ -1,7 +1,6 @@
|
|||||||
name: AI Code Review
|
name: AI Code Review
|
||||||
|
|
||||||
on:
|
on:
|
||||||
# Кнопка "Run workflow" в UI Gitea
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
@@ -20,9 +19,4 @@ jobs:
|
|||||||
run: pip install httpx
|
run: pip install httpx
|
||||||
|
|
||||||
- name: Run AI review
|
- name: Run AI review
|
||||||
env:
|
|
||||||
TOGETHER_API_KEY: ${{ secrets.TOGETHER_API_KEY }}
|
|
||||||
BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
|
|
||||||
GITEA_INSTANCE: https://git.filwordspl.com
|
|
||||||
GITEA_REPO: Drobysh/filwordspl-backend
|
|
||||||
run: python scripts/ai_review.py
|
run: python scripts/ai_review.py
|
||||||
|
|||||||
+25
-8
@@ -8,10 +8,12 @@ AI Code Review for Filwords PL Backend
|
|||||||
Запускается через Gitea Actions (workflow_dispatch — вручную из UI).
|
Запускается через Gitea Actions (workflow_dispatch — вручную из UI).
|
||||||
|
|
||||||
(20.09.2026) Первая версия — конвейер без tool-calling, предсказуемо по токенам.
|
(20.09.2026) Первая версия — конвейер без tool-calling, предсказуемо по токенам.
|
||||||
|
(20.09.2026, вечер) Фикс: tool_choice=none, безопасное извлечение content.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -38,6 +40,9 @@ IGNORE_FILES = {"ai_review.py", "conftest.py"}
|
|||||||
# Расширения, которые читаем
|
# Расширения, которые читаем
|
||||||
INCLUDE_EXTENSIONS = {".py"}
|
INCLUDE_EXTENSIONS = {".py"}
|
||||||
|
|
||||||
|
# Максимальный размер одного файла (символов) — большие контент-файлы пропускаем
|
||||||
|
MAX_FILE_SIZE = 100_000
|
||||||
|
|
||||||
|
|
||||||
# ============ Проверка окружения ============
|
# ============ Проверка окружения ============
|
||||||
|
|
||||||
@@ -79,8 +84,8 @@ def collect_code(repo_root: Path) -> str:
|
|||||||
print(f"⚠️ Не прочитал {rel}: {e}", file=sys.stderr)
|
print(f"⚠️ Не прочитал {rel}: {e}", file=sys.stderr)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Пропускаем слишком большие файлы (>100 KB)
|
# Пропускаем слишком большие файлы
|
||||||
if len(content) > 100_000:
|
if len(content) > MAX_FILE_SIZE:
|
||||||
print(f"⚠️ Пропущен большой файл: {rel} ({len(content)} символов)", file=sys.stderr)
|
print(f"⚠️ Пропущен большой файл: {rel} ({len(content)} символов)", file=sys.stderr)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -171,19 +176,32 @@ def call_together(code: str) -> str:
|
|||||||
],
|
],
|
||||||
"max_tokens": MAX_OUTPUT_TOKENS,
|
"max_tokens": MAX_OUTPUT_TOKENS,
|
||||||
"temperature": 0.3,
|
"temperature": 0.3,
|
||||||
|
"tool_choice": "none",
|
||||||
},
|
},
|
||||||
timeout=300.0,
|
timeout=300.0,
|
||||||
)
|
)
|
||||||
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
print(f"❌ Together AI вернул {response.status_code}: {response.text[:500]}", file=sys.stderr)
|
print(f"❌ Together AI вернул {response.status_code}", file=sys.stderr)
|
||||||
|
print(f"Ответ: {response.text[:1000]}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
data = response.json()
|
data = response.json()
|
||||||
result = data["choices"][0]["message"]["content"]
|
|
||||||
|
try:
|
||||||
|
result = data["choices"][0]["message"]["content"]
|
||||||
|
if result is None:
|
||||||
|
raise KeyError("content is None")
|
||||||
|
except (KeyError, IndexError, TypeError) as e:
|
||||||
|
print(f"❌ Неожиданный формат ответа: {e}", file=sys.stderr)
|
||||||
|
print(f"Полный ответ: {data}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
usage = data.get("usage", {})
|
usage = data.get("usage", {})
|
||||||
print(f"✅ Ответ получен. Токены: вход={usage.get('prompt_tokens', 0)}, выход={usage.get('completion_tokens', 0)}")
|
print(
|
||||||
|
f"✅ Ответ получен. Токены: вход={usage.get('prompt_tokens', 0)}, "
|
||||||
|
f"выход={usage.get('completion_tokens', 0)}"
|
||||||
|
)
|
||||||
|
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@@ -192,7 +210,7 @@ def call_together(code: str) -> str:
|
|||||||
|
|
||||||
def create_issue(title: str, body: str) -> str:
|
def create_issue(title: str, body: str) -> str:
|
||||||
"""Создаёт Issue в Gitea, возвращает URL."""
|
"""Создаёт Issue в Gitea, возвращает URL."""
|
||||||
print(f"📝 Создаю Issue в Gitea...")
|
print("📝 Создаю Issue в Gitea...")
|
||||||
|
|
||||||
response = httpx.post(
|
response = httpx.post(
|
||||||
f"{GITEA_INSTANCE}/api/v1/repos/{GITEA_REPO}/issues",
|
f"{GITEA_INSTANCE}/api/v1/repos/{GITEA_REPO}/issues",
|
||||||
@@ -232,7 +250,6 @@ def main() -> None:
|
|||||||
|
|
||||||
analysis = call_together(code)
|
analysis = call_together(code)
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
date_str = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
|
date_str = datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")
|
||||||
title = f"🤖 AI Review: список задач ({date_str})"
|
title = f"🤖 AI Review: список задач ({date_str})"
|
||||||
|
|
||||||
@@ -256,4 +273,4 @@ _Этот Issue создан автоматически. Исправления
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user