import { smoothStream, streamText, generateText } from "ai";
import { createGoogleGenerativeAI } from "@ai-sdk/google";
const googleClient = createGoogleGenerativeAI({
apiKey: process.env.NEXT_PUBLIC_GOOGLE_API_KEY,
});
const generateItineraryPrompt = (prompt) => {
return `You are a travel itinerary expert. Generate a detailed travel itinerary based on the following requirements:
${prompt}
Please follow these guidelines:
1. Analyze the prompt to determine the start and end destinations, number of days, and any specific requirements
2. For each location mentioned in the itinerary, create:
a. A specific and optimized Google image search query that will return the best possible images. Follow these rules for image queries:
- Include the full name of the location
- Add descriptive terms like "landmark", "tourist spot", "famous", "beautiful", "scenic", "aerial view" where appropriate
- Include specific features or attractions of the location
- Use terms that will yield high-quality, professional photos
- Avoid generic terms that might return irrelevant results
- Format as: 
b. A Google Maps location query for places that need coordinates. Follow these rules for location queries:
- Always include the full name of the place
- Always include the city/area name
- Always include the country
- For restaurants: include "restaurant" and street name if available
- For hotels: include "hotel" and street name if available
- For attractions: include specific identifiers (e.g., "temple", "museum", "park")
- For meeting points: include nearby landmarks
- Format as: [Location Name](location: "specific location query")
- Use this format for ALL places that need coordinates: restaurants, hotels, attractions, meeting points, etc.
- Be as specific as possible to ensure accurate coordinates
3. Format the response in Markdown with the following structure:
# Travel Itinerary
## Overview
- Brief summary of the trip
- Total duration
- Main highlights
## Day-by-Day Breakdown
### Day 1: [Location Name]

#### Morning
- Activity 1 (Time) at [Place Name](location: "Place Name, Street Name, City, Country")
- Activity 2 (Time) at [Place Name](location: "Place Name, Street Name, City, Country")
#### Afternoon
- Lunch at [Restaurant Name](location: "Restaurant Name, Street Name, City, Country restaurant")
- Activity 1 (Time) at [Place Name](location: "Place Name, Street Name, City, Country")
#### Evening
- Dinner at [Restaurant Name](location: "Restaurant Name, Street Name, City, Country restaurant")
- Activity 1 (Time) at [Place Name](location: "Place Name, Street Name, City, Country")
#### Accommodation
- [Hotel Name](location: "Hotel Name, Street Name, City, Country hotel")
- Estimated cost
#### Local Cuisine
- Restaurant recommendations with location queries
- Must-try dishes
#### Transportation
- How to get there
- Estimated cost
[Repeat for each day]
## Budget Breakdown
- Accommodation
- Transportation
- Activities
- Food
- Miscellaneous
## Travel Tips
- Best time to visit
- Local customs and etiquette
- Safety considerations
- Packing suggestions
Make sure to:
1. Include specific details about each location and activity
2. Provide accurate time estimates
3. Include practical information like costs and transportation options
4. Format all content in proper Markdown
5. For each location:
- Create an optimized image search query that will return the best possible images
- Add a location query for places that need coordinates
6. Use the formats:
-  for images
- [Location Name](location: "specific location query") for Google Maps coordinates
Example of good queries:
- Image query for Eiffel Tower: "Eiffel Tower Paris landmark aerial view sunset"
- Location query for Eiffel Tower: "Eiffel Tower, Champ de Mars, 75007 Paris, France"
- Image query for Tokyo Skytree: "Tokyo Skytree Japan modern architecture night view"
- Location query for Tokyo Skytree: "Tokyo Skytree, 1 Chome-1-2 Oshiage, Sumida City, Tokyo, Japan"
- Image query for Grand Canyon: "Grand Canyon Arizona USA scenic landscape aerial view"
- Location query for Grand Canyon: "Grand Canyon National Park, Arizona, United States"
- Image query for Sensō-ji Temple: "Sensō-ji Temple Tokyo Asakusa district famous pagoda"
- Location query for Sensō-ji Temple: "Sensō-ji Temple, 2 Chome-3-1 Asakusa, Taito City, Tokyo, Japan"
- Image query for Le Jules Verne: "Le Jules Verne Restaurant Eiffel Tower Paris fine dining"
- Location query for Le Jules Verne: "Le Jules Verne Restaurant, Eiffel Tower, 75007 Paris, France"
- Image query for Park Hyatt Tokyo: "Park Hyatt Tokyo hotel luxury rooms city view"
- Location query for Park Hyatt Tokyo: "Park Hyatt Tokyo, 3-7-1-2 Nishishinjuku, Shinjuku City, Tokyo, Japan"`;
};
export default async function handler(req, res) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Method Not Allowed" });
}
try {
const { prompt } = req.body;
if (!prompt) {
return res.status(400).json({ error: "Missing prompt parameter" });
}
// Set headers for streaming
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.setHeader("Transfer-Encoding", "chunked");
const result = await streamText({
model: googleClient("gemini-1.5-flash"),
messages: [
{
role: "system",
content: generateItineraryPrompt(prompt),
},
{
role: "user",
content: prompt,
},
],
temperature: 0.7,
streamProtocol: true,
});
try {
for await (const chunk of result.textStream) {
res.write(chunk);
res.flush();
}
res.end();
} catch (streamError) {
console.error("Streaming error:", streamError);
res.write(
`data: ${JSON.stringify({
error: "Streaming error",
details: streamError.message,
})}\n\n`
);
res.end();
}
} catch (error) {
console.error("API Error:", error);
res.write(
`data: ${JSON.stringify({
error: "Internal Server Error",
details: error.message,
})}\n\n`
);
res.end();
}
}