#!/usr/bin/env python3 """Test DeepSeek API connection and authentication.""" import os import sys import httpx import asyncio import json from pathlib import Path # Add parent directory to path sys.path.append(str(Path(__file__).parent.parent)) from dotenv import load_dotenv # Load environment variables load_dotenv() async def test_deepseek_connection(): """Test DeepSeek API connection with current API key.""" api_key = os.getenv("DEEPSEEK_API_KEY") if not api_key: print("āŒ DEEPSEEK_API_KEY not found in environment variables") return False print(f"šŸ”‘ Found API key: {api_key[:20]}...") # DeepSeek API endpoint base_url = "https://api.deepseek.com/v1" # Create client with headers headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } try: print("šŸ” Testing DeepSeek API connection...") # Test with a simple completion request async with httpx.AsyncClient(headers=headers, timeout=30) as client: # First, try to list available models print("šŸ“‹ Fetching available models...") response = await client.get(f"{base_url}/models") if response.status_code == 200: models = response.json() print("āœ… Successfully connected to DeepSeek API!") print(f"šŸ“Š Available models: {len(models.get('data', []))}") for model in models.get('data', [])[:5]: # Show first 5 models print(f" - {model.get('id', 'unknown')}") else: print(f"āš ļø Model list request failed with status {response.status_code}") print(f"Response: {response.text}") # Test with a minimal chat completion print("\nšŸ¤– Testing chat completion...") test_payload = { "model": "deepseek-chat", "messages": [ { "role": "system", "content": "You are a helpful assistant. Respond with exactly: 'API connection successful'" }, { "role": "user", "content": "Test" } ], "max_tokens": 10, "temperature": 0 } response = await client.post( f"{base_url}/chat/completions", json=test_payload ) if response.status_code == 200: result = response.json() content = result["choices"][0]["message"]["content"] print(f"āœ… Chat completion successful!") print(f"šŸ“ Response: {content}") # Show token usage and cost usage = result.get("usage", {}) print(f"šŸ“Š Tokens used: {usage.get('total_tokens', 0)}") # Calculate approximate cost input_tokens = usage.get("prompt_tokens", 0) output_tokens = usage.get("completion_tokens", 0) input_cost = (input_tokens / 1000) * 0.00014 # $0.14 per 1M tokens output_cost = (output_tokens / 1000) * 0.00028 # $0.28 per 1M tokens total_cost = input_cost + output_cost print(f"šŸ’° Estimated cost: ${total_cost:.8f}") return True elif response.status_code == 401: print("āŒ Authentication failed - Invalid API key") error_data = response.json() print(f"Error: {error_data.get('error', {}).get('message', 'Unknown error')}") return False elif response.status_code == 429: print("āš ļø Rate limit exceeded") print(f"Response: {response.text}") return False else: print(f"āŒ Request failed with status {response.status_code}") print(f"Response: {response.text}") return False except httpx.ConnectError as e: print(f"āŒ Connection error: Could not connect to DeepSeek API") print(f" Error: {e}") return False except httpx.TimeoutException as e: print(f"ā±ļø Request timed out after 30 seconds") print(f" Error: {e}") return False except Exception as e: print(f"āŒ Unexpected error: {e}") import traceback traceback.print_exc() return False async def test_summary_generation(): """Test actual summary generation with DeepSeek.""" api_key = os.getenv("DEEPSEEK_API_KEY") if not api_key: return False print("\nšŸ“ Testing summary generation...") # Sample transcript for testing test_transcript = """ Hello everyone, and welcome to this tutorial on Python programming. Today we'll be covering the basics of functions in Python. Functions are reusable blocks of code that perform specific tasks. They help us organize our code and avoid repetition. Let's start with a simple example of defining a function. """ headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } payload = { "model": "deepseek-chat", "messages": [ { "role": "system", "content": "You are an expert content summarizer. Provide a brief summary in JSON format." }, { "role": "user", "content": f"Summarize this transcript:\n\n{test_transcript}\n\nProvide JSON with 'summary' and 'key_points' fields." } ], "max_tokens": 200, "temperature": 0.3, "response_format": {"type": "json_object"} } try: async with httpx.AsyncClient(headers=headers, timeout=30) as client: response = await client.post( "https://api.deepseek.com/v1/chat/completions", json=payload ) if response.status_code == 200: result = response.json() content = result["choices"][0]["message"]["content"] print("āœ… Summary generation successful!") # Try to parse as JSON try: summary_data = json.loads(content) print("\nšŸ“Š Generated Summary:") print(json.dumps(summary_data, indent=2)) except json.JSONDecodeError: print(f"šŸ“ Raw response: {content}") return True else: print(f"āŒ Summary generation failed: {response.status_code}") print(f"Response: {response.text}") return False except Exception as e: print(f"āŒ Error during summary generation: {e}") return False async def main(): """Run all tests.""" print("šŸš€ DeepSeek API Test Suite") print("=" * 50) # Test basic connection connection_ok = await test_deepseek_connection() if connection_ok: # Test summary generation summary_ok = await test_summary_generation() if summary_ok: print("\nāœ… All tests passed! DeepSeek API is working correctly.") print("\nšŸ’” You can now generate summaries using the DeepSeek API.") else: print("\nāš ļø Connection works but summary generation failed.") else: print("\nāŒ DeepSeek API connection failed.") print("\nšŸ”§ Please check:") print("1. Your API key is valid and active") print("2. You have sufficient credits/quota") print("3. The API endpoint is accessible") print("\nšŸ“ To get a new API key, visit: https://platform.deepseek.com/") if __name__ == "__main__": asyncio.run(main())