HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: /var/www/html/calendar-planning/app/utils/openai_utils.py
from openai import OpenAI
from django.conf import settings
from pydantic import BaseModel, Field

import os
from dotenv import load_dotenv
load_dotenv()

# client = OpenAI(api_key=settings.OPENAI_API_KEY)
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

class EventDetail(BaseModel):
    name : str = Field(..., description="Name of the event")
    date : str = Field(..., description="Starting date of the event in DD-MM-YYY format if present else use NA")
    location : str = Field(..., description="Location of the event city or country if present else use NA")
    

class Event(BaseModel):
    category : str = Field(..., description="Event category given by the user")
    event_detail: list[EventDetail]


def generate_events(user_prompt:str, model:str = "gpt-4o-mini") -> dict:
    
    system_prompt ='''You will be provided with a Category, Year, Location, and text scraped from a website. Your task is to extract and generate unique event details that are relevant to the given Category, Year, and Location. Ensure that all event details are distinct, with no duplicate event names or repetitive entries. Each event should be explicitly tied to the inputs provided, and any event lacking sufficient information in the text should be excluded. Focus on accuracy and avoid assumptions, ensuring the generated content is clear, complete, and free from redundancy.'''

    completion = client.beta.chat.completions.parse(
        model=model,
        messages=[
            # {"role": "system", "content": "You will be provided with a Category, Year, Location and text scrapped from a website. Your task is to generate all possible event details relevant to the given Category, Year and Location from the given text. All event detail must be unique."},
            {"role": "system", "content": system_prompt},           
            {"role": "user", "content": user_prompt}
        ],
        response_format=Event,
        max_tokens= 16384
    )

    result = completion.choices[0].message    
    
    if result.parsed:
        # print(result.parsed)
        # print(result)
        return result.parsed
    else:
        print("No result")
        return {}
    

# Function calling

tools = [
    {
        "type": "function",
        "function": {
            "name": "search_web",
            "description": "Search the web using google search",
            "parameters": {
                "type": "object",
                "properties": {
                    "search_query": {
                        "type": "string",
                        "description": "The query to be searched.",
                    },
                    "format": {
                        "type": "string",
                        "description": "The result of web search.",
                    },
                },
                "required": ["search_query"],
            },
        }
    }
]

def chat_completion_request(messages, tools=None, tool_choice=None, model="gpt-4o-mini"):
    try:
        response = client.chat.completions.create(
            model=model,
            messages=messages,
            tools=tools,
            tool_choice=tool_choice,
        )
        return response
    except Exception as e:
        print("Unable to generate ChatCompletion response")
        print(f"Exception: {e}")
        return e