"""FonFin AI Sohbet API v1 — Python standart kütüphane örneği, yayınlanmış SDK değildir.""" import json import re from urllib.error import HTTPError from urllib.request import Request, HTTPRedirectHandler, build_opener class FonFinError(Exception): def __init__(self, status, code, request_id): super().__init__(f"FonFin HTTP {status}: {code}") self.status, self.code, self.request_id = status, code, request_id class _NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None # Authorization başka kökene yönlendirilmez. class FonFin: def __init__(self, api_key, *, sandbox=False, timeout=150): if not isinstance(api_key, str) or not re.fullmatch(r"ffk_chat_[a-z2-7]{8}_[A-Za-z0-9_-]{43}", api_key): raise ValueError("Geçerli Sohbet API anahtarı (ffk_chat_…) gerekli.") self._key = api_key self._base = "https://api.fonfin.ai" + ("/sandbox" if sandbox else "") + "/v1" self._timeout = timeout self._opener = build_opener(_NoRedirect) def _request(self, path, body): headers = {"Authorization": f"Bearer {self._key}", "Accept": "application/json", "Content-Type": "application/json"} request = Request(self._base + path, data=json.dumps(body).encode(), headers=headers) try: response = self._opener.open(request, timeout=self._timeout) except HTTPError as error: response = error with response: request_id = response.headers.get("X-Request-Id") raw = response.read(1048577) if len(raw) > 1048576: raise ValueError("Yanıt 1 MB sınırını aştı.") try: data = json.loads(raw) except (ValueError, UnicodeError): raise FonFinError(response.status, "gecersiz_yanit", request_id) from None if not 200 <= response.status < 300: error = data.get("hata", {}) if isinstance(data, dict) else {} code = error.get("kod", "") if isinstance(error, dict) else "" if not isinstance(code, str) or not re.fullmatch("[a-z_]{1,80}", code): code = "api_hatasi" raise FonFinError(response.status, code, request_id) return {"data": data, "request_id": request_id, "sandbox": response.headers.get("X-FonFin-Sandbox") == "true"} def chat(self, prompt, *, onceki_yanit_id=None): body = {"prompt": prompt} if onceki_yanit_id: body["onceki_yanit_id"] = onceki_yanit_id # sohbeti sürdür (Sandbox desteklemez) return self._request("/chat", body) # import os # client = FonFin(os.environ["FONFIN_API_KEY"], sandbox=True) # result = client.chat("Sandbox bağlantı testi") # Ücretli POST otomatik tekrarlanmaz; timeout işlemin durduğunu kanıtlamaz.