Calling OpenAI hangs when using Firestore emulator

25 views Asked by At

I am trying to build some code that will run as a Firebase function. The code will call OpenAI and then write the results to Firestore. However, when I try to run the code using the Firebase emulator, it is hanging. I have trimmed it down to the following minimal example. Any thoughts on how to work around this problem would be greatly appreciated. I am running Mac OS 14.0 and Python 3.11.8. I also tried Python 3.12.2.

This seems to be very similar to this problem, maybe even the same. But no answer was posted, so hoping for more input.

Thank you in advance for your help.

import os
from firebase_admin import initialize_app, firestore
import openai

# Configure Firestore to use the emulator

os.environ["FIRESTORE_EMULATOR_HOST"] = 'localhost:8080'
app = initialize_app()

# Note: You will need to replace "your-project-id" with your own project id
db = firestore.Client(project="your-project-id")

# Configure OpenAI

# Note: You will need to provide a valid OpenAI API key
OPENAI_API_KEY = "sk-..."
OPENAI_MODEL = "gpt-4"
messages = [{"role": "system", 
             "content": "You are an intelligent AI assistant."}, 
            {"role": "user", 
            "content": "Write python to code to generate the first 100 prime numbers."}]

# If the following line is uncommented, then the program will hang indefinitely.
# If the following line is commented out, then the program will run to completion
# after about 15 seconds.
db.collection("test").add({"test": "test"})   ### COMMENT OUT THIS LINE TO AVOID HANGING
openai_client = openai.OpenAI(api_key=OPENAI_API_KEY)
response = openai_client.chat.completions.create(
    model=OPENAI_MODEL,
    messages=messages,
)

print(response.choices[0].message.content)
0

There are 0 answers