Getting connection error when trying to connect to OpenAI API

I keep getting connection errors whenever I try to make requests to OpenAI’s API in my chatbot application. I’m building this app using streamlit and langchain but can’t get past this connection issue.

I already checked the official docs and tried different solutions but nothing works. The error happens when I call the API to process user messages.

Here’s the error I’m seeing:

Traceback (most recent call last):
  File "C:\Users\Dev\anaconda3\envs\chat_app\Lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 600, in _run_script
    exec(code, module.__dict__)
  File "C:\Users\Dev\Desktop\projects\chat_app\main.py", line 91, in <module>
    processed_input = input_processor(chat_history, user_input)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Dev\Desktop\projects\chat_app\helpers.py", line 42, in input_processor
    result = openai_client.completions.create(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Dev\anaconda3\envs\chat_app\Lib\site-packages\openai\_base_client.py", line 986, in _request
    raise APIConnectionError(request=request) from err
openai.APIConnectionError: Connection error.

And here’s my code:

with st.spinner("processing..."):
    chat_history = build_chat_history()
    processed_input = input_processor(chat_history, user_input)

def input_processor(history, user_message):
    result = openai_client.completions.create(
        model="gpt-3.5-turbo",
        prompt=f"""Based on the chat history and current message, create a refined question for knowledge base search.\n\nCHAT HISTORY: \n{history}\n\nUser Message: {user_message}\n\nRefined Question:""",
        temperature=0.8,
        max_tokens=200,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )
    return result['choices'][0]['text']

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

for sure! it sounds like you’re hitting the endpoint wrong. try using openai_client.chat.completions.create() for GPT-3.5-turbo. make sure you format the messages with system and user roles. that oughtta do it!