File size: 6,210 Bytes
e7b8e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# ==========================================================
#                  MODULES / CLIENT.PY
#   Клиент Gemini API с умной ротацией ключей и фильтрацией ошибок
# ==========================================================

import re
import requests
import config

def get_all_api_keys() -> list[str]:
    raw = getattr(config, "API_KEY", [])
    if isinstance(raw, list):
        keys = [str(k).strip() for k in raw if str(k).strip()]
        if keys:
            return keys
    elif isinstance(raw, str) and raw.strip():
        return [raw.strip()]
    raise ValueError("Задайте переменную GEMINI_API_KEY.")

def extract_code_block(text: str) -> str:
    text = text.strip()
    match = re.search(r"```(?:python|json)?\s*([\s\S]*?)\s*```", text, flags=re.IGNORECASE)
    if match:
        return match.group(1).strip()
    clean = re.sub(r"^```(?:python|json)?\s*", "", text, flags=re.IGNORECASE)
    clean = re.sub(r"\s*```$", "", clean).strip()
    return clean

def is_google_side_error(status_code: int, response_text: str) -> bool:
    """Определяет, относится ли ошибка к стороне Google/Ключа или это локальная ошибка."""
    if status_code in (429, 500, 502, 503, 504, 524):
        return True
    if status_code == 403:
        # Исчерпан лимит или ключ заблокирован
        return True
    if status_code == 400:
        err_lower = response_text.lower()
        if any(w in err_lower for w in ["api_key_invalid", "key expired", "api key not valid", "quota", "resource_exhausted"]):
            return True
    return False

def call_gemini(system_prompt: str, user_prompt: str, model: str = None, thinking: bool = True, images: list = None) -> str:
    keys = get_all_api_keys()
    selected_model = model or getattr(config, "MODEL_NAME", "gemini-3.5-flash-lite")
    proxy_url = getattr(config, "PROXY_URL", "").strip()
    base_url = proxy_url.rstrip("/") if proxy_url else "https://generativelanguage.googleapis.com"
    proxies = getattr(config, "PROXIES", None)

    parts = [{"text": f"{system_prompt}\n\nUSER REQUEST: {user_prompt}"}]

    if images and isinstance(images, list):
        for img in images[:10]:
            if isinstance(img, dict) and "data" in img and "mime_type" in img:
                parts.append({
                    "inline_data": {
                        "mime_type": img["mime_type"],
                        "data": img["data"]
                    }
                })

    payload = {
        "contents": [{"parts": parts}],
        "generationConfig": {
            "temperature": 0.7,
            "maxOutputTokens": 65536
        }
    }

    if thinking:
        payload["generationConfig"]["thinkingConfig"] = {"thinkingLevel": "medium"}
        print(f"[+] [Gemini API] Модель: {selected_model} | 🧠 Thinking: ВКЛ")
    else:
        print(f"[+] [Gemini API] Модель: {selected_model} | ⚡ Thinking: ВЫКЛ")

    last_google_error = ""

    for index, key in enumerate(keys):
        print(f"[*] Попытка запроса с ключом #{index + 1}/{len(keys)}")
        url = f"{base_url}/v1beta/models/{selected_model}:generateContent"

        try:
            res = requests.post(
                url,
                json=payload,
                headers={"Content-Type": "application/json; charset=utf-8", "x-goog-api-key": key},
                proxies=proxies,
                timeout=120
            )
        except requests.exceptions.Timeout:
            print(f"[!] Ключ #{index + 1}: Таймаут соединения с сервером Google.")
            last_google_error = "Таймаут соединения с Gemini API"
            continue
        except requests.exceptions.RequestException as e:
            # Ошибка локального сетевого стека или DNS клиента
            raise RuntimeError(f"Локальная сетевая ошибка соединения: {type(e).__name__}")

        # Успешный ответ
        if res.status_code == 200:
            data = res.json()
            candidates = data.get("candidates", [])
            if not candidates:
                raise RuntimeError("Gemini API вернул ответ, но список 'candidates' пуст.")

            cand_parts = candidates[0].get("content", {}).get("parts", [])
            text = "".join(p.get("text", "") for p in cand_parts if not p.get("thought", False))
            if not text and cand_parts:
                text = cand_parts[-1].get("text", "")

            clean = extract_code_block(text)
            if not clean:
                raise RuntimeError("Не удалось извлечь код из ответа модели.")

            return clean

        # Проверяем причину ошибки
        err_text = res.text
        if is_google_side_error(res.status_code, err_text):
            try:
                err_msg = res.json().get("error", {}).get("message", err_text[:200])
            except Exception:
                err_msg = err_text[:200]
            print(f"[!] Ошибка Google (код {res.status_code}): {err_msg}. Переключаемся на следующий ключ...")
            last_google_error = f"Код {res.status_code}: {err_msg}"
            continue
        else:
            # Ошибка вызвана некорректным телом запроса/клиентскими параметрами — прерываем перебор
            try:
                client_err = res.json().get("error", {}).get("message", res.text)
            except Exception:
                client_err = res.text
            raise RuntimeError(f"Фатальная ошибка клиента (код {res.status_code}): {client_err}")

    # Если цикл завершился и все ключи исчерпаны
    raise RuntimeError(f"Все доступные API-ключи ({len(keys)} шт.) исчерпали лимит или недоступны. Последняя ошибка Google: {last_google_error}")