fixed a bug
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import requests
|
||||
|
||||
@@ -24,6 +25,19 @@ class AITutor:
|
||||
def available(self) -> bool:
|
||||
return bool(self.endpoint and self.model)
|
||||
|
||||
@property
|
||||
def request_url(self) -> str:
|
||||
"""Resolve either a full chat URL or an OpenAI-compatible base URL."""
|
||||
parsed = urlsplit(self.endpoint)
|
||||
path = parsed.path.rstrip("/")
|
||||
if parsed.query or path.endswith("/chat/completions"):
|
||||
return self.endpoint
|
||||
if path.endswith("/v1") or path.endswith("/v1/openai"):
|
||||
return self.endpoint + "/chat/completions"
|
||||
if not path:
|
||||
return self.endpoint + "/v1/chat/completions"
|
||||
return self.endpoint
|
||||
|
||||
def explain(
|
||||
self,
|
||||
sentence_text: str,
|
||||
@@ -51,7 +65,7 @@ class AITutor:
|
||||
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
try:
|
||||
response = requests.post(
|
||||
self.endpoint,
|
||||
self.request_url,
|
||||
headers=headers,
|
||||
json={
|
||||
"model": self.model,
|
||||
@@ -67,7 +81,7 @@ class AITutor:
|
||||
except requests.RequestException as exc:
|
||||
logger.exception(
|
||||
"AI explanation request failed: endpoint=%s model=%s",
|
||||
self.endpoint,
|
||||
self.request_url,
|
||||
self.model,
|
||||
)
|
||||
raise AITutorError("AI service request failed.") from exc
|
||||
@@ -76,7 +90,7 @@ class AITutor:
|
||||
logger.warning(
|
||||
"AI explanation returned HTTP %s: endpoint=%s model=%s body=%s",
|
||||
response.status_code,
|
||||
self.endpoint,
|
||||
self.request_url,
|
||||
self.model,
|
||||
response.text[:1000],
|
||||
)
|
||||
@@ -87,14 +101,14 @@ class AITutor:
|
||||
except (KeyError, IndexError, TypeError, ValueError) as exc:
|
||||
logger.warning(
|
||||
"AI explanation returned an unexpected body: endpoint=%s body=%s",
|
||||
self.endpoint,
|
||||
self.request_url,
|
||||
response.text[:1000],
|
||||
)
|
||||
raise AITutorError("AI service returned an unexpected response.") from exc
|
||||
if not isinstance(explanation, str) or not explanation.strip():
|
||||
logger.warning(
|
||||
"AI explanation returned empty content: endpoint=%s body=%s",
|
||||
self.endpoint,
|
||||
self.request_url,
|
||||
response.text[:1000],
|
||||
)
|
||||
raise AITutorError("AI service returned an empty explanation.")
|
||||
|
||||
Reference in New Issue
Block a user