|
| 1 | +import os |
| 2 | +import argparse |
| 3 | +import json |
| 4 | +import subprocess |
| 5 | +from typing import Optional, List, Dict |
| 6 | +from dotenv import load_dotenv |
| 7 | + |
| 8 | +# Load environment variables from .env file if it exists |
| 9 | +load_dotenv() |
| 10 | + |
| 11 | +class ClaudeClient: |
| 12 | + """ |
| 13 | + A unified client for interacting with Anthropic's Claude 4.6 Sonnet model. |
| 14 | + Uses 'curl.exe' as a backend to bypass certain OS/Firewall restrictions that |
| 15 | + block Python networking libraries from sending API keys. |
| 16 | + """ |
| 17 | + def __init__(self, api_key: Optional[str] = None): |
| 18 | + self.api_key = api_key or os.environ.get("ANTHROPIC_API_KEY") |
| 19 | + if not self.api_key: |
| 20 | + raise ValueError( |
| 21 | + "Anthropic API Key not found. Please set 'ANTHROPIC_API_KEY' " |
| 22 | + "in your environment or .env file." |
| 23 | + ) |
| 24 | + self.base_url = "https://api.anthropic.com/v1/messages" |
| 25 | + self.model = "claude-sonnet-4-6" |
| 26 | + |
| 27 | + def _call_curl(self, data: dict, stream: bool = False) -> str: |
| 28 | + """ |
| 29 | + Calls the Anthropic API using system curl.exe. |
| 30 | + """ |
| 31 | + # Create a temporary JSON file for the data to avoid command line length issues |
| 32 | + temp_file = "claude_req.json" |
| 33 | + with open(temp_file, "w") as f: |
| 34 | + json.dump(data, f) |
| 35 | + |
| 36 | + cmd = [ |
| 37 | + "curl.exe", "-s", "-X", "POST", self.base_url, |
| 38 | + "-H", f"x-api-key: {self.api_key}", |
| 39 | + "-H", "anthropic-version: 2023-06-01", |
| 40 | + "-H", "content-type: application/json", |
| 41 | + "--data-binary", f"@{temp_file}" |
| 42 | + ] |
| 43 | + |
| 44 | + if stream: |
| 45 | + # For streaming, we need to parse the SSE output manually |
| 46 | + process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| 47 | + full_text = [] |
| 48 | + for line in process.stdout: |
| 49 | + if line.startswith("data: "): |
| 50 | + try: |
| 51 | + event_data = json.loads(line[6:]) |
| 52 | + if event_data["type"] == "content_block_delta": |
| 53 | + text = event_data["delta"]["text"] |
| 54 | + print(text, end="", flush=True) |
| 55 | + full_text.append(text) |
| 56 | + except: |
| 57 | + pass |
| 58 | + print() |
| 59 | + os.remove(temp_file) |
| 60 | + return "".join(full_text) |
| 61 | + else: |
| 62 | + result = subprocess.run(cmd, capture_output=True, text=True) |
| 63 | + os.remove(temp_file) |
| 64 | + |
| 65 | + if result.returncode != 0: |
| 66 | + return f"Error executing curl: {result.stderr}" |
| 67 | + |
| 68 | + try: |
| 69 | + response_json = json.loads(result.stdout) |
| 70 | + if "error" in response_json: |
| 71 | + error_msg = response_json["error"]["message"] |
| 72 | + # Check for credit-related errors |
| 73 | + if "credit" in error_msg.lower() or "balance" in error_msg.lower(): |
| 74 | + return f"CRITICAL ERROR: Credit Exhaustion. {error_msg}\nPlease top up your Anthropic account." |
| 75 | + return f"API Error: {error_msg}" |
| 76 | + return response_json["content"][0]["text"] |
| 77 | + except Exception as e: |
| 78 | + return f"Error parsing response: {e}\nRaw Output: {result.stdout}" |
| 79 | + |
| 80 | + def ask(self, prompt: str, system_prompt: Optional[str] = None, max_tokens: int = 4096) -> str: |
| 81 | + data = { |
| 82 | + "model": self.model, |
| 83 | + "max_tokens": max_tokens, |
| 84 | + "messages": [{"role": "user", "content": prompt}] |
| 85 | + } |
| 86 | + if system_prompt: |
| 87 | + data["system"] = system_prompt |
| 88 | + return self._call_curl(data) |
| 89 | + |
| 90 | + def stream_ask(self, prompt: str, system_prompt: Optional[str] = None): |
| 91 | + data = { |
| 92 | + "model": self.model, |
| 93 | + "max_tokens": 4096, |
| 94 | + "messages": [{"role": "user", "content": prompt}], |
| 95 | + "stream": True |
| 96 | + } |
| 97 | + if system_prompt: |
| 98 | + data["system"] = system_prompt |
| 99 | + return self._call_curl(data, stream=True) |
| 100 | + |
| 101 | +def main(): |
| 102 | + parser = argparse.ArgumentParser(description="Claude 4.6 Sonnet API Integration (Bypass Mode)") |
| 103 | + parser.add_argument("--test", action="store_true", help="Run a simple connectivity test") |
| 104 | + parser.add_argument("--prompt", type=str, help="Prompt to send to Claude") |
| 105 | + parser.add_argument("--stream", action="store_true", help="Stream the response") |
| 106 | + |
| 107 | + args = parser.parse_args() |
| 108 | + |
| 109 | + try: |
| 110 | + client = ClaudeClient() |
| 111 | + |
| 112 | + if args.test: |
| 113 | + print(f"Testing connectivity to model: {client.model}...") |
| 114 | + response = client.ask("Confirm you are Sonnet 4.6 and our connection via curl is working.") |
| 115 | + print(f"\nResponse: {response}") |
| 116 | + elif args.prompt: |
| 117 | + if args.stream: |
| 118 | + client.stream_ask(args.prompt) |
| 119 | + else: |
| 120 | + response = client.ask(args.prompt) |
| 121 | + print(response) |
| 122 | + else: |
| 123 | + parser.print_help() |
| 124 | + |
| 125 | + except Exception as e: |
| 126 | + print(f"Error: {e}") |
| 127 | + |
| 128 | +if __name__ == "__main__": |
| 129 | + main() |
0 commit comments