英文:
How do I correctly set up an API key in Google Cloud Platform?
问题
我正在尝试在GCP中部署一个需要OpenAI API密钥的项目。我将API密钥设置为环境变量,方法如下:
export OPENAI_API_KEY='sh-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
并且我可以在Python中访问它,如下所示:
然而,当我构建项目的Docker镜像并尝试运行它时,它会出现以下错误:
$ docker run app
[nltk_data] Downloading package punkt to /root/nltk_data...
[nltk_data] Unzipping tokenizers/punkt.zip.
Traceback (most recent call last):
File "/app/app.py", line 9, in <module>
os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY")
File "/usr/local/lib/python3.9/os.py", line 684, in __setitem__
value = self.encodevalue(value)
File "/usr/local/lib/python3.9/os.py", line 756, in encode
raise TypeError("str expected, not %s" % type(value).__name__)
TypeError: str expected, not NoneType
所以,这里有什么问题?
如果我执行以下操作,就不会出现任何错误:
$ python
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits", or "license" for more information.
>>> import os
>>> os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY")
>>>
所以,我不明白为什么在运行Docker镜像时会出现这个错误。
英文:
I am trying to deploy a project in GCP that needs OpenAI API key. I set the API key as an environment variable from the cloud shell terminal as follows:
export OPENAI_API_KEY='sh-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
And I can access it using Python as you can see here:
However, after I build a docker image of the project and try to run it, it gives the following error:
$ docker run app
[nltk_data] Downloading package punkt to /root/nltk_data...
[nltk_data] Unzipping tokenizers/punkt.zip.
Traceback (most recent call last):
File "/app/app.py", line 9, in <module>
os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY")
File "/usr/local/lib/python3.9/os.py", line 684, in __setitem__
value = self.encodevalue(value)
File "/usr/local/lib/python3.9/os.py", line 756, in encode
raise TypeError("str expected, not %s" % type(value).__name__)
TypeError: str expected, not NoneType
So, what's wrong here?
If I do the following, I don't get any error:
$ python
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['OPENAI_API_KEY'] = os.getenv("OPENAI_API_KEY")
>>>
So I don't understand why it is giving this error when running the docker image.
答案1
得分: 2
Docker无法访问主机环境变量。您需要通过docker run
调用传递它们,使用-e|--env
参数。您可以尝试:
docker run -e OPENAI_API_KEY='sh-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' app
或者
docker run -e OPENAI_API_KEY="$OPENAI_API_KEY" app
英文:
Docker does not have access to the host environment variables. You need to pass them into the docker run
call via -e|--env
. Could you try:
docker run -e OPENAI_API_KEY='sh-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' app
or
docker run -e OPENAI_API_KEY="$OPENAI_API_KEY" app
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论