2025-05-13 08:30:59 -07:00
|
|
|
import logging
|
|
|
|
|
from typing import List
|
2025-06-11 21:24:15 +05:30
|
|
|
|
2025-07-08 10:57:25 +05:30
|
|
|
from app.utils.prompts import MEMORY_CATEGORIZATION_PROMPT
|
2025-05-13 08:30:59 -07:00
|
|
|
from dotenv import load_dotenv
|
2025-06-11 21:24:15 +05:30
|
|
|
from openai import OpenAI
|
2025-05-13 08:30:59 -07:00
|
|
|
from pydantic import BaseModel
|
|
|
|
|
from tenacity import retry, stop_after_attempt, wait_exponential
|
|
|
|
|
|
|
|
|
|
load_dotenv()
|
|
|
|
|
openai_client = OpenAI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class MemoryCategories(BaseModel):
|
|
|
|
|
categories: List[str]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=15))
|
|
|
|
|
def get_categories_for_memory(memory: str) -> List[str]:
|
|
|
|
|
try:
|
2025-06-11 21:24:15 +05:30
|
|
|
messages = [
|
|
|
|
|
{"role": "system", "content": MEMORY_CATEGORIZATION_PROMPT},
|
|
|
|
|
{"role": "user", "content": memory}
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
# Let OpenAI handle the pydantic parsing directly
|
2025-06-25 11:32:26 -05:00
|
|
|
completion = openai_client.beta.chat.completions.parse(
|
2025-05-13 08:30:59 -07:00
|
|
|
model="gpt-4o-mini",
|
2025-06-11 21:24:15 +05:30
|
|
|
messages=messages,
|
2025-06-25 11:32:26 -05:00
|
|
|
response_format=MemoryCategories,
|
2025-06-11 21:24:15 +05:30
|
|
|
temperature=0
|
2025-05-13 08:30:59 -07:00
|
|
|
)
|
2025-06-11 21:24:15 +05:30
|
|
|
|
|
|
|
|
parsed: MemoryCategories = completion.choices[0].message.parsed
|
|
|
|
|
return [cat.strip().lower() for cat in parsed.categories]
|
|
|
|
|
|
2025-05-13 08:30:59 -07:00
|
|
|
except Exception as e:
|
2025-06-11 21:24:15 +05:30
|
|
|
logging.error(f"[ERROR] Failed to get categories: {e}")
|
|
|
|
|
try:
|
|
|
|
|
logging.debug(f"[DEBUG] Raw response: {completion.choices[0].message.content}")
|
|
|
|
|
except Exception as debug_e:
|
|
|
|
|
logging.debug(f"[DEBUG] Could not extract raw response: {debug_e}")
|
|
|
|
|
raise
|