mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-09-07 00:16:57 +08:00
feat: google临时环境变量线程安全处理
This commit is contained in:
+24
-19
@@ -1,6 +1,7 @@
|
|||||||
"""MoviePilot AI智能体实现"""
|
"""MoviePilot AI智能体实现"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import threading
|
||||||
from typing import Dict, List, Any
|
from typing import Dict, List, Any
|
||||||
|
|
||||||
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
||||||
@@ -20,6 +21,9 @@ from app.helper.message import MessageHelper
|
|||||||
from app.log import logger
|
from app.log import logger
|
||||||
from app.schemas import Notification
|
from app.schemas import Notification
|
||||||
|
|
||||||
|
# 用于保护环境变量修改的线程锁
|
||||||
|
_env_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
class AgentChain(ChainBase):
|
class AgentChain(ChainBase):
|
||||||
pass
|
pass
|
||||||
@@ -77,28 +81,29 @@ class MoviePilotAgent:
|
|||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from langchain_google_genai import ChatGoogleGenerativeAI
|
from langchain_google_genai import ChatGoogleGenerativeAI
|
||||||
|
|
||||||
# 使用临时环境变量配置代理
|
# 使用线程锁保护的临时环境变量配置
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def _temp_proxy_env():
|
def _temp_proxy_env():
|
||||||
"""临时设置代理环境变量的上下文管理器"""
|
"""线程安全的临时设置代理环境变量的上下文管理器"""
|
||||||
old_http = os.environ.get("HTTP_PROXY")
|
with _env_lock:
|
||||||
old_https = os.environ.get("HTTPS_PROXY")
|
old_http = os.environ.get("HTTP_PROXY")
|
||||||
try:
|
old_https = os.environ.get("HTTPS_PROXY")
|
||||||
if settings.PROXY_HOST:
|
try:
|
||||||
os.environ["HTTP_PROXY"] = settings.PROXY_HOST
|
if settings.PROXY_HOST:
|
||||||
os.environ["HTTPS_PROXY"] = settings.PROXY_HOST
|
os.environ["HTTP_PROXY"] = settings.PROXY_HOST
|
||||||
yield
|
os.environ["HTTPS_PROXY"] = settings.PROXY_HOST
|
||||||
finally:
|
yield
|
||||||
# 恢复原始环境变量
|
finally:
|
||||||
if old_http is not None:
|
# 恢复原始环境变量
|
||||||
os.environ["HTTP_PROXY"] = old_http
|
if old_http is not None:
|
||||||
elif "HTTP_PROXY" in os.environ:
|
os.environ["HTTP_PROXY"] = old_http
|
||||||
del os.environ["HTTP_PROXY"]
|
elif "HTTP_PROXY" in os.environ:
|
||||||
|
del os.environ["HTTP_PROXY"]
|
||||||
|
|
||||||
if old_https is not None:
|
if old_https is not None:
|
||||||
os.environ["HTTPS_PROXY"] = old_https
|
os.environ["HTTPS_PROXY"] = old_https
|
||||||
elif "HTTPS_PROXY" in os.environ:
|
elif "HTTPS_PROXY" in os.environ:
|
||||||
del os.environ["HTTPS_PROXY"]
|
del os.environ["HTTPS_PROXY"]
|
||||||
|
|
||||||
# 在临时环境变量中初始化 ChatGoogleGenerativeAI
|
# 在临时环境变量中初始化 ChatGoogleGenerativeAI
|
||||||
with _temp_proxy_env():
|
with _temp_proxy_env():
|
||||||
|
|||||||
Reference in New Issue
Block a user