Spaces:
Sleeping
Sleeping
| import os | |
| from openai import OpenAI | |
| from dotenv import load_dotenv | |
| # Load environment variables | |
| load_dotenv() | |
| # OpenAI configuration | |
| api_key = os.environ.get("OPENAI_API_KEY") | |
| if not api_key: | |
| raise ValueError("OPENAI_API_KEY environment variable is not set. Please set it and try again.") | |
| client = OpenAI(api_key=api_key) | |
| OPENAI_MODEL = "gpt-3.5-turbo" | |
| def get_ai_response(messages): | |
| """ | |
| Get a response from the AI model using the OpenAI client. | |
| :param messages: List of message dictionaries as expected by OpenAI API | |
| :return: The content of the AI's response | |
| """ | |
| try: | |
| response = client.chat.completions.create( | |
| model=OPENAI_MODEL, | |
| messages=messages | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| print(f"Error getting AI response: {str(e)}") | |
| return None |