import openai

# Initialize OpenAI API key
openai.api_key = "YOUR_API_KEY"

def generate_response(prompt, conversation_history):
    """
    Send prompt and conversation history to GPT-4 and receive response.
    """
    try:
        # Prepare conversation with previous history and current prompt
        messages = [{"role": "system", "content": "You are an AI assistant."}]
        messages.extend(conversation_history)
        messages.append({"role": "user", "content": prompt})

        # Generate response from GPT-4
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=messages,
            max_tokens=150,
            n=1,
            stop=None,
            temperature=0.7,
        )

        # Extract response text
        message = response['choices'][0]['message']['content'].strip()
        return message

    except Exception as e:
        print(f"Error generating response: {e}")
        return "I'm having trouble generating a response at the moment."

def main():
    """
    Main function to run the AI agent in a conversational loop.
    """
    conversation_history = []

    print("Hello! I'm your AI assistant. Type 'exit' to end the conversation.")
    
    while True:
        user_input = input("You: ")
        
        if user_input.lower() == "exit":
            print("Goodbye!")
            break
        
        # Add user's message to conversation history
        conversation_history.append({"role": "user", "content": user_input})

        # Generate and print AI's response
        response = generate_response(user_input, conversation_history)
        print("AI: " + response)

        # Add AI's response to conversation history
        conversation_history.append({"role": "assistant", "content": response})

if __name__ == "__main__":
    main()