Преглед изворни кода

修改代理改为环境变量

xueyiming пре 6 дана
родитељ
комит
1137f88be9
1 измењених фајлова са 32 додато и 2 уклоњено
  1. 32 2
      agent/llm/openrouter.py

+ 32 - 2
agent/llm/openrouter.py

@@ -39,6 +39,28 @@ _RETRYABLE_EXCEPTIONS = (
 )
 
 
+def _select_http_proxy_url() -> Optional[str]:
+    """
+    从环境变量读取代理地址。
+    - 环境变量存在且非空:使用该代理
+    - 环境变量不存在:不传 proxy(让 httpx 按直连/系统配置处理)
+    """
+    # 优先级:专用 OPENROUTER_PROXY > 通用 HTTPS/HTTP/ALL 代理变量
+    for key in (
+        "OPENROUTER_PROXY",
+        "HTTPS_PROXY",
+        "https_proxy",
+        "HTTP_PROXY",
+        "http_proxy",
+        "ALL_PROXY",
+        "all_proxy",
+    ):
+        v = os.getenv(key)
+        if v:
+            return v
+    return None
+
+
 # ── OpenRouter Anthropic endpoint: model name mapping ──────────────────────
 # Local copy of yescode's model tables so this module is self-contained.
 _OR_MODEL_EXACT = {
@@ -537,8 +559,12 @@ async def _openrouter_anthropic_call(
 
     max_retries = 3
     last_exception = None
+    proxy_url = _select_http_proxy_url()
     for attempt in range(max_retries):
-        async with httpx.AsyncClient(timeout=300.0, proxy="http://127.0.0.1:7890") as client:
+        client_kwargs = {"timeout": 300.0}
+        if proxy_url:
+            client_kwargs["proxy"] = proxy_url
+        async with httpx.AsyncClient(**client_kwargs) as client:
             try:
                 response = await client.post(endpoint, json=payload, headers=headers)
                 response.raise_for_status()
@@ -661,8 +687,12 @@ async def openrouter_llm_call(
     # 调用 API(带重试)
     max_retries = 3
     last_exception = None
+    proxy_url = _select_http_proxy_url()
     for attempt in range(max_retries):
-        async with httpx.AsyncClient(timeout=300.0, proxy="http://127.0.0.1:7890") as client:
+        client_kwargs = {"timeout": 300.0}
+        if proxy_url:
+            client_kwargs["proxy"] = proxy_url
+        async with httpx.AsyncClient(**client_kwargs) as client:
             try:
                 response = await client.post(endpoint, json=payload, headers=headers)
                 response.raise_for_status()