chatbot1 / scripts /troubleshoot.py
Jack-ki1's picture
Upload 16 files
00bd2b1 verified
#!/usr/bin/env python3
"""Troubleshoot common issues with the FINESE SCHOOL application.
This script helps diagnose common configuration issues and provides
suggestions for fixing them.
"""
import os
import sys
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def check_environment_variables():
"""Check if required environment variables are set."""
print("πŸ” Checking environment variables...")
# Check API type
api_type = os.getenv("API_TYPE", "huggingface").lower()
print(f"βœ… API_TYPE is set to: {api_type}")
# Check API key based on API type
if api_type == "google":
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
print("❌ GOOGLE_API_KEY is not set")
print(" Please set your Google API key in the .env file")
return False
else:
print(f"βœ… GOOGLE_API_KEY is set (length: {len(api_key)} characters)")
elif api_type == "openai":
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("❌ OPENAI_API_KEY is not set")
print(" Please set your OpenAI API key in the .env file")
return False
else:
print(f"βœ… OPENAI_API_KEY is set (length: {len(api_key)} characters)")
else: # huggingface
api_key = os.getenv("HUGGINGFACE_API_KEY")
if not api_key:
print("❌ HUGGINGFACE_API_KEY is not set")
print(" Please set your Hugging Face API key in the .env file")
return False
else:
print(f"βœ… HUGGINGFACE_API_KEY is set (length: {len(api_key)} characters)")
model_name = os.getenv("MODEL_NAME")
if model_name:
print(f"βœ… MODEL_NAME is set to: {model_name}")
else:
print("⚠️ MODEL_NAME is not set, using default model")
temperature = os.getenv("TEMPERATURE", "0.3")
print(f"βœ… TEMPERATURE is set to: {temperature}")
max_tokens = os.getenv("MAX_TOKENS", "2048")
print(f"βœ… MAX_TOKENS is set to: {max_tokens}")
is_docker = os.getenv("IS_DOCKER", "false")
print(f"βœ… IS_DOCKER is set to: {is_docker}")
return True
def check_dependencies():
"""Check if required dependencies are installed."""
print("\nπŸ” Checking dependencies...")
dependencies = [
"streamlit",
"pdfkit",
"python-dotenv",
"langchain",
"pydantic",
"pygments"
]
# API-specific dependencies
api_type = os.getenv("API_TYPE", "huggingface").lower()
if api_type == "google":
dependencies.append("langchain-google-genai")
elif api_type == "openai":
dependencies.append("langchain-openai")
else: # huggingface
dependencies.append("langchain-huggingface")
missing_deps = []
for dep in dependencies:
try:
__import__(dep)
print(f"βœ… {dep} is installed")
except ImportError as e:
print(f"❌ {dep} is missing: {e}")
missing_deps.append(dep)
if missing_deps:
print(f"\nπŸ”§ To install missing dependencies, run:")
print(f" pip install {' '.join(missing_deps)}")
return False
return True
def check_model_access():
"""Check if we can access the configured model."""
print("\nπŸ” Checking model access...")
api_type = os.getenv("API_TYPE", "huggingface").lower()
if api_type == "google":
try:
from langchain_google_genai import GoogleGenerativeAI
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
print("❌ Cannot check model access without GOOGLE_API_KEY")
return False
model_name = os.getenv("MODEL_NAME", "gemini-1.5-flash")
print(f" Testing access to Google model: {model_name}")
llm = GoogleGenerativeAI(
model=model_name,
google_api_key=api_key
)
# Test a simple prompt
print(" Sending test request...")
response = llm.invoke("Say 'Hello, FINESE SCHOOL!' in one word.")
print(f"βœ… Successfully connected to Google Generative AI")
print(f" Test response: {response.content.strip()}")
return True
except Exception as e:
print(f"❌ Failed to access Google model: {str(e)}")
print("\nπŸ’‘ Troubleshooting tips:")
print(" 1. Check that your API key is valid")
print(" 2. Verify the model name is correct by running scripts/list_models.py")
print(" 3. Check your internet connection")
return False
elif api_type == "openai":
try:
from langchain_openai import ChatOpenAI
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("❌ Cannot check model access without OPENAI_API_KEY")
return False
model_name = os.getenv("MODEL_NAME", "gpt-3.5-turbo")
print(f" Testing access to OpenAI model: {model_name}")
llm = ChatOpenAI(
model_name=model_name,
openai_api_key=api_key
)
# Test a simple prompt
print(" Sending test request...")
response = llm.invoke("Say 'Hello, FINESE SCHOOL!' in one word.")
print(f"βœ… Successfully connected to OpenAI")
print(f" Test response: {response.content.strip()}")
return True
except Exception as e:
print(f"❌ Failed to access OpenAI model: {str(e)}")
print("\nπŸ’‘ Troubleshooting tips:")
print(" 1. Check that your API key is valid")
print(" 2. Verify the model name is correct")
print(" 3. Check your internet connection")
return False
else: # huggingface
try:
from langchain_huggingface import HuggingFaceEndpoint
api_key = os.getenv("HUGGINGFACE_API_KEY")
if not api_key:
print("❌ Cannot check model access without HUGGINGFACE_API_KEY")
return False
model_name = os.getenv("MODEL_NAME", "mistralai/Mistral-7B-Instruct-v0.2")
print(f" Testing access to Hugging Face model: {model_name}")
llm = HuggingFaceEndpoint(
repo_id=model_name,
huggingfacehub_api_token=api_key,
temperature=0.1,
max_new_tokens=100
)
# Test a simple prompt
print(" Sending test request...")
response = llm.invoke("Say 'Hello, FINESE SCHOOL!' in one word.")
print(f"βœ… Successfully connected to Hugging Face Inference API")
print(f" Test response: {response.strip()}")
return True
except Exception as e:
print(f"❌ Failed to access Hugging Face model: {str(e)}")
print("\nπŸ’‘ Troubleshooting tips:")
print(" 1. Check that your API key is valid")
print(" 2. Verify the model name is correct")
print(" 3. Check your internet connection")
print(" 4. Make sure you haven't exceeded rate limits")
return False
def check_wkhtmltopdf():
"""Check if wkhtmltopdf is installed for PDF generation."""
print("\nπŸ” Checking PDF generation support...")
try:
import pdfkit
print("βœ… pdfkit is installed")
except ImportError:
print("❌ pdfkit is not installed")
return False
try:
# Try to configure wkhtmltopdf
config = pdfkit.configuration()
print("βœ… wkhtmltopdf is configured")
return True
except OSError:
print("⚠️ wkhtmltopdf is not installed or not in PATH")
print(" PDF export functionality will be limited")
print("\nπŸ”§ To install wkhtmltopdf:")
print(" Windows: Download from https://wkhtmltopdf.org/downloads.html")
print(" macOS: brew install --cask wkhtmltopdf")
print(" Linux: sudo apt-get install wkhtmltopdf")
return True # Not critical for basic functionality
def main():
"""Main troubleshooting function."""
print("πŸ› οΈ FINESE SCHOOL Troubleshooting Script")
print("=" * 50)
checks = [
check_environment_variables,
check_dependencies,
check_model_access,
check_wkhtmltopdf
]
results = []
for check in checks:
try:
results.append(check())
except Exception as e:
print(f"❌ Check failed with exception: {e}")
results.append(False)
print("\nπŸ“‹ Summary")
print("=" * 50)
if all(results):
print("βœ… All checks passed! You should be able to run FINESE SCHOOL.")
print("\nπŸš€ To start the application, run:")
print(" streamlit run src/app.py")
else:
passed = sum(results)
total = len(results)
print(f"⚠️ {passed}/{total} checks passed.")
if passed > 0:
print("βœ… Some functionality may work, but fix the issues above for full functionality.")
else:
print("❌ Critical issues found. Please address them before running the application.")
print("\nπŸ“ For more help, check the README.md file or open an issue on GitHub.")
if __name__ == "__main__":
main()