import openai
from openai import OpenAI
from fastchat.conversation import get_conv_template
import time
class OpenaiModel():
    def __init__(self, model_name: str):
        self.model_name = model_name
        self.api_key = ""

        self.client = OpenAI(
        api_key=self.api_key,
        base_url=''
        )  

        self.conversation = get_conv_template('chatgpt')

    def generate_response(self, messages, **kwargs):
        for _ in range(20): 
            try:
                response = self.client.chat.completions.create(
                    model=self.model_name,
                    messages=[
                        {"role": "user", "content": messages},
                    ],
                    temperature=0,
                    **kwargs
                )
                result=response.choices[0].message.content
                # time.sleep(5)
                break
            except openai.APIConnectionError as e:
                print("The server could not be reached")
                print(e.__cause__)  # an underlying Exception, likely raised within httpx.
            except openai.RateLimitError as e:
                print("A 429 status code was received; we should back off a bit.")
            except openai.APIStatusError as e:
                print("Another non-200-range status code was received")
                print(e.status_code)
                print(e.response)
            time.sleep(4)
        
        return result
    
def getResponse(prompt, model_name):
    model_instance = OpenaiModel(model_name)
    response = model_instance.generate_response(prompt)

    return response