Error when creating a chatbot using Streamlit with API interface using `AzureOpenAI()`

I am having issues running the chatbot using streamlit. I am using python version 3.11.2. The error output is the following in the localost link:

NameError:

name 'sys' is not defined

Traceback:

File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesstreamlitruntimescriptrunnerscript_runner.py", line 600, in _run_script
    exec(code, module.__dict__)
File "C:Usersxxxxapp.py", line 17, in <module>
    completion = generate_chat_completion(user_input)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:Usersxxxxhandlers.py", line 24, in generate_chat_completion
    completion = client.chat.completions.create(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_utils.py", line 299, in wrapper
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenairesourceschatcompletions.py", line 600, in create
    body=maybe_transform(
         ^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 72, in maybe_transform
    return transform(data, expected_type)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 94, in transform
    transformed = _transform_recursive(data, annotation=cast(type, expected_type))
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 167, in _transform_recursive
    data = _transform_recursive(data, annotation=annotation, inner_type=subtype)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 155, in _transform_recursive
    return _transform_typeddict(data, stripped_type)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 213, in _transform_typeddict
    result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_)
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 159, in _transform_recursive
    return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 159, in <listcomp>
    return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 167, in _transform_recursive
    data = _transform_recursive(data, annotation=annotation, inner_type=subtype)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 155, in _transform_recursive
    return _transform_typeddict(data, stripped_type)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 213, in _transform_typeddict
    result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_)
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagesopenai_utils_transform.py", line 170, in _transform_recursive
    if isinstance(data, pydantic.BaseModel):
                        ^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libsite-packagespydantic__init__.py", line 383, in __getattr__
    module = import_module(module_name, package=package)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:UsersxxxxAppDataLocalProgramsPythonPython311Libimportlib__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
File "<frozen importlib._bootstrap>", line 1172, in _find_and_load

I created two files in Visual Code:

The file called handlers.py:

import openai, os, requests, json, tiktoken, openpyxl, sys
from openai import AzureOpenAI
import pandas as pd
from dotenv import load_dotenv
from colorama import Fore

client = AzureOpenAI(
    azure_endpoint = "https:...openai.azure.com/",
    api_key = "...",
    api_version="...",
)

MESSAGE_SYSTEM = """"You are a skilled stand-up comedian with a quick wit and charismatic presence for telling short clever storytelling and ability to 
connect with diverse audiences through humor that is both insightful and relatable."""
messages = [{"role": "system", "content": MESSAGE_SYSTEM}]

def to_dict(obj):
    return {
        "content": obj.content,
        "role": obj.role,
    }

   
def generate_chat_completion(user_input=""):
    messages.append({"role": "user", "content": user_input})
    completion = client.chat.completions.create(
        model="gpt-4",
        messages=messages
    )
    message = completion.choices[0].message
    messages.append(to_dict(message))
    return message.content

2nd file called app.py

import streamlit as st
from handlers import generate_chat_completion

st.title("???? Funny Chatbot App")

with st.form("user_form", clear_on_submit=True):
    user_input = st.text_input("Type something")
    submit_button = st.form_submit_button(label="Send")

if submit_button:
    completion = generate_chat_completion(user_input)
    st.write(completion)

To further isolate the issue,I created a simple test script to check in Jupyter Notebook if the API call works independently of Streamlit and it did with the following code:

import openai, os, requests, json, tiktoken, openpyxl, sys
from openai import AzureOpenAI
import pandas as pd
from dotenv import load_dotenv
from colorama import Fore

client = AzureOpenAI(
    azure_endpoint = "https://...openai.azure.com/",
    api_key = "...",
    api_version="...",
)

MESSAGE_SYSTEM = """"You are a skilled stand-up comedian with a quick wit and charismatic presence for telling short clever storytelling and ability to 
connect with diverse audiences through humor that is both insightful and relatable."""
messages = [{"role": "system", "content": MESSAGE_SYSTEM}]

def to_dict(obj):
    return {
        "content": obj.content,
        "role": obj.role,
    }

   
def generate_chat_completion(user_input=""):
    messages.append({"role": "user", "content": user_input})
    completion = client.chat.completions.create(
        model="gpt-4",
        messages=messages
    )
    message = completion.choices[0].message
    messages.append(to_dict(message))
    return message.content

if __name__ == "__main__":
    user_input = "Tell me a joke."
    completion = generate_chat_completion(user_input)
    print(completion)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật