Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Language models without an API key (#403)
Murtaza Nasird685011ead32
diff --git a/config/docker-compose.example.yml b/config/docker-compose.example.ymlindex 3e238dd4..3c016c44 100644--- a/config/docker-compose.example.yml+++ b/config/docker-compose.example.yml@@ -30,7 +30,7 @@ services:## 3. Edit the .env file to add your API keys:# - TRANSCRIPTION_API_KEY (for OpenAI) or ASR_BASE_URL (for self-hosted)- # - TEXT_MODEL_API_KEY (REQUIRED for summaries, titles, and chat)+ # - TEXT_MODEL_API_KEY for summaries, titles, and chat (not needed for a local server without a key)## 4. Start Speakr:# docker compose up -ddiff --git a/docs/admin-guide/model-configuration.md b/docs/admin-guide/model-configuration.mdindex 5e70994c..324aacd3 100644--- a/docs/admin-guide/model-configuration.md+++ b/docs/admin-guide/model-configuration.md@@ -32,6 +32,8 @@ TEXT_MODEL_NAME=openai/gpt-4o-mini**Custom Endpoints**: Speakr works with any OpenAI-compatible API endpoint, including self-hosted solutions like LocalAI, Ollama with OpenAI compatibility, or enterprise API gateways.+**Local servers without a key**: `TEXT_MODEL_API_KEY` is optional. Leave it unset for a server that needs no key, such as Ollama, vLLM or llama.cpp on your own network; set only `TEXT_MODEL_BASE_URL` and `TEXT_MODEL_NAME`.+**Google Gemini (OpenAI-compatible)**: Google exposes Gemini models behind an OpenAI-compatible URL. Point Speakr at it like any other base URL:```bash@@ -261,11 +263,14 @@ CHAT_MODEL_NAME=openai/gpt-4o| Configuration | Behavior ||--------------|----------|| No `CHAT_MODEL_*` variables set | Chat uses `TEXT_MODEL_*` settings (default) |-| Only `CHAT_MODEL_NAME` set | Falls back to `TEXT_MODEL_*` (API key required) |+| Only `CHAT_MODEL_NAME` set | Falls back to `TEXT_MODEL_*` (a key or a base URL is required) || Only `CHAT_MODEL_API_KEY` set | Falls back to `TEXT_MODEL_*` (model name required) || `CHAT_MODEL_API_KEY` + `CHAT_MODEL_NAME` set | Uses chat config with `TEXT_MODEL_BASE_URL` |+| `CHAT_MODEL_BASE_URL` + `CHAT_MODEL_NAME` set | Uses a dedicated chat server; no key is sent unless `CHAT_MODEL_API_KEY` is set (suits a local server) || All `CHAT_MODEL_*` variables set | Uses fully dedicated chat configuration |+The text model's key is sent only to the text model's server. A chat model on another server uses `CHAT_MODEL_API_KEY`, or no key.+### GPT-5 Settings for ChatIf you use GPT-5 models for chat, you can configure separate GPT-5 parameters:diff --git a/src/services/llm.py b/src/services/llm.pyindex 793cd265..7c4f3a31 100644--- a/src/services/llm.py+++ b/src/services/llm.py@@ -116,10 +116,13 @@ def get_chat_config():Get chat model configuration, falling back to TEXT_MODEL if not set.Returns a dict with api_key, base_url, model_name, and GPT-5 settings.+ A dedicated chat model needs CHAT_MODEL_NAME and either its own key or+ its own base URL; a local server often needs no key at all (#403)."""- if CHAT_MODEL_API_KEY and CHAT_MODEL_NAME:+ if CHAT_MODEL_NAME and (CHAT_MODEL_API_KEY or CHAT_MODEL_BASE_URL):return {- 'api_key': CHAT_MODEL_API_KEY,+ # The text model's key goes only to the text model's server.+ 'api_key': CHAT_MODEL_API_KEY or (TEXT_MODEL_API_KEY if (CHAT_MODEL_BASE_URL or TEXT_MODEL_BASE_URL) == TEXT_MODEL_BASE_URL else None),'base_url': CHAT_MODEL_BASE_URL or TEXT_MODEL_BASE_URL,'model_name': CHAT_MODEL_NAME,'gpt5_reasoning_effort': CHAT_GPT5_REASONING_EFFORT or os.environ.get("GPT5_REASONING_EFFORT", "medium"),@@ -170,24 +173,27 @@ try:except Exception as client_init_e:client = None+def _build_chat_client():+ """The chat client: the main client, or a dedicated one when the chat+ model has its own key or server. The key is optional, since a local+ server often runs without one (#403)."""+ chat_config = get_chat_config()+ if (chat_config['api_key'], chat_config['base_url']) == (TEXT_MODEL_API_KEY, TEXT_MODEL_BASE_URL):+ return client+ dedicated = OpenAI(+ api_key=chat_config['api_key'] or "not-needed",+ base_url=chat_config['base_url'],+ http_client=http_client_no_proxy,+ timeout=llm_timeout,+ max_retries=LLM_MAX_RETRIES,+ )+ logger.info(f"Separate chat client initialized: {chat_config['base_url']} / {chat_config['model_name']}")+ return dedicated++# Create chat client (may be same as main client if no separate config)-chat_client = Nonetry:- chat_config = get_chat_config()- if chat_config['api_key']:- if CHAT_MODEL_API_KEY and CHAT_MODEL_API_KEY != TEXT_MODEL_API_KEY:- # Separate chat configuration - create dedicated client- chat_client = OpenAI(- api_key=chat_config['api_key'],- base_url=chat_config['base_url'],- http_client=http_client_no_proxy,- timeout=llm_timeout,- max_retries=LLM_MAX_RETRIES,- )- logger.info(f"Separate chat client initialized: {chat_config['base_url']} / {chat_config['model_name']}")- else:- # Use same client as main LLM- chat_client = client+ chat_client = _build_chat_client()except Exception as chat_client_init_e:logger.warning(f"Failed to initialize chat client, falling back to main client: {chat_client_init_e}")chat_client = client@@ -241,9 +247,6 @@ def call_llm_completion(messages, temperature=0.7, response_format=None, stream=if not client:raise ValueError("LLM client not initialized")- if not TEXT_MODEL_API_KEY:- raise ValueError("TEXT_MODEL_API_KEY not configured")-# Check budget before making the callif user_id and operation_type:try:diff --git a/tests/test_cov_llm.py b/tests/test_cov_llm.pyindex 6c55e06b..bfde963f 100644--- a/tests/test_cov_llm.py+++ b/tests/test_cov_llm.py@@ -187,11 +187,12 @@ def test_call_llm_completion_no_client(monkeypatch):call_llm_completion([{"role": "user", "content": "hi"}])-def test_call_llm_completion_no_api_key(monkeypatch):- install_client(monkeypatch)+def test_call_llm_completion_without_api_key(monkeypatch):+ # A local server needs no key (#403): the call goes through.+ install_client(monkeypatch, return_value=make_completion("local"))monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", None)- with pytest.raises(ValueError, match="TEXT_MODEL_API_KEY"):- call_llm_completion([{"role": "user", "content": "hi"}])+ resp = call_llm_completion([{"role": "user", "content": "hi"}])+ assert resp.choices[0].message.content == "local"# ===========================================================================diff --git a/tests/test_keyless_llm.py b/tests/test_keyless_llm.pynew file mode 100644index 00000000..27143386--- /dev/null+++ b/tests/test_keyless_llm.py@@ -0,0 +1,76 @@+"""Language models without an API key (#403).++A local server (Ollama, vLLM, llama.cpp) often runs without a key. Every+model call refused to run when TEXT_MODEL_API_KEY was empty, although the+client was built with a placeholder for exactly this case, and the chat+client was never created at all. A dedicated chat model was only used when+it had its own key.+"""++import os+import sys++import pytest++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import src.services.llm as llm+++class _FakeOpenAI:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+++def env(monkeypatch):+ monkeypatch.setattr(llm, "OpenAI", _FakeOpenAI)+ main = object()+ monkeypatch.setattr(llm, "client", main)++ def configure(text_key=None, text_url="http://llm.lan/v1", chat_key=None, chat_url=None, chat_name=None):+ monkeypatch.setattr(llm, "TEXT_MODEL_API_KEY", text_key)+ monkeypatch.setattr(llm, "TEXT_MODEL_BASE_URL", text_url)+ monkeypatch.setattr(llm, "TEXT_MODEL_NAME", "text-model")+ monkeypatch.setattr(llm, "CHAT_MODEL_API_KEY", chat_key)+ monkeypatch.setattr(llm, "CHAT_MODEL_BASE_URL", chat_url)+ monkeypatch.setattr(llm, "CHAT_MODEL_NAME", chat_name)+ return main+ return configure+++def test_without_any_key_chat_uses_the_main_client(env):+ main = env()+ assert llm._build_chat_client() is main+ assert llm.get_chat_config()["model_name"] == "text-model"+++def test_a_keyless_chat_server_gets_its_own_client(env):+ env(chat_url="http://chat.lan/v1", chat_name="chat-model")+ chat = llm._build_chat_client()+ assert isinstance(chat, _FakeOpenAI)+ assert chat.kwargs["base_url"] == "http://chat.lan/v1" and chat.kwargs["api_key"] == "not-needed"+ assert llm.get_chat_config()["model_name"] == "chat-model"+++def test_the_text_key_never_goes_to_another_server(env):+ env(text_key="sk-text", text_url="https://openrouter.ai/api/v1", chat_url="http://chat.lan/v1", chat_name="chat-model")+ assert llm.get_chat_config()["api_key"] is None+ assert llm._build_chat_client().kwargs["api_key"] == "not-needed"+++def test_a_chat_model_on_the_text_server_shares_the_key_and_client(env):+ main = env(text_key="sk-text", chat_key="sk-text", chat_name="chat-model")+ assert llm.get_chat_config()["api_key"] == "sk-text"+ assert llm._build_chat_client() is main+++def test_a_chat_model_with_its_own_key(env):+ env(text_key="sk-text", chat_key="sk-chat", chat_name="chat-model")+ chat = llm._build_chat_client()+ assert chat.kwargs["api_key"] == "sk-chat" and chat.kwargs["base_url"] == "http://llm.lan/v1"+++def test_a_chat_name_alone_keeps_the_text_model(env):+ env(text_key="sk-text", chat_name="chat-model")+ assert llm.get_chat_config()["model_name"] == "text-model"