cryogenic22's picture
Update utils_core/llm_utils.py
48d4cca verified
import os
import logging
import traceback
import requests
from typing import Tuple, Optional
# Configure logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("llm_connectivity")
def comprehensive_anthropic_connectivity_test() -> Tuple[bool, Optional[str]]:
"""
Perform a comprehensive connectivity test for Anthropic API
Returns:
- Boolean indicating success
- Error message (if any)
"""
try:
# 1. Check API Key
api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
return False, "No Anthropic API key found in environment variables"
# 2. Test network connectivity to Anthropic
try:
# Check basic internet connectivity
requests.get("https://www.google.com", timeout=5)
except requests.RequestException:
return False, "No internet connection detected"
# 3. Test Anthropic API endpoint
try:
import anthropic
# Create client
client = anthropic.Anthropic(api_key=api_key)
# Attempt a simple API call
response = client.messages.create(
model="claude-3-haiku-20240307",
max_tokens=10,
messages=[
{"role": "user", "content": "Confirm API connectivity"}
]
)
# Check response
if not response or not response.content:
return False, "Received empty response from Anthropic API"
logger.info("Anthropic API connectivity test successful")
return True, None
except Exception as api_error:
logger.error(f"Anthropic API connection failed: {api_error}")
return False, f"Anthropic API connection error: {str(api_error)}"
except Exception as e:
logger.error(f"Unexpected error in connectivity test: {e}")
logger.error(traceback.format_exc())
return False, f"Unexpected error: {str(e)}"
def debug_anthropic_connection():
"""
Comprehensive debug function for Anthropic API connection
Prints detailed diagnostic information
"""
print("πŸ” Anthropic API Connectivity Diagnostics")
print("=" * 50)
# 1. Environment Check
print("\nπŸ“‹ Environment Variables:")
api_key = os.getenv("ANTHROPIC_API_KEY")
print(f"ANTHROPIC_API_KEY: {'SET' if api_key else 'NOT SET'}")
# 2. Connectivity Test
print("\n🌐 Connectivity Test:")
success, error = comprehensive_anthropic_connectivity_test()
if success:
print("βœ… API Connection: Successful")
else:
print(f"❌ API Connection: Failed")
print(f"Error Details: {error}")
# 3. Library Versions
print("\nπŸ“¦ Library Versions:")
try:
import anthropic
import langchain
print(f"Anthropic Library: {anthropic.__version__}")
print(f"LangChain Library: {langchain.__version__}")
except ImportError as e:
print(f"Error checking library versions: {e}")
# 4. Network Diagnostics
print("\nπŸ”¬ Network Diagnostics:")
try:
import socket
print("Hostname:", socket.gethostname())
print("IP Addresses:")
print(socket.gethostbyname(socket.gethostname()))
except Exception as e:
print(f"Network diagnostic error: {e}")
# Run diagnostics if script is executed directly
if __name__ == "__main__":
debug_anthropic_connection()