File size: 3,675 Bytes
2b5a896
48d4cca
 
2b5a896
48d4cca
2b5a896
48d4cca
 
 
 
2b5a896
48d4cca
2b5a896
48d4cca
2b5a896
 
48d4cca
 
2b5a896
 
48d4cca
 
 
 
2b5a896
48d4cca
 
 
 
 
 
2b5a896
48d4cca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b5a896
48d4cca
 
 
 
 
 
 
 
2b5a896
48d4cca
2b5a896
48d4cca
2b5a896
48d4cca
2b5a896
48d4cca
 
2b5a896
48d4cca
 
 
 
2b5a896
48d4cca
 
 
2b5a896
48d4cca
 
 
 
 
2b5a896
48d4cca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b5a896
48d4cca
2b5a896
48d4cca
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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()