From 7f8cec84310a4b1fc2d5cf98f4cbcbb84d5d1a43 Mon Sep 17 00:00:00 2001 From: linwei85 Date: Wed, 30 Oct 2024 12:05:38 +0800 Subject: [PATCH] add feature to connect claude via proxy --- .env.example | 4 +++- src/main/store/anthropic.ts | 37 ++++++++++++++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/.env.example b/.env.example index 80a79e6..d59c640 100644 --- a/.env.example +++ b/.env.example @@ -1 +1,3 @@ -ANTHROPIC_API_KEY= \ No newline at end of file +ANTHROPIC_API_KEY= +#PROXY_HOST_NAME=127.0.0.1 +#PROXY_PORT=12111 diff --git a/src/main/store/anthropic.ts b/src/main/store/anthropic.ts index 981d68d..19af164 100644 --- a/src/main/store/anthropic.ts +++ b/src/main/store/anthropic.ts @@ -1,9 +1,40 @@ import Anthropic from '@anthropic-ai/sdk'; import dotenv from 'dotenv'; +import { SocksProxyAgent } from 'socks-proxy-agent'; dotenv.config(); -export const anthropic = new Anthropic({ - apiKey: process.env.ANTHROPIC_API_KEY, +// Initialize Anthropic client with or without proxy based on configuration +const anthropicConfig: { + apiKey: string; + baseURL: string; + httpAgent?: SocksProxyAgent; + timeout: number; +} = { + apiKey: process.env.ANTHROPIC_API_KEY!, baseURL: process.env.ANTHROPIC_BASE_URL || 'https://api.anthropic.com', -}); + timeout: 60000, +}; + +// Configure SOCKS5 proxy if proxy settings are provided in environment variables +if (process.env.PROXY_HOST_NAME && process.env.PROXY_PORT) { + // Create proxy configuration + const proxyOptions = { + hostname: process.env.PROXY_HOST_NAME, + port: parseInt(process.env.PROXY_PORT, 10), + // Optional: Add authentication if required + // username: process.env.PROXY_USERNAME, + // password: process.env.PROXY_PASSWORD, + }; + + // Initialize SOCKS5 proxy agent + const socksAgent = new SocksProxyAgent( + `socks5://${proxyOptions.hostname}:${proxyOptions.port}`, + ); + + // Add proxy agent to Anthropic configuration + anthropicConfig.httpAgent = socksAgent; +} + +// Create and export Anthropic client instance +export const anthropic = new Anthropic(anthropicConfig);