Download backend/app/llm/cloud.py from SevdanurGenc/LLM-Automated-Test-Generation-Agent: direct link, hf CLI and curl.
- Browser
- Download file 23.5 kB
-
https://huggingface.co/SevdanurGenc/LLM-Automated-Test-Generation-Agent/resolve/main/backend/app/llm/cloud.py
- Command line
-
hf download hf://SevdanurGenc/LLM-Automated-Test-Generation-Agent/backend/app/llm/cloud.py
-
curl -L -o cloud.py https://huggingface.co/SevdanurGenc/LLM-Automated-Test-Generation-Agent/resolve/main/backend/app/llm/cloud.py
23.5 kB
| """Bulut LLM istemcileri: OpenAI (ve OpenAI uyumlu sunucular) ile Anthropic Claude. | |
| Her iki istemci de akış (stream) kullanır: uzun yanıtlarda zaman aşımı her parçada sıfırlanır, arayüze | |
| ilerleme bildirilir ve iptal yanıtın ortasında da çalışır. Ajanın iç mesaj biçimi (Ollama tarzı: "tool" | |
| rolü + tool_name, kimliksiz tool_calls) her sağlayıcının istediği biçime burada çevrilir. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import re | |
| import time | |
| from typing import Any, Callable, Iterator, Optional | |
| import httpx | |
| from ..config import settings | |
| from .base import LLMClient, LLMResponse, ToolCall, ToolSpec, recover_tool_calls | |
| OPENAI_URL = "https://api.openai.com/v1" | |
| ANTHROPIC_URL = "https://api.anthropic.com" | |
| ANTHROPIC_VERSION = "2023-06-01" | |
| NO_RESULT = "(the result follows in the next message)" | |
| TEXT_TOOLS = ("You can call tools. To call a tool, reply with ONLY a JSON object of the form " | |
| '{"name": "<tool>", "arguments": {...}}. Available tools:\n') | |
| class ProviderError(RuntimeError): | |
| """code: auth | notfound | network | timeout | http — arayüz bunu seçili dile çevirir; | |
| detail: sağlayıcının kendi (genellikle İngilizce) hata iletisi.""" | |
| def __init__(self, message: str, code: str = "http", detail: str = "") -> None: | |
| super().__init__(message) | |
| self.code, self.detail = code, detail | |
| # --------------------------------------------------------------------------- | |
| # Ortak yardımcılar | |
| # --------------------------------------------------------------------------- | |
| def _args(a: Any) -> dict[str, Any]: | |
| if isinstance(a, dict): | |
| return a | |
| if isinstance(a, str) and a.strip(): | |
| try: | |
| v = json.loads(a, strict=False) | |
| return v if isinstance(v, dict) else {} | |
| except json.JSONDecodeError: | |
| return {} | |
| return {} | |
| def normalize(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: | |
| """İç mesajları kimlikli, eşleşmiş bir biçime çevirir. | |
| - Asistanın her araç çağrısına bir kimlik verilir; ardından gelen "tool" mesajları önce ada göre, | |
| yoksa sıraya göre bu kimliklerle eşleştirilir. | |
| - Yanıtsız kalan çağrılar için yer tutucu bir sonuç eklenir (OpenAI ve Anthropic her çağrının | |
| bir sonucu olmasını şart koşar; ajan bazen sonucu düz "user" mesajıyla verir). | |
| - Eşleşecek çağrısı olmayan "tool" mesajı, "user" mesajına çevrilir. | |
| """ | |
| out: list[dict[str, Any]] = [] | |
| pending: list[dict[str, Any]] = [] | |
| n = 0 | |
| def flush() -> None: | |
| for c in pending: | |
| out.append({"role": "tool", "id": c["id"], "name": c["name"], "content": NO_RESULT}) | |
| pending.clear() | |
| for m in messages: | |
| role, content = m.get("role"), m.get("content") or "" | |
| if role == "assistant": | |
| flush() | |
| calls = [] | |
| for tc in m.get("tool_calls") or []: | |
| fn = tc.get("function") if isinstance(tc.get("function"), dict) else tc | |
| n += 1 | |
| calls.append({"id": tc.get("id") or f"call_{n}", "name": fn.get("name", ""), | |
| "arguments": _args(fn.get("arguments"))}) | |
| out.append({"role": "assistant", "content": content, "tool_calls": calls}) | |
| pending = list(calls) | |
| elif role == "tool": | |
| name = m.get("tool_name") or m.get("name") or "" | |
| idx = next((i for i, c in enumerate(pending) if c["name"] == name), 0 if pending else None) | |
| if idx is None: | |
| out.append({"role": "user", "content": f"[{name or 'tool'} result]\n{content}"}) | |
| continue | |
| c = pending.pop(idx) | |
| out.append({"role": "tool", "id": c["id"], "name": c["name"], "content": content}) | |
| else: | |
| flush() | |
| out.append({"role": role or "user", "content": content}) | |
| flush() | |
| return out | |
| def _sse(r: httpx.Response) -> Iterator[dict[str, Any]]: | |
| """Server-Sent Events akışındaki "data:" satırlarını JSON olarak verir.""" | |
| for line in r.iter_lines(): | |
| if not line or not line.startswith("data:"): | |
| continue | |
| data = line[5:].strip() | |
| if data == "[DONE]": | |
| return | |
| try: | |
| yield json.loads(data) | |
| except json.JSONDecodeError: | |
| continue | |
| def _short(body: str) -> str: | |
| try: | |
| j = json.loads(body) | |
| err = j.get("error") | |
| if isinstance(err, dict): | |
| return str(err.get("message") or err)[:400] | |
| if err: | |
| return str(err)[:400] | |
| except (json.JSONDecodeError, AttributeError): | |
| pass | |
| return body[:400] | |
| class _CloudBase(LLMClient): | |
| provider = "cloud" | |
| label = "Cloud" | |
| def __init__(self, model: str, api_key: str, base_url: str, | |
| transport: Optional[httpx.BaseTransport] = None) -> None: | |
| self.model = model | |
| self.api_key = api_key | |
| self.base_url = base_url.rstrip("/") | |
| self._transport = transport | |
| self.on_progress: Optional[Callable[[int, float], None]] = None | |
| def _client(self, timeout: float | httpx.Timeout) -> httpx.Client: | |
| return httpx.Client(timeout=timeout, transport=self._transport) | |
| def _timeout(self) -> httpx.Timeout: | |
| return httpx.Timeout(connect=15.0, read=settings.llm_timeout, write=60.0, pool=15.0) | |
| def _headers(self) -> dict[str, str]: # pragma: no cover - alt sınıflar tanımlar | |
| raise NotImplementedError | |
| def _post_stream(self, url: str, payload: dict[str, Any], | |
| handle: Callable[[httpx.Response], LLMResponse], | |
| fixups: Callable[[dict[str, Any], int, str], bool]) -> LLMResponse: | |
| """İsteği gönderir; geçici hatalarda bekleyip yeniden dener, 400 hatalarında `fixups` ile | |
| isteği düzeltip (ör. desteklenmeyen parametreyi çıkarıp) tekrar dener.""" | |
| attempts, fixes = 0, 0 | |
| while True: | |
| attempts += 1 | |
| try: | |
| with self._client(self._timeout()) as c, \ | |
| c.stream("POST", url, json=payload, headers=self._headers()) as r: | |
| if r.status_code == 200: | |
| return handle(r) | |
| body = r.read().decode(errors="ignore") | |
| status, retry_after = r.status_code, r.headers.get("retry-after") | |
| except httpx.TimeoutException as e: | |
| raise ProviderError(f"{self.label}: model {settings.llm_timeout:.0f} s yanıt vermedi.", "timeout") from e | |
| except httpx.HTTPError as e: | |
| if attempts <= 2: | |
| time.sleep(2 * attempts) | |
| continue | |
| raise ProviderError(f"{self.label} sunucusuna ulaşılamadı ({self.base_url}): {e}", "network", str(e)) from e | |
| if status in (429, 500, 502, 503, 504, 529) and attempts <= 4: | |
| try: | |
| wait = min(60.0, float(retry_after)) if retry_after else 0.0 | |
| except ValueError: | |
| wait = 0.0 | |
| time.sleep(wait or min(60.0, 3.0 * 2 ** (attempts - 1))) | |
| continue | |
| if status == 400 and fixes < 4 and fixups(payload, status, body): | |
| fixes += 1 | |
| continue | |
| if status in (401, 403): | |
| raise ProviderError(f"{self.label}: API anahtarı reddedildi ({status}). {_short(body)}", "auth", _short(body)) | |
| if status == 404: | |
| raise ProviderError(f"{self.label}: model '{self.model}' bulunamadı ya da erişim yok. {_short(body)}", | |
| "notfound", _short(body)) | |
| raise ProviderError(f"{self.label} hata {status}: {_short(body)}", "http", f"{status}: {_short(body)}") | |
| def _tick(self, n: int, start: float, last: list[float]) -> None: | |
| now = time.time() | |
| if self.on_progress and now - last[0] >= 2.0: | |
| last[0] = now | |
| self.on_progress(n, now - start) | |
| if now - start > settings.llm_total_timeout: | |
| raise ProviderError(f"Model yanıtı {settings.llm_total_timeout:.0f} sn içinde tamamlanmadı.") | |
| # Bulut modelleri bu makinenin GPU'sunda çalışmaz. | |
| def processor(self, model: Optional[str] = None) -> None: | |
| return None | |
| # --------------------------------------------------------------------------- | |
| # OpenAI (ve OpenAI uyumlu: LM Studio, OpenRouter, vLLM, Groq ...) | |
| # --------------------------------------------------------------------------- | |
| _OPENAI_SKIP = re.compile(r"audio|realtime|transcribe|tts|image|dall-e|whisper|embedding|moderation|search|" | |
| r"instruct|codex|computer-use|-pro\b|davinci|babbage|sora", re.I) | |
| _OPENAI_CHAT = re.compile(r"^(gpt-|o\d|chatgpt-)", re.I) | |
| class OpenAIClient(_CloudBase): | |
| provider = "openai" | |
| label = "OpenAI" | |
| def __init__(self, model: str, api_key: str, base_url: Optional[str] = None, | |
| transport: Optional[httpx.BaseTransport] = None) -> None: | |
| super().__init__(model, api_key, base_url or OPENAI_URL, transport) | |
| def official(self) -> bool: | |
| return "api.openai.com" in self.base_url | |
| def _headers(self) -> dict[str, str]: | |
| h = {"Content-Type": "application/json"} | |
| if self.api_key: | |
| h["Authorization"] = f"Bearer {self.api_key}" | |
| return h | |
| def to_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: | |
| out: list[dict[str, Any]] = [] | |
| for m in normalize(messages): | |
| if m["role"] == "assistant": | |
| msg: dict[str, Any] = {"role": "assistant", "content": m["content"] or None} | |
| if m["tool_calls"]: | |
| msg["tool_calls"] = [{"id": c["id"], "type": "function", | |
| "function": {"name": c["name"], "arguments": json.dumps(c["arguments"])}} | |
| for c in m["tool_calls"]] | |
| elif msg["content"] is None: | |
| msg["content"] = "" | |
| out.append(msg) | |
| elif m["role"] == "tool": | |
| out.append({"role": "tool", "tool_call_id": m["id"], "content": m["content"]}) | |
| else: | |
| out.append({"role": m["role"], "content": m["content"]}) | |
| return out | |
| def chat(self, messages: list[dict[str, Any]], tools: Optional[list[ToolSpec]] = None, | |
| json_mode: bool = False, temperature: float = 0.2) -> LLMResponse: | |
| msgs = self.to_messages(messages) | |
| payload: dict[str, Any] = {"model": self.model, "messages": msgs, "stream": True, | |
| "stream_options": {"include_usage": True}, "temperature": temperature} | |
| if tools: | |
| payload["tools"] = [t.as_openai() for t in tools] | |
| if json_mode: | |
| # json_object kipi, mesajlarda "JSON" sözcüğünün geçmesini şart koşar | |
| if not any("json" in str(m.get("content") or "").lower() for m in msgs): | |
| msgs.insert(0, {"role": "system", "content": "Reply with a single valid JSON object."}) | |
| payload["response_format"] = {"type": "json_object"} | |
| def fixups(p: dict[str, Any], _status: int, body: str) -> bool: | |
| low = body.lower() | |
| # Akıl yürütme modelleri (o-serisi, gpt-5) sıcaklık parametresini kabul etmez, vb. | |
| for key in ("temperature", "stream_options", "response_format"): | |
| if key in p and key in low: | |
| p.pop(key) | |
| return True | |
| if "tools" in p and "tool" in low and "support" in low: | |
| # Sunucu/model yerel araç çağrısını desteklemiyor: araçlar metinle tarif edilir | |
| desc = "\n".join(f"- {t['function']['name']}: {t['function']['description']} " | |
| f"Parameters: {json.dumps(t['function']['parameters'])}" for t in p.pop("tools")) | |
| p["messages"] = [{"role": "system", "content": TEXT_TOOLS + desc}] + [ | |
| {"role": "user", "content": f"[tool result]\n{m.get('content')}"} if m.get("role") == "tool" | |
| else {"role": m["role"], "content": m.get("content") or ""} for m in p["messages"]] | |
| return True | |
| if "unsupported" in low and "temperature" in p: | |
| p.pop("temperature") | |
| return True | |
| return False | |
| start = time.time() | |
| def handle(r: httpx.Response) -> LLMResponse: | |
| parts: list[str] = [] | |
| slots: dict[int, dict[str, str]] = {} | |
| usage: dict[str, Any] = {} | |
| n, last, first = 0, [start], None | |
| for chunk in _sse(r): | |
| if chunk.get("error"): | |
| raise ProviderError(f"OpenAI hata: {_short(json.dumps(chunk))}") | |
| if chunk.get("usage"): | |
| usage = chunk["usage"] | |
| for ch in chunk.get("choices") or []: | |
| d = ch.get("delta") or {} | |
| if d.get("content"): | |
| parts.append(d["content"]) | |
| first = first or time.time() | |
| for tc in d.get("tool_calls") or []: | |
| s = slots.setdefault(int(tc.get("index") or 0), {"id": "", "name": "", "args": ""}) | |
| s["id"] = s["id"] or tc.get("id") or "" | |
| fn = tc.get("function") or {} | |
| if fn.get("name") and not s["name"]: | |
| s["name"] = fn["name"] | |
| s["args"] += fn.get("arguments") or "" | |
| first = first or time.time() | |
| n += 1 | |
| self._tick(n, start, last) | |
| return self._finish("".join(parts), [slots[k] for k in sorted(slots)], usage, start, first, tools) | |
| return self._post_stream(f"{self.base_url}/chat/completions", payload, handle, fixups) | |
| def _finish(self, content: str, raw_calls: list[dict[str, str]], usage: dict[str, Any], start: float, | |
| first: Optional[float], tools: Optional[list[ToolSpec]]) -> LLMResponse: | |
| calls = [ToolCall(name=c["name"], arguments=_args(c["args"]) or ({"code": c["args"]} if c["name"] == "write_tests" else {})) | |
| for c in raw_calls if c["name"]] | |
| if tools and not calls: | |
| calls = recover_tool_calls(content, {t.name for t in tools}) | |
| out_tok = int(usage.get("completion_tokens") or usage.get("output_tokens") or 0) | |
| gen = time.time() - (first or start) | |
| return LLMResponse(content=content, tool_calls=calls, raw={"usage": usage}, | |
| prompt_tokens=int(usage.get("prompt_tokens") or usage.get("input_tokens") or 0), | |
| completion_tokens=out_tok, duration_s=time.time() - start, | |
| tokens_per_s=round(out_tok / gen, 1) if out_tok and gen > 0.05 else 0.0) | |
| def list_models(self) -> list[dict[str, Any]]: | |
| with self._client(20) as c: | |
| r = c.get(f"{self.base_url}/models", headers=self._headers()) | |
| if r.status_code in (401, 403): | |
| raise ProviderError(f"OpenAI: API anahtarı reddedildi ({r.status_code}). {_short(r.text)}", "auth", | |
| _short(r.text)) | |
| r.raise_for_status() | |
| data = r.json().get("data") or [] | |
| out = [] | |
| for m in data: | |
| mid = m.get("id") or "" | |
| if not mid: | |
| continue | |
| if self.official and (not _OPENAI_CHAT.search(mid) or _OPENAI_SKIP.search(mid)): | |
| continue | |
| out.append({"id": mid, "name": mid, "created": m.get("created")}) | |
| return sorted(out, key=lambda x: x["id"]) | |
| # --------------------------------------------------------------------------- | |
| # Anthropic Claude (Messages API) | |
| # --------------------------------------------------------------------------- | |
| class AnthropicClient(_CloudBase): | |
| provider = "anthropic" | |
| label = "Claude" | |
| def __init__(self, model: str, api_key: str, base_url: Optional[str] = None, | |
| transport: Optional[httpx.BaseTransport] = None) -> None: | |
| super().__init__(model, api_key, base_url or ANTHROPIC_URL, transport) | |
| self.max_tokens = int(os.environ.get("ANTHROPIC_MAX_TOKENS", "16000")) | |
| def _headers(self) -> dict[str, str]: | |
| return {"x-api-key": self.api_key, "anthropic-version": ANTHROPIC_VERSION, | |
| "content-type": "application/json"} | |
| def to_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str, Any]]]: | |
| system: list[str] = [] | |
| out: list[dict[str, Any]] = [] | |
| def add(role: str, blocks: list[dict[str, Any]]) -> None: | |
| if not blocks: | |
| return | |
| if out and out[-1]["role"] == role: # art arda aynı rol birleştirilir | |
| out[-1]["content"].extend(blocks) | |
| else: | |
| out.append({"role": role, "content": blocks}) | |
| for m in normalize(messages): | |
| role, text = m["role"], m["content"] | |
| if role == "system": | |
| if text.strip(): | |
| system.append(text) | |
| elif role == "assistant": | |
| blocks = [{"type": "text", "text": text}] if text.strip() else [] | |
| blocks += [{"type": "tool_use", "id": c["id"], "name": c["name"], "input": c["arguments"]} | |
| for c in m["tool_calls"]] | |
| add("assistant", blocks or [{"type": "text", "text": "(no output)"}]) | |
| elif role == "tool": | |
| add("user", [{"type": "tool_result", "tool_use_id": m["id"], "content": text or "(empty)"}]) | |
| else: | |
| add("user", [{"type": "text", "text": text or "(empty)"}]) | |
| if not out or out[0]["role"] != "user": | |
| out.insert(0, {"role": "user", "content": [{"type": "text", "text": "Begin."}]}) | |
| # Araç sonuçları, kullanıcı içeriğinde metinden önce gelmelidir | |
| for m in out: | |
| if m["role"] == "user": | |
| m["content"].sort(key=lambda b: 0 if b["type"] == "tool_result" else 1) | |
| return "\n\n".join(system), out | |
| def chat(self, messages: list[dict[str, Any]], tools: Optional[list[ToolSpec]] = None, | |
| json_mode: bool = False, temperature: float = 0.2) -> LLMResponse: | |
| system, msgs = self.to_messages(messages) | |
| if json_mode: | |
| system = (system + "\n\n" if system else "") + "Respond with ONLY a single valid JSON object, no prose." | |
| payload: dict[str, Any] = {"model": self.model, "max_tokens": self.max_tokens, "messages": msgs, | |
| "stream": True, "temperature": max(0.0, min(1.0, temperature))} | |
| if system: | |
| payload["system"] = system | |
| if tools: | |
| payload["tools"] = [{"name": t.name, "description": t.description, "input_schema": t.parameters} | |
| for t in tools] | |
| def fixups(p: dict[str, Any], _status: int, body: str) -> bool: | |
| low = body.lower() | |
| if "max_tokens" in low and p.get("max_tokens", 0) > 4096: | |
| p["max_tokens"] = 8192 if p["max_tokens"] > 8192 else 4096 | |
| return True | |
| if "temperature" in low and "temperature" in p: | |
| p.pop("temperature") | |
| return True | |
| return False | |
| start = time.time() | |
| def handle(r: httpx.Response) -> LLMResponse: | |
| blocks: dict[int, dict[str, Any]] = {} | |
| usage = {"input_tokens": 0, "output_tokens": 0} | |
| n, last, first = 0, [start], None | |
| for ev in _sse(r): | |
| t = ev.get("type") | |
| if t == "error": | |
| err = ev.get("error") or {} | |
| raise ProviderError(f"Claude hata: {err.get('type', '')} {err.get('message', '')}".strip()) | |
| if t == "message_start": | |
| u = (ev.get("message") or {}).get("usage") or {} | |
| usage["input_tokens"] = int(u.get("input_tokens") or 0) + int(u.get("cache_read_input_tokens") or 0) | |
| elif t == "content_block_start": | |
| cb = ev.get("content_block") or {} | |
| blocks[int(ev.get("index") or 0)] = {"type": cb.get("type"), "text": cb.get("text") or "", | |
| "id": cb.get("id"), "name": cb.get("name"), "json": ""} | |
| elif t == "content_block_delta": | |
| b = blocks.setdefault(int(ev.get("index") or 0), {"type": "text", "text": "", "json": ""}) | |
| d = ev.get("delta") or {} | |
| if d.get("type") == "text_delta": | |
| b["text"] += d.get("text") or "" | |
| elif d.get("type") == "input_json_delta": | |
| b["json"] += d.get("partial_json") or "" | |
| first = first or time.time() | |
| elif t == "message_delta": | |
| u = ev.get("usage") or {} | |
| usage["output_tokens"] = int(u.get("output_tokens") or usage["output_tokens"]) | |
| elif t == "message_stop": | |
| break | |
| n += 1 | |
| self._tick(n, start, last) | |
| content = "".join(b["text"] for _, b in sorted(blocks.items()) if b["type"] == "text") | |
| calls = [ToolCall(name=b["name"], arguments=_args(b["json"]) if b["json"] else {}) | |
| for _, b in sorted(blocks.items()) if b["type"] == "tool_use" and b.get("name")] | |
| if tools and not calls: | |
| calls = recover_tool_calls(content, {t.name for t in tools}) | |
| out_tok = usage["output_tokens"] | |
| gen = time.time() - (first or start) | |
| return LLMResponse(content=content, tool_calls=calls, raw={"usage": usage}, | |
| prompt_tokens=usage["input_tokens"], completion_tokens=out_tok, | |
| duration_s=time.time() - start, | |
| tokens_per_s=round(out_tok / gen, 1) if out_tok and gen > 0.05 else 0.0) | |
| return self._post_stream(f"{self.base_url}/v1/messages", payload, handle, fixups) | |
| def list_models(self) -> list[dict[str, Any]]: | |
| out: list[dict[str, Any]] = [] | |
| after: Optional[str] = None | |
| with self._client(20) as c: | |
| for _ in range(20): | |
| params: dict[str, Any] = {"limit": 1000} | |
| if after: | |
| params["after_id"] = after | |
| r = c.get(f"{self.base_url}/v1/models", headers=self._headers(), params=params) | |
| if r.status_code in (401, 403): | |
| raise ProviderError(f"Claude: API anahtarı reddedildi ({r.status_code}). {_short(r.text)}", "auth", | |
| _short(r.text)) | |
| r.raise_for_status() | |
| j = r.json() | |
| for m in j.get("data") or []: | |
| if m.get("id"): | |
| out.append({"id": m["id"], "name": m.get("display_name") or m["id"], | |
| "created": m.get("created_at")}) | |
| if not j.get("has_more") or not j.get("last_id"): | |
| break | |
| after = j["last_id"] | |
| return out # API en yeniden eskiye sıralı döndürür | |