Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""GreenPT transport — the one way this product talks to its provider.
The chat calls go to GreenPT v4 flash (deepseek-v4-flash-0731) over itsOpenAI-compatible endpoint, and embeddings to the green-embedding model(shared/embed.py). urllib only, like the rest of the repo.
The transport is the single choke point for the provider: the key is readhere, every HTTP failure is turned into a ClassifyError whose message nevernames the key, and the JSON-extraction helpers that tolerate the model'sfences and stray prose live next to it.
from shared.greenpt import _completion, ClassifyError content = _completion([{"role": "user", "content": "hi"}])"""
import jsonimport osimport reimport urllib.errorimport urllib.requestfrom pathlib import Path
GREENPT_URL = "https://api.greenpt.ai/v1/chat/completions"GREENPT_MODEL = os.environ.get("GREENPT_MODEL", "deepseek-v4-flash-0731")TIMEOUT = 120
ENV_FILE = Path(__file__).parent.parent / ".env"
class ClassifyError(RuntimeError): """A failed classification. The message is safe to print — it never names a key or a raw model dump, only the reason a decision could not be made."""
def api_key() -> str: """The provider key, from the environment or .env. Never printed.""" key = os.environ.get("GREENPT_API_KEY", "").strip() if not key and ENV_FILE.exists(): for line in ENV_FILE.read_text().splitlines(): if line.startswith("GREENPT_API_KEY="): key = line.split("=", 1)[1].strip().strip('"').strip("'") break if not key: raise ClassifyError( "GREENPT_API_KEY is not set. Put `GREENPT_API_KEY=sk-…` in .env " "or export it before running." ) return key
def _completion(messages: list[dict]) -> str: body = json.dumps({ "model": GREENPT_MODEL, "messages": messages, "temperature": 0, "max_tokens": 8000, }).encode() req = urllib.request.Request( GREENPT_URL, data=body, headers={ "Authorization": f"Bearer {api_key()}", "Content-Type": "application/json", }, ) try: with urllib.request.urlopen(req, timeout=TIMEOUT) as response: payload = json.loads(response.read()) except urllib.error.HTTPError as e: detail = e.read().decode("utf-8", "replace") raise ClassifyError(f"GreenPT returned HTTP {e.code}: {detail[:300]}") from None except OSError as e: raise ClassifyError(f"cannot reach GreenPT ({e}). Is the network up?") from None except json.JSONDecodeError: raise ClassifyError("GreenPT returned an unparseable response") from None
try: return payload["choices"][0]["message"]["content"] except (KeyError, IndexError): raise ClassifyError( f"GreenPT response had no choices — model {GREENPT_MODEL!r} " "possibly unusable right now" ) from None
def _find_json_object(text: str) -> str: """The model may wrap the object in a code fence or add a stray line; the object itself is the only part that matters.""" text = text.strip() if text.startswith("```"): text = re.sub(r"^```[a-zA-Z]*\s*|\s*```$", "", text, flags=re.S) start, end = text.find("{"), text.rfind("}") if start == -1 or end < start: raise ClassifyError( "the classifier did not return a JSON object. Try again." ) return text[start:end + 1]
def _find_json_array(text: str) -> str: """The model may wrap the array in a code fence or add a stray line; the array itself is the only part that matters.""" text = text.strip() if text.startswith("```"): text = re.sub(r"^```[a-zA-Z]*\s*|\s*```$", "", text, flags=re.S) start, end = text.find("["), text.rfind("]") if start == -1 or end < start: raise ClassifyError( "the classifier did not return a JSON array. Try again." ) return text[start:end + 1]