# gemini_utils.py import os import time import backoff import google.generativeai as genai from typing import Dict, List # Load the Gemini API key from environment variables GOOGLE_API_KEY="AIzaSyDuDPP0eWWA0UsGBBIeOI7Fl0WcPli4Sdo" genai.configure(api_key=GOOGLE_API_KEY) # Initialize the model once model = genai.GenerativeModel(model_name="gemini-1.5-flash") @backoff.on_exception( backoff.expo, Exception, max_tries=3, giveup=lambda e: "rate limit" not in str(e).lower() and "timeout" not in str(e).lower(), max_value=20 ) def generate_with_gemini(prompt: str, max_tokens: int = 2048, temperature: float = 0.7) -> str: """ Generates a response from the Gemini model using the given prompt. Retries on transient errors using exponential backoff. """ try: response = model.generate_content( prompt, generation_config={ "max_output_tokens": max_tokens, "temperature": temperature } ) return response.text except Exception as e: print(f"Gemini API Error: {str(e)}") raise e def create_travel_plan_prompt(travel_data: Dict) -> str: """ Constructs a prompt to generate a travel itinerary based on user-provided data. """ destination = travel_data.get("destination") or "a suitable destination based on additional preferences" location_type = travel_data.get("location_type") province = travel_data.get("province") starting_location = travel_data.get("starting_location") or "Pakistan" gender = travel_data.get("gender") num_people = travel_data.get("num_people") has_children = travel_data.get("has_children") activity_type = travel_data.get("activity_type") travel_group = travel_data.get("travel_group") preferences = ", ".join(travel_data.get("preferences", [])) or "None" budget = travel_data.get("budget", 0) num_days = travel_data.get("num_days") additional_preferences = travel_data.get("additional_preferences", "") or "None" budget_str = f"They have a budget of {budget} PKR" if budget > 0 else "No specific budget is provided" prompt = f"""You are a travel expert specializing in Pakistan. Create a detailed {num_days}-day travel itinerary for {num_people} people, including {gender.lower()} travelers, who are {travel_group.lower()}, {'with children' if has_children else 'without children'}, starting from {starting_location}. {'They want to visit ' + destination + '.' if destination != 'a suitable destination based on additional preferences' else 'Suggest a suitable destination based on their preferences.'} The destination is a {location_type} in {province}. They prefer {activity_type.lower()} activities and are interested in {preferences}. {budget_str}. Additional requests: {additional_preferences} INCLUDE ALL THE FOLLOWING SECTIONS in your itinerary, using simple and clear language: 1. **Itinerary Overview:** - Destination: [Destination Name] - Brief summary of the trip - Key highlights and attractions - Best time to visit the destination - If no destination is specified, explain why the suggested destination was chosen 2. **Daily Itinerary:** - For each day (Day 1 to Day {num_days}), provide: - Morning, afternoon, and evening activities - Meal suggestions (local cuisine where possible) - Accommodation recommendations (hotels, guesthouses, etc.) 3. **Transportation:** - How to travel from {starting_location} to the destination (e.g., flights, buses) - Local transportation options within the destination 4. **Safety and Health:** - Safety precautions, especially for children if applicable - Health considerations or recommended vaccinations 5. **Cultural Etiquette:** - Important cultural norms to respect 6. **Estimated Costs:** - Detailed cost breakdown for activities, meals, accommodations, and transportation - Ensure the itinerary fits within the budget if provided, or provide approximate costs 7. **Travel Tips:** - Practical tips for a smooth trip (e.g., packing, local customs, safety) 8. **Contingency Plans:** - Alternatives for bad weather, cancellations, or other issues Format the itinerary using Markdown with clear headers (# for main sections, ## for days) and consistent structure for each day. """ return prompt def create_chat_prompt(plan: str, destination: str, num_days: int, history: List[Dict], user_input: str) -> str: """ Constructs a prompt for a chat interaction based on an existing travel plan and chat history. """ conversation = "" for msg in history: conversation += f"{msg['role'].capitalize()}: {msg['content']}\n" prompt = f"""You are a helpful travel assistant. The user has a {num_days}-day travel plan for {destination}. The plan is: {plan} Conversation history: {conversation} User: {user_input} Assistant:""" return prompt