11# llm_api.py
22import os
3+ import json
34from groq import Groq
45from pydantic import BaseModel , Field , ValidationError
56from .system_info import fetch_system_info
67from .package_managers import detect_package_manager
78import sqlite3
89from .database import DB_PATH , save_command_suggestion
910
11+ # Configuration file path
12+ CONFIG_FILE = os .path .expanduser ("~/.snapshell_config.json" )
1013
11- API_KEY = os .getenv ('HELPER_GROQ_API_KEY' )
12-
13- groq = Groq (api_key = API_KEY )
14+ # Global variable to store the API key
15+ API_KEY = None
1416
1517# Data model for LLM to generate
1618class CommandSuggestion (BaseModel ):
@@ -21,9 +23,26 @@ class CommandSuggestion(BaseModel):
2123class SQLQuery (BaseModel ):
2224 query : str = Field (description = "The SQL query to be executed" )
2325
26+ def load_api_key ():
27+ global API_KEY
28+ if os .path .exists (CONFIG_FILE ):
29+ with open (CONFIG_FILE , "r" ) as config_file :
30+ config = json .load (config_file )
31+ API_KEY = config .get ("api_key" )
32+ return API_KEY
33+
34+ def set_api_key (api_key ):
35+ global API_KEY
36+ API_KEY = api_key
37+ config = {"api_key" : api_key }
38+ with open (CONFIG_FILE , "w" ) as config_file :
39+ json .dump (config , config_file )
40+
2441def suggest_command (user_input , conversation_history ):
2542 if not API_KEY :
26- raise ValueError ("API key not found. Please set the GROQ_API_KEY environment variable." )
43+ raise ValueError ("API key not set. Please set the API key using set_api_key function." )
44+
45+ groq = Groq (api_key = API_KEY )
2746
2847 system_info = fetch_system_info ()
2948 package_manager = detect_package_manager ()
@@ -103,6 +122,8 @@ def fallback_to_llm(user_input, package_manager, fallback_message, conversation_
103122
104123 messages .append ({"role" : "user" , "content" : user_input })
105124
125+ groq = Groq (api_key = API_KEY )
126+
106127 chat_completion = groq .chat .completions .create (
107128 messages = messages ,
108129 model = "llama-3.2-90b-text-preview" ,
@@ -131,6 +152,8 @@ def formulate_sql_query(user_input):
131152 {"role" : "user" , "content" : user_input },
132153 ]
133154
155+ groq = Groq (api_key = API_KEY )
156+
134157 chat_completion = groq .chat .completions .create (
135158 messages = messages ,
136159 model = "llama-3.2-90b-text-preview" ,
@@ -170,4 +193,7 @@ def query_database(sql_query):
170193 return relevant_packages
171194 except sqlite3 .Error as e :
172195 # If there's any issue with the database query, return an empty result
173- return []
196+ return []
197+
198+ # Load the API key from the configuration file on module import
199+ load_api_key ()
0 commit comments