classifier: Support authenticated Ollama endpoints via OLLAMA_API_KEY

Ollama Cloud and other hosted endpoints reject unauthenticated requests,
so the classifier and its test harness could not reach them. Send a
Bearer token when OLLAMA_API_KEY is set, letting the same code work
against both the local instance and hosted services without changing
behavior for keyless setups.
This commit is contained in:
Jeena 2026-10-08 08:26:26 +09:00
parent 71319a7587
commit 3cba601c72
2 changed files with 9 additions and 2 deletions

View file

@ -118,10 +118,13 @@ def call_ollama(messages: list[dict]) -> dict:
"stream": False, "stream": False,
"options": {"temperature": 0}, "options": {"temperature": 0},
}).encode("utf-8") }).encode("utf-8")
headers = {"Content-Type": "application/json"}
if api_key := os.getenv("OLLAMA_API_KEY", ""):
headers["Authorization"] = f"Bearer {api_key}"
req = Request( req = Request(
f"{OLLAMA_BASE_URL}/v1/chat/completions", f"{OLLAMA_BASE_URL}/v1/chat/completions",
data=payload, data=payload,
headers={"Content-Type": "application/json"}, headers=headers,
method="POST", method="POST",
) )
with urlopen(req, timeout=300) as resp: with urlopen(req, timeout=300) as resp:

View file

@ -34,6 +34,7 @@ class Classifier:
self.base_url = base_url or os.getenv("OLLAMA_BASE_URL", "http://192.168.1.20:11434") self.base_url = base_url or os.getenv("OLLAMA_BASE_URL", "http://192.168.1.20:11434")
self.model = model or os.getenv("OLLAMA_MODEL", "gemma4:26b") self.model = model or os.getenv("OLLAMA_MODEL", "gemma4:26b")
self.fallback_model = fallback_model or os.getenv("OLLAMA_FALLBACK_MODEL", "gemma4:12b") self.fallback_model = fallback_model or os.getenv("OLLAMA_FALLBACK_MODEL", "gemma4:12b")
self.api_key = os.getenv("OLLAMA_API_KEY", "")
def classify( def classify(
self, self,
@ -77,10 +78,13 @@ class Classifier:
"stream": False, "stream": False,
"options": {"temperature": 0}, "options": {"temperature": 0},
}).encode("utf-8") }).encode("utf-8")
headers = {"Content-Type": "application/json"}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
req = Request( req = Request(
f"{self.base_url}/v1/chat/completions", f"{self.base_url}/v1/chat/completions",
data=payload, data=payload,
headers={"Content-Type": "application/json"}, headers=headers,
method="POST", method="POST",
) )
with urlopen(req, timeout=timeout) as resp: with urlopen(req, timeout=timeout) as resp: