Getting Connection Error with OpenAI API in Python Application

I keep getting a connection error when trying to connect to OpenAI’s API in my Python app. I’m building a chatbot using streamlit and langchain but can’t get past this issue.

I’ve checked the OpenAI docs but nothing seems to work. The error happens every time I try to make a request.

Here’s my code:

def enhance_user_input(chat_history, user_message):
    api_response = openai_client.completions.create(
        model="gpt-3.5-turbo",
        prompt=f"""Based on this chat history and user message, create a better question for searching our database.\n\nCHAT HISTORY: \n{chat_history}\n\nUser Message: {user_message}\n\nImproved Question:""",
        temperature=0.5,
        max_tokens=200,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )
    return api_response['choices'][0]['text']

def build_chat_history():
    full_conversation = ""
    for index in range(len(st.session_state['bot_replies'])-1):
        full_conversation += "User: " + st.session_state['user_messages'][index] + "\n"
        full_conversation += "Assistant: " + st.session_state['bot_replies'][index+1] + "\n"
    return full_conversation

# Main execution
with st.spinner("Processing..."):
    chat_context = build_chat_history()
    improved_question = enhance_user_input(chat_context, user_input)

The error shows up when calling the completions.create method. Has anyone faced this before?