Ramesh Adhikari
Ramesh Adhikari

Reputation: 21

How to Optimize Prompt Engineering for Financial Advice from the FinguAI Language Model?

I'm working on a personal finance application that uses the FinguAI language model to generate personalized insights and financial advice based on user-provided expense data. However, I'm facing challenges in getting the model to produce accurate and relevant responses.

Here's what I've tried so far:

Simplified the input data and formatted it as JSON. Iterated on various prompts, providing explicit instructions and desired output format. Experimented with temperature and top-p parameters. Despite these efforts, the model's responses often lack accuracy, miss crucial details, or offer generic advice that's not tailored to the specific user data.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextStreamer
import pandas as pd
from datetime import datetime, timedelta
import random
import json

# Define categories
categories = ["Groceries", "Utilities", "Entertainment", "Transport", "Rent", "Miscellaneous"]

# Generate dummy data (replace with your actual data later)
data = []
for i in range(30):
    date = (datetime.now() - timedelta(days=i)).strftime("%Y-%m-%d")
    category = random.choice(categories)
    amount = round(random.uniform(100, 1000), 2)  # Adjust random amount range for more realistic data
    description = f"{category} expense"
    data.append([date, category, amount, description])

df = pd.DataFrame(data, columns=["Date", "Category", "Amount", "Description"])
category_totals = df.groupby('Category')['Amount'].sum().to_dict()

# --- VARIABLES TO CHANGE ---
monthly_income = 5000  # Replace with the user's actual monthly income in ₹
# --- END VARIABLES TO CHANGE ---

# Format the category totals for the prompt
category_totals_string = "\n".join([f"- {category}: ₹{amount:.2f}" for category, amount in category_totals.items()])

# Load the model and tokenizer
model_id = 'FINGU-AI/FinguAI-Chat-v1'
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained(model_id)
streamer = TextStreamer(tokenizer)
model.to('cuda')  # Move model to GPU if available

# Create the prompt with improved instructions
prompt_template = """You are a financial advisor in India analyzing monthly expenses for a user earning ₹{income}.
Their goal is to improve financial health.

Analyze this spending data (in ₹):

{expenses_string}

Provide personalized insights and actionable suggestions focusing on:

1.  Top 2 highest spending categories and 2-3 specific, actionable ways to reduce spending in each.
2.  Lowest spending category and if any adjustments are needed there.
3.  Realistic monthly savings goal, considering their income and expenses.
4.  Overall financial health assessment, including strengths, weaknesses, and potential risks.
"""

prompt = prompt_template.format(income=monthly_income, expenses_string=category_totals_string)


# Tokenize the input
tokenized_chat = tokenizer.apply_chat_template([{"role": "user", "content": prompt}], tokenize=True, add_generation_prompt=True, return_tensors="pt").to("cuda")


# Set generation parameters
generation_params = {
    'max_new_tokens': 250,
    'use_cache': True,
    'do_sample': True,
    'temperature': 0.7,
    'top_p': 0.95,
    'top_k': 50,
    'eos_token_id': tokenizer.eos_token_id,
}

# Generate insights
outputs = model.generate(tokenized_chat, **generation_params, streamer=streamer)
decoded_outputs = tokenizer.batch_decode(outputs)

print(decoded_outputs[0])

Response:

Assessment of支出 in the user's monthly expenses data: 1. Entertainment: A notable expenditure that results in an average of around 1013.13 in姬ar Rupee ($). This category could be reduced by allocating funds towards hobbies or leisure activities that align with the user's personality or interests. For example, investing in a subscription service like Netflix or shopping at local markets can be cost-effective alternatives to entertainment expenditures. Additionally, allocating a portion of the budget towards entertainment would allow for a more balanced and fulfilling lifestyle without compromising the quality of life. The user should prioritize spending in areas that bring them joy and fulfillment, such as self-care, hobbies, or hobbies that they enjoy. It's crucial to track these amounts regularly to ensure continued satisfaction with their overall financial well-being and goals. 2. Groceries: In姬ar Rupee ($), groceries accounted for approximately $2590.55. To reduce expenses in grocery purchases, the user can adopt a portion-based approach, where they spend a portion of their姬ar Rupee per week on groceries. For instance, instead of spending full weeks on groceries, the user might allocate $50 in姬ar Rupee each month to purchase items that they

Upvotes: 2

Views: 33

Answers (1)

Shumyl
Shumyl

Reputation: 1

Use a new prompt engineering technique called "chain of thought". I was working on developing a customer service assistant for an organization and had similar issues related to accuracy, precision and tone etc. By chain of thought what I mean is give examples in the prompt of the process you want the financial advisor agent to give. For instnace,

prompt_template = """You are a financial advisor in India analyzing monthly expenses for a user earning ₹{income}.
Their goal is to improve financial health.

Analyze this spending data (in ₹):

{expenses_string}

Follow this step-by-step process to generate insights and suggestions:

### Example 1:

Input: Income = ₹80,000  
Expenses:
- Rent: ₹25,000  
- Groceries: ₹10,000  
- Dining Out: ₹8,000  
- Entertainment: ₹5,000  
- Transportation: ₹7,000  
- Utilities: ₹3,000  
- Savings: ₹12,000  

Step 1: Identify Top 2 Highest Spending Categories.
- Top 2 categories: Rent (₹25,000) and Dining Out (₹8,000).  

Step 2: Provide 2-3 Specific Ways to Reduce Spending. 
- Rent: Explore sharing accommodations or relocating to a less expensive area (potential savings ₹5,000–₹7,000).  
- Dining Out: Reduce frequency of eating out, switch to home-cooked meals, and set a dining budget (potential savings ₹3,000–₹5,000).  

Step 3: Identify the Lowest Spending Category.
- Utilities (₹3,000) appear balanced. No changes recommended.  

Step 4: Suggest a Realistic Monthly Savings Goal. 
- Suggested Savings Target: ₹15,000 per month (additional ₹3,000 from adjustments).  

Step 5: Assess Overall Financial Health.
- Strengths: Current savings are ₹12,000, indicating a savings habit.  
- Weaknesses: High spending on discretionary categories like dining and entertainment.  
- Risks: Low emergency fund coverage; recommend reallocating reduced expenses toward an emergency fund.  


### Example 2:

Give another example here.


### Final Instructions for Analysis:
Follow the above process step-by-step to evaluate the provided income and expenses. Offer clear, actionable suggestions aligned with the user’s goal of improving financial health."""

Upvotes: 0

Related Questions