aboutsummaryrefslogtreecommitdiffstats
path: root/cogs/utils/llm.py
diff options
context:
space:
mode:
authorsalmonik <raisersoft@proton.me>2026-06-03 13:58:55 +0200
committersalmonik <raisersoft@proton.me>2026-06-03 13:58:55 +0200
commit5c66e4ca00a0a7fe32232a90f4b546459c44c774 (patch)
treeef1a5bc7b29e9b32a777cbf826a495570fba9f28 /cogs/utils/llm.py
parentFix voice reconnect race: reuse VoiceClient instead of destroying it (diff)
downloadsenator-sperma-5c66e4ca00a0a7fe32232a90f4b546459c44c774.tar.gz
senator-sperma-5c66e4ca00a0a7fe32232a90f4b546459c44c774.zip
feat: add local API support for OpenAI compatible APIs
Signed-off-by: salmonik <raisersoft@proton.me>
Diffstat (limited to '')
-rw-r--r--cogs/utils/llm.py62
1 files changed, 62 insertions, 0 deletions
diff --git a/cogs/utils/llm.py b/cogs/utils/llm.py
new file mode 100644
index 0000000..2b05b12
--- /dev/null
+++ b/cogs/utils/llm.py
@@ -0,0 +1,62 @@
1# This file is part of Senator Sperma
2# Licensed under the GPL-3.0 License
3# Copyright (C) 2026 Salmonik @ salmonik@tuta.io
4# https://codeberg.org/salmonik/senator-sperma
5
6import os
7import httpx
8import logging
9
10logger = logging.getLogger(__name__)
11
12BACKWARD_COMPAT_MSG = (
13 "OPENROUTER_API_KEY/OPENROUTER_MODEL are deprecated. "
14 "Use LLM_API_KEY, LLM_MODEL instead."
15)
16
17
18def _get_config():
19 api_url = os.getenv("LLM_API_URL", "https://openrouter.ai/api/v1/chat/completions")
20 api_key = os.getenv("LLM_API_KEY") or os.getenv("OPENROUTER_API_KEY") or ""
21 model = os.getenv("LLM_MODEL") or os.getenv("OPENROUTER_MODEL") or ""
22
23 if os.getenv("OPENROUTER_API_KEY") and not os.getenv("LLM_API_KEY"):
24 logger.warning(BACKWARD_COMPAT_MSG)
25 if os.getenv("OPENROUTER_MODEL") and not os.getenv("LLM_MODEL"):
26 logger.warning(BACKWARD_COMPAT_MSG)
27
28 return api_url, api_key, model
29
30
31async def llm_completion(
32 messages: list[dict],
33 model: str | None = None,
34 api_url: str | None = None,
35 api_key: str | None = None,
36 extra: dict | None = None,
37 timeout: float = 180.0,
38) -> str | None:
39 url = api_url or os.getenv("LLM_API_URL", "https://openrouter.ai/api/v1/chat/completions")
40 model = model or os.getenv("LLM_MODEL") or os.getenv("OPENROUTER_MODEL") or ""
41 api_key = api_key or os.getenv("LLM_API_KEY") or os.getenv("OPENROUTER_API_KEY") or ""
42
43 headers = {"Content-Type": "application/json"}
44 if api_key:
45 headers["Authorization"] = f"Bearer {api_key}"
46
47 payload: dict = {"model": model, "messages": messages}
48 if extra:
49 payload.update(extra)
50
51 verify = os.getenv("LLM_API_VERIFY", "true").lower() in ("true", "1", "yes")
52
53 try:
54 async with httpx.AsyncClient(timeout=timeout, verify=verify) as client:
55 resp = await client.post(url, headers=headers, json=payload)
56 resp.raise_for_status()
57 data = resp.json()
58 logger.info("LLM response: %s", data)
59 return data["choices"][0]["message"]["content"]
60 except httpx.HTTPError as e:
61 logger.error("LLM API request failed (url=%s, model=%s): %s", url, model, e, exc_info=True)
62 return None