TypeError: str expected, not NoneType - Docker run problem with .env file in python

32 Views Asked by At

I have a python RAG script that works fine locally (Windows).

My understanding is that the problem is related to the .env file when it is called in basic_rag.py

os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY')

When I run it with docker:

TypeError: str expected, not NoneType

This is the file structure:

APP
 chroma
 data
   text.pdf
 .env
 .gitignore
 basic_rag
 Dockerfile
 requirements.txt
 style

The Dockerfile code is:

FROM python:3.8-slim

WORKDIR /rag-test

COPY ./data  ./data/
COPY ./basic_rag.py ./main.py

COPY ./requirements.txt ./

RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8080

CMD ["python", "main.py"]

I am new to Docker and cannot find a solution for this Error.

Thanks for the help.

1

There are 1 best solutions below

3
David Maze On

The line you quote does nothing and you should just delete it.

You're getting a problem when the environment variable isn't already set. In that case, os.getenv() returns None. You're then trying to assign an environment variable the value None, but environment variables can only have string values.

Conversely, if the environment variable is already set, then this line takes the current value from the environment, and assigns the same environment variable the same value.

So, the only function of this line is to throw the error you show if the variable isn't set. You can give a clearer error, if that's the case:

if 'OPENAI_AI_KEY' not in os.environ:
  logging.critical('OPENAI_AI_KEY environment variable is not set')
  sys.exit(1)