Docker容器中Python代码无法连接OpenAI且运行OpenAI Agent代码报参数错误的解决求助
Docker容器中Python代码无法连接OpenAI且运行OpenAI Agent代码报参数错误的解决求助
我正在尝试创建一个OpenAI代理,基于用户输入对运行在Docker容器(docker-vscode-1)里的VS Code Server进行认证。我在容器内运行了以下代码:
import os import requests import logging from requests.exceptions import RequestException from dotenv import load_dotenv from langchain_community.llms import OpenAI from langchain.agents import initialize_agent, Tool from langchain.agents.agent_types import AgentType import warnings warnings.simplefilter("ignore") load_dotenv() # Configuration CODE_SERVER_URL = os.getenv("CODE_SERVER_URL", "http://172.20.0.2:8080") PASSWORD = os.getenv("CODE_SERVER_PASSWORD", "yourpassword") LOGIN_URL = f"{CODE_SERVER_URL}/login" SESSION = requests.Session() DEBUG = os.getenv("DEBUG", "False").lower() == "true" OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") # Set up logging logging.basicConfig( level=logging.DEBUG if DEBUG else logging.INFO, format="%(asctime)s [%(levelname)s]: %(message)s" ) def authenticate(): """Authenticates with the code-server.""" if not PASSWORD: logging.error("Password not set. Please set the 'CODE_SERVER_PASSWORD' environment variable.") return "Password not set." try: # Get the login page to retrieve CSRF token if needed (optional for code-server) response = SESSION.get(LOGIN_URL) response.raise_for_status() # Post the login credentials payload = {"password": PASSWORD} auth_response = SESSION.post(LOGIN_URL, data=payload) auth_response.raise_for_status() # Check if login was successful if auth_response.status_code == 200 and "code-server" in auth_response.text: logging.info("Authentication successful!") return "Authentication successful!" else: logging.warning("Authentication failed. Check your password or URL.") return "Authentication failed. Check your password or URL." except Exception as e: error_message = f"An unexpected error occurred: {e}" logging.error(error_message) return error_message # Define the LangChain agent tools tools = [ Tool( name="Authenticate with Code-Server", func=authenticate, description="Authenticate with the VS code-server. \ This is a one-time action and does not require further input. \ This action completes immediately." ) ] # Initialize the LangChain agent with OpenAI's LLM def main(): llm = OpenAI(openai_api_key=OPENAI_API_KEY, temperature=0) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True ) # Agent loop to take user input print("Simple AI Agent is ready! Type 'exit' to quit.") while True: user_input = input("\nEnter your instruction (type 'exit' to quit): ") if user_input.lower() in ["exit", "quit"]: print("Goodbye!") break try: # Get the agent's response for a single action response = agent.run(user_input) # Ensure that no further actions are taken after a single response if "Action:" in response: print("Ashwani Kumar Shamlodhiya: The AI has finished processing your request.") else: print(response) except Exception as e: logging.error(f"An error occurred: {e}") if __name__ == "__main__": main()
运行后收到以下错误:
Traceback (most recent call last): File "/home/coder/project/temp/aiagent-vscode-using-openaiTODO.py", line 113, in <module> main() File "/home/coder/project/temp/aiagent-vscode-using-openaiTODO.py", line 83, in main llm = OpenAI(openai_api_key=OPENAI_API_KEY, temperature=0) File "/home/coder/.local/lib/python3.9/site-packages/langchain_core/_api/deprecation.py", line 216, in warn_if_direct_instance return wrapped(self, *args, **kwargs) File "/home/coder/.local/lib/python3.9/site-packages/langchain_core/load/serializable.py", line 125, in __init__ super().__init__(*args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/pydantic/main.py", line 214, in __init__ validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self) File "/usr/local/lib/python3.9/dist-packages/pydantic/_internal/_decorators_v1.py", line 148, in _wrapper1 return validator(values) File "/home/coder/.local/lib/python3.9/site-packages/langchain_core/utils/pydantic.py", line 219, in wrapper return func(cls, values) File "/home/coder/.local/lib/python3.9/site-packages/langchain_community/llms/openai.py", line 322, in validate_environment values["client"] = openai.OpenAI(**client_params).completions File "/usr/local/lib/python3.9/dist-packages/openai/_client.py", line 123, in __init__ super().__init__( File "/usr/local/lib/python3.9/dist-packages/openai/_base_client.py", line 844, in __init__ self._client = http_client or SyncHttpxClientWrapper( File "/usr/local/lib/python3.9/dist-packages/openai/_base_client.py", line 742, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'proxies'
我的操作系统是Windows,请问有什么办法可以解决这个问题?
解决方案分析
这个错误核心是OpenAI SDK与LangChain系列包的版本不兼容导致的。新版本的OpenAI Python SDK(v1.x及以上)已经移除了proxies这个初始化参数,但旧版本的LangChain仍在尝试传递该参数,从而触发了类型错误。下面给你几个实用的解决办法:
方法一:安装兼容的版本组合
如果你不想改动代码,可以直接安装经过验证的兼容版本:- 先卸载现有冲突包:
pip uninstall -y openai langchain langchain-community - 安装指定版本:
这个版本组合能完美适配你当前的代码写法,不会出现参数冲突问题。pip install openai==0.28.1 langchain==0.1.10 langchain-community==0.0.23
- 先卸载现有冲突包:
方法二:升级到最新兼容版本(推荐)
如果想使用新版OpenAI SDK(v1.x+),需要同步升级LangChain并调整代码:- 升级所有相关包:
pip install --upgrade langchain langchain-community openai - 修改代码中的LLM初始化部分:
原来的导入和初始化要替换成:
新版LangChain已经把OpenAI相关的实现迁移到了# 替换旧的from langchain_community.llms import OpenAI from langchain_openai import OpenAI llm = OpenAI(api_key=OPENAI_API_KEY, temperature=0)langchain_openai包中,需要安装这个包的话可以执行pip install langchain-openai。
- 升级所有相关包:
方法三:调整代理配置(如果容器需要代理访问OpenAI)
如果你在Docker容器内需要通过代理访问OpenAI,不要依赖LangChain的旧代理参数,而是直接通过环境变量或requests会话设置:# 在代码开头添加环境变量代理(可选) os.environ['HTTP_PROXY'] = 'http://你的代理地址:端口' os.environ['HTTPS_PROXY'] = 'http://你的代理地址:端口' # 或者给requests.Session设置代理 SESSION = requests.Session() SESSION.proxies = { 'http': 'http://你的代理地址:端口', 'https': 'http://你的代理地址:端口', }
另外,别忘了检查Docker容器的网络连通性,可以在容器内执行curl https://api.openai.com/v1/models测试是否能正常访问OpenAI API,避免因网络问题引发其他错误。
备注:内容来源于stack exchange,提问作者Ashwani Shamlodhiya
相关产品推荐
相关产品推荐

