in 11-recommendation/helper_functions.py [0:0]
def expand_query_with_llm(query: str, past_history: List[Dict[str, Any]]) -> str:
"""
Expands a user's query by leveraging OpenAI's language model to incorporate past history and categories.
:param query: The user's input message.
:param past_history: A list of dictionaries representing the user's past history.
:return: An expanded query string.
"""
try:
# Prepare the prompt for the language model
# Format past purchases as per the expected template
past_purchases_entries = "".join([
f"<past_purchase>Item: {purchase['product_name']}</past_purchase>" for purchase in past_history
])
system_prompt = f"""
You are an event planner with access to a product catalog. Your task is to:
1. **Analyze the User's Input**: Based on the user's stated goals, identify up to 7 relevant unique categories from the provided list that align with their interests and needs. Ensure that they are relevant to the user's goals.
2. **Select Relevant Categories**:
- Only include categories that are directly relevant to the user's input.
- Bias towards categories that are complementary to the user's past purchases. However, if the user's goal is not related to their past purchases, do not include any categories related to their past purchases.
3. **Craft Engaging Descriptions**:
- For each selected category, write a fun and playful description in 3 sentences to excite the user about their project.
- ONLY if applicable, mention how their past purchases contribute to their progress, highlighting that they're already on their way.
**Rules**:
- **Relevance**: Ensure all categories and descriptions are tailored to the user's input and past purchases.
- **Tone**: Maintain a fun and playful tone to engage the user.
- **Quantity**: Do not exceed 7 categories in your final list.
- **Include Essential and Complementary Categories**: Incorporate both categories that are essential for the user's project and those that offer complementary products (for example, patio furniture for a deck project).
- Utilize the past purchases provided, which are delimited by `<past_purchase>` tags, to personalize recommendations and reinforce progress. If the past purchase is not relevant, do not include it in the description.
**Example JSON**:
- Present your findings in a JSON format as shown in the example below, which is delimited by `</example>` tags.
<example>
{{
"categories": [
{{
"item": "Outdoors, Outdoor Heating",
"description": "Keep the party going even when the sun goes down! Your guests will love the warmth."
}},
{{
"item": "Garden Tools",
"description": "Let's get those green thumbs even greener! Your new shovel is itching to dig."
}}
]
}}
</example>
**Past Purchases**
{past_purchases_entries}
"""
response = openai_client.beta.chat.completions.parse(
model="gpt-4o",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": query}
],
response_format=CategoryRecommendations
)
# Extract the generated text
expanded_query = response.choices[0].message.content
logger.info("Query expanded successfully using LLM.")
return expanded_query
except Exception as e:
logger.error(f"Failed to expand query with LLM: {e}")
return query # Return the original query if expansion fails