Skip to content

Commit b973451

Browse files
committed
Set default chat model to KHOJ_CHAT_MODEL env var if set
Simplify code log to set default_use_model during init for readability
1 parent 9b4a276 commit b973451

File tree

4 files changed

+48
-10
lines changed

4 files changed

+48
-10
lines changed

.github/workflows/run_evals.yml

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ on:
4040
options:
4141
- terrarium
4242
- e2b
43+
chat_model:
44+
description: 'Chat model to use'
45+
required: false
46+
default: 'gemini-2.0-flash'
47+
type: string
4348

4449
jobs:
4550
eval:
@@ -48,7 +53,7 @@ jobs:
4853
matrix:
4954
# Use input from manual trigger if available, else run all combinations
5055
khoj_mode: ${{ github.event_name == 'workflow_dispatch' && fromJSON(format('["{0}"]', inputs.khoj_mode)) || fromJSON('["general", "default", "research"]') }}
51-
dataset: ${{ github.event_name == 'workflow_dispatch' && fromJSON(format('["{0}"]', inputs.dataset)) || fromJSON('["frames", "simpleqa"]') }}
56+
dataset: ${{ github.event_name == 'workflow_dispatch' && fromJSON(format('["{0}"]', inputs.dataset)) || fromJSON('["frames", "simpleqa", "gpqa"]') }}
5257

5358
services:
5459
postgres:
@@ -103,6 +108,7 @@ jobs:
103108
BATCH_SIZE: "20"
104109
RANDOMIZE: "True"
105110
KHOJ_URL: "http://localhost:42110"
111+
KHOJ_CHAT_MODEL: ${{ github.event_name == 'workflow_dispatch' && inputs.chat_model || 'gemini-2.0-flash' }}
106112
KHOJ_LLM_SEED: "42"
107113
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
108114
SERPER_DEV_API_KEY: ${{ matrix.dataset != 'math500' && secrets.SERPER_DEV_API_KEY }}
@@ -157,7 +163,7 @@ jobs:
157163
echo "## Evaluation Summary of Khoj on ${{ matrix.dataset }} in ${{ matrix.khoj_mode }} mode" >> $GITHUB_STEP_SUMMARY
158164
echo "**$(head -n 1 *_evaluation_summary_*.txt)**" >> $GITHUB_STEP_SUMMARY
159165
echo "- Khoj Version: ${{ steps.hatch.outputs.version }}" >> $GITHUB_STEP_SUMMARY
160-
echo "- Chat Model: Gemini 2.0 Flash" >> $GITHUB_STEP_SUMMARY
166+
echo "- Chat Model: ${{ inputs.chat_model }}" >> $GITHUB_STEP_SUMMARY
161167
echo "- Code Sandbox: ${{ inputs.sandbox}}" >> $GITHUB_STEP_SUMMARY
162168
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
163169
tail -n +2 *_evaluation_summary_*.txt >> $GITHUB_STEP_SUMMARY

src/khoj/database/adapters/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1107,6 +1107,12 @@ async def aget_chat_model(user: KhojUser):
11071107
return config.setting
11081108
return ConversationAdapters.aget_advanced_chat_model(user)
11091109

1110+
@staticmethod
1111+
def get_chat_model_by_name(chat_model_name: str, ai_model_api_name: str = None):
1112+
if ai_model_api_name:
1113+
return ChatModel.objects.filter(name=chat_model_name, ai_model_api__name=ai_model_api_name).first()
1114+
return ChatModel.objects.filter(name=chat_model_name).first()
1115+
11101116
@staticmethod
11111117
async def aget_voice_model_config(user: KhojUser) -> Optional[VoiceModelOption]:
11121118
voice_model_config = await UserVoiceModelConfig.objects.filter(user=user).prefetch_related("setting").afirst()
@@ -1205,6 +1211,15 @@ async def aget_advanced_chat_model(user: KhojUser = None):
12051211
return server_chat_settings.chat_advanced
12061212
return await ConversationAdapters.aget_default_chat_model(user)
12071213

1214+
@staticmethod
1215+
def set_default_chat_model(chat_model: ChatModel):
1216+
server_chat_settings = ServerChatSettings.objects.first()
1217+
if server_chat_settings:
1218+
server_chat_settings.chat_default = chat_model
1219+
server_chat_settings.save()
1220+
else:
1221+
ServerChatSettings.objects.create(chat_default=chat_model)
1222+
12081223
@staticmethod
12091224
async def aget_server_webscraper():
12101225
server_chat_settings = await ServerChatSettings.objects.filter().prefetch_related("web_scraper").afirst()

src/khoj/utils/initialization.py

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -185,16 +185,18 @@ def _setup_chat_model_provider(
185185
)
186186
provider_name = provider_name or model_type.name.capitalize()
187187

188-
default_use_model = {True: "y", False: "n"}[default_api_key is not None]
189-
190-
# If not in interactive mode & in the offline setting, it's most likely that we're running in a containerized environment. This usually means there's not enough RAM to load offline models directly within the application. In such cases, we default to not using the model -- it's recommended to use another service like Ollama to host the model locally in that case.
191-
default_use_model = {True: "n", False: default_use_model}[is_offline]
188+
default_use_model = default_api_key is not None
189+
# If not in interactive mode & in the offline setting, it's most likely that we're running in a containerized environment.
190+
# This usually means there's not enough RAM to load offline models directly within the application.
191+
# In such cases, we default to not using the model -- it's recommended to use another service like Ollama to host the model locally in that case.
192+
if is_offline:
193+
default_use_model = False
192194

193195
use_model_provider = (
194-
default_use_model if not interactive else input(f"Add {provider_name} chat models? (y/n): ")
196+
default_use_model if not interactive else input(f"Add {provider_name} chat models? (y/n): ") == "y"
195197
)
196198

197-
if use_model_provider != "y":
199+
if not use_model_provider:
198200
return False, None
199201

200202
logger.info(f"️💬 Setting up your {provider_name} chat configuration")
@@ -303,4 +305,19 @@ def _update_chat_model_options():
303305
logger.error(f"🚨 Failed to create chat configuration: {e}", exc_info=True)
304306
else:
305307
_update_chat_model_options()
306-
logger.info("🗣️ Chat model configuration updated")
308+
logger.info("🗣️ Chat model options updated")
309+
310+
# Update the default chat model if it doesn't match
311+
chat_config = ConversationAdapters.get_default_chat_model()
312+
env_default_chat_model = os.getenv("KHOJ_CHAT_MODEL")
313+
if not chat_config or not env_default_chat_model:
314+
return
315+
if chat_config.name != env_default_chat_model:
316+
chat_model = ConversationAdapters.get_chat_model_by_name(env_default_chat_model)
317+
if not chat_model:
318+
logger.error(
319+
f"🚨 Not setting default chat model. Chat model {env_default_chat_model} not found in existing chat model options."
320+
)
321+
return
322+
ConversationAdapters.set_default_chat_model(chat_model)
323+
logger.info(f"🗣️ Default chat model set to {chat_model.name}")

tests/evals/eval.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -666,7 +666,7 @@ def main():
666666
colored_accuracy_str = f"Overall Accuracy: {colored_accuracy} on {args.dataset.title()} dataset."
667667
accuracy_str = f"Overall Accuracy: {accuracy:.2%} on {args.dataset}."
668668
accuracy_by_reasoning = f"Accuracy by Reasoning Type:\n{reasoning_type_accuracy}"
669-
cost = f"Total Cost: ${running_cost.get():.5f}."
669+
cost = f"Total Cost: ${running_cost.get():.5f} to evaluate {running_total_count.get()} results."
670670
sample_type = f"Sampling Type: {SAMPLE_SIZE} samples." if SAMPLE_SIZE else "Whole dataset."
671671
sample_type += " Randomized." if RANDOMIZE else ""
672672
logger.info(f"\n{colored_accuracy_str}\n\n{accuracy_by_reasoning}\n\n{cost}\n\n{sample_type}\n")

0 commit comments

Comments
 (0)