65 lines
2.5 KiB
Python
65 lines
2.5 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import urllib.request
|
|
from typing import Any
|
|
|
|
|
|
UA = "Mozilla/5.0 (compatible; ai-daily-report/1.0)"
|
|
|
|
|
|
def fetch_text(url: str, timeout_seconds: int) -> str:
|
|
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
|
with urllib.request.urlopen(req, timeout=timeout_seconds) as response:
|
|
return response.read().decode("utf-8", "ignore")
|
|
|
|
|
|
class OpenAICompatibleClient:
|
|
def __init__(self, *, api_key: str, base_url: str, model: str, timeout_seconds: int = 600):
|
|
self.api_key = api_key
|
|
self.base_url = base_url.rstrip("/")
|
|
self.model = model
|
|
self.timeout_seconds = timeout_seconds
|
|
|
|
def chat(self, prompt: str) -> str:
|
|
payload = json.dumps(
|
|
{
|
|
"model": self.model,
|
|
"messages": [{"role": "user", "content": prompt}],
|
|
"temperature": 0.2,
|
|
"max_tokens": 8000,
|
|
},
|
|
ensure_ascii=False,
|
|
).encode("utf-8")
|
|
req = urllib.request.Request(
|
|
f"{self.base_url}/chat/completions",
|
|
data=payload,
|
|
headers={"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"},
|
|
)
|
|
with urllib.request.urlopen(req, timeout=self.timeout_seconds) as response:
|
|
data = json.loads(response.read().decode("utf-8"))
|
|
return data["choices"][0]["message"]["content"].strip()
|
|
|
|
|
|
class BlogApiClient:
|
|
def __init__(self, *, base_url: str, token: str, timeout_seconds: int = 25):
|
|
self.base_url = base_url.rstrip("/")
|
|
self.token = token
|
|
self.timeout_seconds = timeout_seconds
|
|
|
|
def _request(self, method: str, path: str, payload: dict[str, Any] | None = None) -> dict[str, Any]:
|
|
data = None
|
|
headers = {"Authorization": f"Bearer {self.token}", "User-Agent": UA}
|
|
if payload is not None:
|
|
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
headers["Content-Type"] = "application/json"
|
|
req = urllib.request.Request(f"{self.base_url}{path}", data=data, headers=headers, method=method)
|
|
with urllib.request.urlopen(req, timeout=self.timeout_seconds) as response:
|
|
return json.loads(response.read().decode("utf-8"))
|
|
|
|
def create_post(self, payload: dict[str, Any]) -> dict[str, Any]:
|
|
return self._request("POST", "/api/service/posts", payload)
|
|
|
|
def publish_post(self, slug: str) -> None:
|
|
self._request("POST", f"/api/service/posts/{slug}/publish")
|