openfree commited on
Commit
80cb626
·
verified ·
1 Parent(s): 71b8a5a

Rename travel.py to paper.py

Browse files
Files changed (2) hide show
  1. paper.py +199 -0
  2. travel.py +0 -453
paper.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ from datetime import datetime, timedelta
5
+ from langchain_google_genai import ChatGoogleGenerativeAI
6
+ from langchain.schema import SystemMessage, HumanMessage
7
+
8
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
9
+
10
+ class Agent:
11
+ def __init__(self, role: str, goal: str, backstory: str, personality: str = "", llm=None) -> None:
12
+ """
13
+ Initialize an Agent with role, goal, backstory, personality, and assigned LLM.
14
+ """
15
+ self.role = role
16
+ self.goal = goal
17
+ self.backstory = backstory
18
+ self.personality = personality
19
+ self.tools = [] # Initialize with empty list for future tool integrations
20
+ self.llm = llm
21
+
22
+ class Task:
23
+ def __init__(self, description: str, agent: Agent, expected_output: str, context=None) -> None:
24
+ """
25
+ Initialize a Task with its description, the responsible agent, expected output, and optional context.
26
+ """
27
+ self.description = description
28
+ self.agent = agent
29
+ self.expected_output = expected_output
30
+ self.context = context or []
31
+
32
+ google_api_key = os.getenv("GEMINI_API_KEY") # 실제 Google API 키 사용
33
+ if not google_api_key:
34
+ logging.error("GEMINI_API_KEY is not set in the environment variables.")
35
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=google_api_key)
36
+
37
+ # -------------------------------------------------------------------------------
38
+ # Define Academic Research Agents
39
+ # -------------------------------------------------------------------------------
40
+ literature_research_agent = Agent(
41
+ role="Literature Research Agent",
42
+ goal="Research and provide a comprehensive review of existing literature on the research topic.",
43
+ backstory="An experienced academic researcher specialized in literature reviews and meta-analyses.",
44
+ personality="Analytical, thorough, and detail-oriented.",
45
+ llm=llm,
46
+ )
47
+
48
+ outline_agent = Agent(
49
+ role="Outline Agent",
50
+ goal="Generate a structured and detailed outline for a research paper based on the research topic and literature.",
51
+ backstory="A methodical academic planner who organizes research findings into coherent paper structures.",
52
+ personality="Organized, systematic, and insightful.",
53
+ llm=llm,
54
+ )
55
+
56
+ draft_writing_agent = Agent(
57
+ role="Draft Writing Agent",
58
+ goal="Compose a first draft of the research paper based on the literature review and outline.",
59
+ backstory="A skilled academic writer capable of synthesizing research findings into well-structured drafts.",
60
+ personality="Articulate, precise, and scholarly.",
61
+ llm=llm,
62
+ )
63
+
64
+ citation_agent = Agent(
65
+ role="Citation Agent",
66
+ goal="Generate a list of relevant citations and references in the required format for the research paper.",
67
+ backstory="A detail-oriented bibliographic expert with extensive knowledge of citation standards.",
68
+ personality="Meticulous, accurate, and research-savvy.",
69
+ llm=llm,
70
+ )
71
+
72
+ editing_agent = Agent(
73
+ role="Editing Agent",
74
+ goal="Revise and polish the draft for clarity, coherence, and academic tone.",
75
+ backstory="An expert editor skilled in improving academic manuscripts and ensuring high-quality presentation.",
76
+ personality="Critical, precise, and supportive.",
77
+ llm=llm,
78
+ )
79
+
80
+ chatbot_agent = Agent(
81
+ role="Chatbot Agent",
82
+ goal="Engage in interactive conversation to answer queries related to the academic research process.",
83
+ backstory="A conversational AI assistant with extensive knowledge in academia and research methodologies.",
84
+ personality="Helpful, conversational, and knowledgeable.",
85
+ llm=llm,
86
+ )
87
+
88
+ # -------------------------------------------------------------------------------
89
+ # Define Tasks for Academic Research and Writing
90
+ # -------------------------------------------------------------------------------
91
+ literature_research_task = Task(
92
+ description="""Research academic literature on {topic} considering the keywords {keywords}.
93
+
94
+ Please provide:
95
+ - A summary of the current state of research,
96
+ - Key trends and gaps in the literature,
97
+ - Notable studies and their findings,
98
+ - Relevant theoretical frameworks and methodologies.
99
+ Format the response with bullet points and concise summaries.""",
100
+ agent=literature_research_agent,
101
+ expected_output="""A comprehensive literature review summary covering:
102
+ 1. Summary of current research trends
103
+ 2. Identification of gaps and controversies
104
+ 3. Key studies with brief descriptions
105
+ 4. Theoretical frameworks and methodologies used"""
106
+ )
107
+
108
+ outline_task = Task(
109
+ description="""Based on the research topic {topic} and literature review findings, generate a detailed outline for a research paper.
110
+
111
+ Include sections such as:
112
+ - Abstract
113
+ - Introduction (including research questions and objectives)
114
+ - Literature Review
115
+ - Methodology
116
+ - Results/Findings
117
+ - Discussion
118
+ - Conclusion
119
+ - References
120
+ Format the outline in a structured manner with bullet points and subheadings.""",
121
+ agent=outline_agent,
122
+ expected_output="A structured outline for a research paper including all major sections and key points to cover in each section."
123
+ )
124
+
125
+ draft_writing_task = Task(
126
+ description="""Using the research topic {topic}, the literature review, and the generated outline, compose a first draft of the research paper.
127
+
128
+ The draft should include:
129
+ - A coherent narrative flow,
130
+ - Detailed sections as per the outline,
131
+ - Integration of key findings from the literature review.
132
+ Ensure the tone is academic and the content is well-organized.""",
133
+ agent=draft_writing_agent,
134
+ expected_output="A complete first draft of the research paper covering all sections with sufficient academic detail."
135
+ )
136
+
137
+ citation_task = Task(
138
+ description="""Based on the literature review for {topic}, generate a list of key references and citations in APA format.
139
+
140
+ Include:
141
+ - Author names, publication year, title, and source,
142
+ - At least 10 key references relevant to the research topic.
143
+ Format the output as a numbered list of citations.""",
144
+ agent=citation_agent,
145
+ expected_output="A list of 10+ relevant citations in APA format."
146
+ )
147
+
148
+ editing_task = Task(
149
+ description="""Review and edit the draft for clarity, coherence, and academic tone.
150
+
151
+ Focus on:
152
+ - Improving sentence structure,
153
+ - Ensuring logical flow between sections,
154
+ - Correcting grammar and stylistic issues,
155
+ - Enhancing academic tone.
156
+ Provide the polished version of the paper.""",
157
+ agent=editing_agent,
158
+ expected_output="A refined and polished version of the research paper draft."
159
+ )
160
+
161
+ chatbot_task = Task(
162
+ description="Provide a conversational and detailed response to academic research-related queries.",
163
+ agent=chatbot_agent,
164
+ expected_output="A friendly, informative response addressing the query."
165
+ )
166
+
167
+ def run_task(task: Task, input_text: str) -> str:
168
+ """
169
+ Executes the given task using the associated agent's LLM and returns the response content.
170
+ """
171
+ try:
172
+ if not isinstance(task, Task):
173
+ raise ValueError(f"Expected 'task' to be an instance of Task, got {type(task)}")
174
+ if not hasattr(task, 'agent') or not isinstance(task.agent, Agent):
175
+ raise ValueError("Task must have a valid 'agent' attribute of type Agent.")
176
+ system_input = (
177
+ f"Agent Details:\n"
178
+ f"Role: {task.agent.role}\n"
179
+ f"Goal: {task.agent.goal}\n"
180
+ f"Backstory: {task.agent.backstory}\n"
181
+ f"Personality: {task.agent.personality}\n"
182
+ )
183
+ task_input = (
184
+ f"Task Details:\n"
185
+ f"Task Description: {task.description}\n"
186
+ f"Expected Output: {task.expected_output}\n"
187
+ f"Input for Task:\n{input_text}\n"
188
+ )
189
+ messages = [
190
+ SystemMessage(content=system_input),
191
+ HumanMessage(content=task_input)
192
+ ]
193
+ response = task.agent.llm.invoke(messages)
194
+ if not response or not response.content:
195
+ raise ValueError("Empty response from LLM.")
196
+ return response.content
197
+ except Exception as e:
198
+ logging.error(f"Error in task '{task.agent.role}': {e}")
199
+ return f"Error in {task.agent.role}: {e}"
travel.py DELETED
@@ -1,453 +0,0 @@
1
- import os
2
- import json
3
- import logging
4
- from datetime import datetime, timedelta
5
- from langchain_google_genai import ChatGoogleGenerativeAI
6
- from langchain.schema import SystemMessage, HumanMessage
7
-
8
- # Setup logging configuration
9
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
10
-
11
- # -------------------------------------------------------------------------------
12
- # Agent and Task Classes with Type Hints and Docstrings
13
- # -------------------------------------------------------------------------------
14
- class Agent:
15
- def __init__(self, role: str, goal: str, backstory: str, personality: str = "", llm=None) -> None:
16
- """
17
- Initialize an Agent with role, goal, backstory, personality, and assigned LLM.
18
- """
19
- self.role = role
20
- self.goal = goal
21
- self.backstory = backstory
22
- self.personality = personality
23
- self.tools = [] # Initialize with empty list for future tool integrations
24
- self.llm = llm
25
-
26
- class Task:
27
- def __init__(self, description: str, agent: Agent, expected_output: str, context=None) -> None:
28
- """
29
- Initialize a Task with its description, the responsible agent, expected output, and optional context.
30
- """
31
- self.description = description
32
- self.agent = agent
33
- self.expected_output = expected_output
34
- self.context = context or []
35
-
36
- # -------------------------------------------------------------------------------
37
- # Initialize LLM
38
- # -------------------------------------------------------------------------------
39
- google_api_key = os.getenv("GEMINI_API_KEY") # 실제 Google API 키 사용
40
- if not google_api_key:
41
- logging.error("GEMINI_API_KEY is not set in the environment variables.")
42
- llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", google_api_key=google_api_key)
43
-
44
- # -------------------------------------------------------------------------------
45
- # Define Travel Agents
46
- # -------------------------------------------------------------------------------
47
- destination_research_agent = Agent(
48
- role="Destination Research Agent",
49
- goal=(
50
- "Research and provide comprehensive information about the destination including popular attractions, "
51
- "local culture, weather patterns, best times to visit, and local transportation options."
52
- ),
53
- backstory=(
54
- "An experienced travel researcher with extensive knowledge of global destinations. "
55
- "I specialize in uncovering both popular attractions and hidden gems that match travelers' interests."
56
- ),
57
- personality="Curious, detail-oriented, and knowledgeable about global cultures and travel trends.",
58
- llm=llm,
59
- )
60
-
61
- accommodation_agent = Agent(
62
- role="Accommodation Agent",
63
- goal="Find and recommend suitable accommodations based on the traveler's preferences, budget, and location requirements.",
64
- backstory="A hospitality expert who understands different types of accommodations and can match travelers with their ideal places to stay.",
65
- personality="Attentive, resourceful, and focused on comfort and value.",
66
- llm=llm,
67
- )
68
-
69
- transportation_agent = Agent(
70
- role="Transportation Agent",
71
- goal="Plan efficient transportation between the origin, destination, and all points of interest in the itinerary.",
72
- backstory="A logistics specialist with knowledge of global transportation systems, from flights to local transit options.",
73
- personality="Efficient, practical, and detail-oriented.",
74
- llm=llm,
75
- )
76
-
77
- activities_agent = Agent(
78
- role="Activities & Attractions Agent",
79
- goal="Curate personalized activities and attractions that align with the traveler's interests, preferences, and time constraints.",
80
- backstory="An enthusiastic explorer who has experienced diverse activities around the world and knows how to match experiences to individual preferences.",
81
- personality="Enthusiastic, creative, and personable.",
82
- llm=llm,
83
- )
84
-
85
- dining_agent = Agent(
86
- role="Dining & Culinary Agent",
87
- goal="Recommend dining experiences that showcase local cuisine while accommodating dietary preferences and budget considerations.",
88
- backstory="A culinary expert with knowledge of global food scenes and an appreciation for authentic local dining experiences.",
89
- personality="Passionate about food, culturally aware, and attentive to preferences.",
90
- llm=llm,
91
- )
92
-
93
- itinerary_agent = Agent(
94
- role="Itinerary Integration Agent",
95
- goal="Compile all recommendations into a cohesive, day-by-day itinerary that optimizes time, minimizes travel fatigue, and maximizes enjoyment.",
96
- backstory="A master travel planner who understands how to balance activities, rest, and logistics to create the perfect travel experience.",
97
- personality="Organized, balanced, and practical.",
98
- llm=llm,
99
- )
100
-
101
- # -------------------------------------------------------------------------------
102
- # Define Chatbot Agent and Task for Interactive Conversation
103
- # -------------------------------------------------------------------------------
104
- chatbot_agent = Agent(
105
- role="Chatbot Agent",
106
- goal="Engage in interactive conversation to answer travel-related queries.",
107
- backstory="A conversational AI assistant who provides instant, accurate travel information and recommendations.",
108
- personality="Friendly, conversational, and knowledgeable about travel.",
109
- llm=llm,
110
- )
111
-
112
- chatbot_task = Task(
113
- description="Provide a conversational and detailed response to travel-related queries.",
114
- agent=chatbot_agent,
115
- expected_output="A friendly, helpful response to the user's query."
116
- )
117
-
118
- # -------------------------------------------------------------------------------
119
- # Define Other Travel Tasks
120
- # -------------------------------------------------------------------------------
121
- destination_research_task = Task(
122
- description="""Research {destination} thoroughly, considering the traveler's interests in {preferences}.
123
-
124
- Efficient research parameters:
125
- - Prioritize research in these critical categories:
126
- * Top attractions that match specific {preferences} (not generic lists)
127
- * Local transportation systems with cost-efficiency analysis
128
- * Neighborhood breakdown with accommodation recommendations by budget tier
129
- * Seasonal considerations for the specific travel dates
130
- * Safety assessment with specific areas to embrace or avoid
131
- * Cultural norms that impact visitor experience (dress codes, tipping, etiquette)
132
-
133
- - Apply efficiency filters:
134
- * Focus exclusively on verified information from official tourism boards, recent travel guides, and reliable local sources
135
- * Analyze recent visitor reviews (< 6 months old) to identify changing conditions
136
- * Evaluate price-to-experience value for attractions instead of just popularity
137
- * Identify logistical clusters where multiple interests can be satisfied efficiently
138
- * Research off-peak times for popular attractions to minimize waiting
139
- * Evaluate digital tools (apps, passes, reservation systems) that streamline the visit
140
-
141
- - Create practical knowledge matrices:
142
- * Transportation method comparison (cost vs. time vs. convenience)
143
- * Weather impact on specific activities
144
- * Budget allocation recommendations based on preference priorities
145
- * Time-saving opportunity identification""",
146
- agent=destination_research_agent,
147
- expected_output="""Targeted destination brief containing:
148
- 1. Executive summary highlighting the 5 most relevant aspects based on {preferences}
149
- 2. Neighborhood analysis with accommodation recommendations mapped to specific interests
150
- 3. Transportation efficiency guide with cost/convenience matrix
151
- 4. Cultural briefing focusing only on need-to-know information that impacts daily activities
152
- 5. Seasonal advantages and challenges specific to travel dates
153
- 6. Digital resource toolkit (essential apps, websites, reservation systems)
154
- 7. Budget optimization strategies with price ranges for key experiences
155
- 8. Safety and health quick-reference including emergency contacts
156
- 9. Logistics efficiency map showing optimal activity clustering
157
- 10. Local insider advantage recommendations that save time or money
158
-
159
- Format should prioritize scannable information with bullet points, comparison tables, and decision matrices rather than lengthy prose."""
160
- )
161
-
162
- accommodation_task = Task(
163
- description="Find suitable accommodations in {destination} based on a {budget} budget and preferences for {preferences}.",
164
- agent=accommodation_agent,
165
- expected_output="List of recommended accommodations with details on location, amenities, price range, and availability."
166
- )
167
-
168
- transportation_task = Task(
169
- description="Plan transportation from {origin} to {destination} and local transportation options during the stay.",
170
- agent=transportation_agent,
171
- expected_output="Transportation plan including flights/routes to the destination and recommendations for getting around locally."
172
- )
173
-
174
- activities_task = Task(
175
- description="""Suggest activities and attractions in {destination} that align with interests in {preferences}.
176
-
177
- Detailed requirements:
178
- - Categorize activities into: Cultural Experiences, Outdoor Adventures, Culinary Experiences,
179
- Entertainment & Nightlife, Family-Friendly Activities, and Local Hidden Gems
180
- - For each activity, include:
181
- * Detailed description with historical/cultural context where relevant
182
- * Precise location with neighborhood information
183
- * Operating hours with seasonal variations noted
184
- * Pricing information with different ticket options/packages
185
- * Accessibility considerations for travelers with mobility limitations
186
- * Recommended duration for the activity (minimum and ideal time)
187
- * Best time of day/week/year to visit
188
- * Crowd levels by season
189
- * Photography opportunities and restrictions
190
- * Required reservations or booking windows
191
- - Include a mix of iconic must-see attractions and off-the-beaten-path experiences
192
- - Consider weather patterns in {destination} during travel period
193
- - Analyze the {preferences} to match specific personality types and interest levels
194
- - Include at least 2-3 rainy day alternatives for outdoor activities
195
- - Provide local transportation options to reach each attraction
196
- - Note authentic local experiences that provide cultural immersion
197
- - Flag any activities requiring special equipment, permits, or physical fitness levels""",
198
- agent=activities_agent,
199
- expected_output="""Comprehensive curated list of activities and attractions with:
200
- 1. Clear categorization by type (cultural, outdoor, culinary, entertainment, family-friendly, hidden gems)
201
- 2. Detailed descriptions that include historical and cultural context
202
- 3. Complete practical information (hours, pricing, location, accessibility)
203
- 4. Time optimization recommendations (best time to visit, how to avoid crowds)
204
- 5. Personalized matches explaining why each activity aligns with specific {preferences}
205
- 6. Local transportation details to reach each attraction
206
- 7. Alternative options for inclement weather or unexpected closures
207
- 8. Insider tips from locals that enhance the experience
208
- 9. Suggested combinations of nearby activities for efficient itinerary planning
209
- 10. Risk level assessment and safety considerations where applicable
210
- 11. Sustainability impact and responsible tourism notes
211
- 12. Photographic highlights and optimal viewing points
212
-
213
- Format should include a summary table for quick reference followed by detailed cards for each activity."""
214
- )
215
-
216
- dining_task = Task(
217
- description="Recommend dining experiences in {destination} that showcase local cuisine while considering {preferences}.",
218
- agent=dining_agent,
219
- expected_output="List of recommended restaurants and food experiences with cuisine types, price ranges, and special notes."
220
- )
221
-
222
- itinerary_task = Task(
223
- description="""Create a day-by-day itinerary for a {duration} trip to {destination} from {origin}, incorporating all recommendations.
224
-
225
- Detailed requirements:
226
- - Begin with arrival logistics including airport transfer options, check-in times, and first-day orientation activities
227
- - Structure each day with:
228
- * Morning, afternoon, and evening activity blocks with precise timing
229
- * Estimated travel times between locations using various transportation methods
230
- * Buffer time for rest, spontaneous exploration, and unexpected delays
231
- * Meal recommendations with reservation details and backup options
232
- * Sunset/sunrise opportunities for optimal photography or experiences
233
- - Apply intelligent sequencing to:
234
- * Group attractions by geographic proximity to minimize transit time
235
- * Schedule indoor activities strategically for predicted weather patterns
236
- * Balance high-energy activities with relaxation periods
237
- * Alternate between cultural immersion and entertainment experiences
238
- * Account for opening days/hours of attractions and potential closures
239
- - Include practical timing considerations:
240
- * Museum/attraction fatigue limitations
241
- * Jet lag recovery for first 1-2 days
242
- * Time zone adjustment strategies
243
- * Local rush hours and traffic patterns to avoid
244
- * Cultural norms for meal times and business hours
245
- - End with departure logistics including check-out procedures, airport transfer timing, and luggage considerations
246
- - Add specialized planning elements:
247
- * Local festivals or events coinciding with the travel dates
248
- * Free time blocks for personal exploration or shopping
249
- * Contingency recommendations for weather disruptions
250
- * Early booking requirements for popular attractions/restaurants
251
- * Local emergency contacts and nearby medical facilities""",
252
- agent=itinerary_agent,
253
- expected_output="""Comprehensive day-by-day itinerary featuring:
254
- 1. Detailed timeline for each day with hour-by-hour scheduling and transit times
255
- 2. Color-coded activity blocks that visually distinguish between types of activities
256
- 3. Intelligent geographic clustering to minimize transportation time
257
- 4. Strategic meal placements with both reservation-required and casual options
258
- 5. Built-in flexibility with free time blocks and alternative suggestions
259
- 6. Weather-adaptive scheduling with indoor/outdoor activity balance
260
- 7. Energy level considerations throughout the trip arc
261
- 8. Cultural timing adaptations (accommodating local siesta times, religious observances, etc.)
262
- 9. Practical logistical details (bag storage options, dress code reminders, etc.)
263
- 10. Local transportation guidance including transit cards, apps, and pre-booking requirements
264
- 11. Visual map representation showing daily movement patterns
265
- 12. Key phrases in local language for each day's activities
266
-
267
- Format should include both a condensed overview calendar and detailed daily breakdowns with time, activity, location, notes, and contingency plans."""
268
- )
269
-
270
- # -------------------------------------------------------------------------------
271
- # Helper Function to Run a Task with Full Agent & Task Information
272
- # -------------------------------------------------------------------------------
273
- def run_task(task: Task, input_text: str) -> str:
274
- """
275
- Executes the given task using the associated agent's LLM and returns the response content.
276
- """
277
- try:
278
- if not isinstance(task, Task):
279
- raise ValueError(f"Expected 'task' to be an instance of Task, got {type(task)}")
280
- if not hasattr(task, 'agent') or not isinstance(task.agent, Agent):
281
- raise ValueError("Task must have a valid 'agent' attribute of type Agent.")
282
-
283
- system_input = (
284
- f"Agent Details:\n"
285
- f"Role: {task.agent.role}\n"
286
- f"Goal: {task.agent.goal}\n"
287
- f"Backstory: {task.agent.backstory}\n"
288
- f"Personality: {task.agent.personality}\n"
289
- )
290
- task_input = (
291
- f"Task Details:\n"
292
- f"Task Description: {task.description}\n"
293
- f"Expected Output: {task.expected_output}\n"
294
- f"Input for Task:\n{input_text}\n"
295
- )
296
- messages = [
297
- SystemMessage(content=system_input),
298
- HumanMessage(content=task_input)
299
- ]
300
- response = task.agent.llm.invoke(messages)
301
- if not response or not response.content:
302
- raise ValueError("Empty response from LLM.")
303
- return response.content
304
- except Exception as e:
305
- logging.error(f"Error in task '{task.agent.role}': {e}")
306
- return f"Error in {task.agent.role}: {e}"
307
-
308
- # -------------------------------------------------------------------------------
309
- # User Input Functions
310
- # -------------------------------------------------------------------------------
311
- def get_user_input() -> dict:
312
- """
313
- Collects user input for travel itinerary generation.
314
- """
315
- print("\n=== Travel Itinerary Generator ===\n")
316
- origin = input("Enter your origin city/country: ")
317
- destination = input("Enter your destination city/country: ")
318
- duration = input("Enter trip duration (number of days): ")
319
- budget = input("Enter your budget level (budget, moderate, luxury): ")
320
-
321
- print("\nEnter your travel preferences and interests (comma-separated):")
322
- print("Examples: museums, hiking, food, shopping, beaches, history, nightlife, family-friendly, etc.")
323
- preferences = input("> ")
324
-
325
- special_requirements = input("\nAny special requirements or notes (dietary restrictions, accessibility needs, etc.)? ")
326
-
327
- return {
328
- "origin": origin,
329
- "destination": destination,
330
- "duration": duration,
331
- "budget": budget,
332
- "preferences": preferences,
333
- "special_requirements": special_requirements
334
- }
335
-
336
- # -------------------------------------------------------------------------------
337
- # Main Function to Generate Travel Itinerary
338
- # -------------------------------------------------------------------------------
339
- def generate_travel_itinerary(user_input: dict) -> str:
340
- """
341
- Generates a personalized travel itinerary by sequentially running defined tasks.
342
- """
343
- print("\nGenerating your personalized travel itinerary...\n")
344
-
345
- # Create input context using f-string formatting
346
- input_context = (
347
- f"Travel Request Details:\n"
348
- f"Origin: {user_input['origin']}\n"
349
- f"Destination: {user_input['destination']}\n"
350
- f"Duration: {user_input['duration']} days\n"
351
- f"Budget Level: {user_input['budget']}\n"
352
- f"Preferences/Interests: {user_input['preferences']}\n"
353
- f"Special Requirements: {user_input['special_requirements']}\n"
354
- )
355
-
356
- # Step 1: Destination Research
357
- print("Researching your destination...")
358
- destination_info = run_task(destination_research_task, input_context)
359
- print("✓ Destination research completed")
360
-
361
- # Step 2: Accommodation Recommendations
362
- print("Finding ideal accommodations...")
363
- accommodation_info = run_task(accommodation_task, input_context)
364
- print("✓ Accommodation recommendations completed")
365
-
366
- # Step 3: Transportation Planning
367
- print("Planning transportation...")
368
- transportation_info = run_task(transportation_task, input_context)
369
- print("✓ Transportation planning completed")
370
-
371
- # Step 4: Activities & Attractions
372
- print("Curating activities and attractions...")
373
- activities_info = run_task(activities_task, input_context)
374
- print("✓ Activities and attractions curated")
375
-
376
- # Step 5: Dining Recommendations
377
- print("Finding dining experiences...")
378
- dining_info = run_task(dining_task, input_context)
379
- print("✓ Dining recommendations completed")
380
-
381
- # Step 6: Create Day-by-Day Itinerary
382
- print("Creating your day-by-day itinerary...")
383
- combined_info = (
384
- input_context + "\n"
385
- "Destination Information:\n" + destination_info + "\n"
386
- "Accommodation Options:\n" + accommodation_info + "\n"
387
- "Transportation Plan:\n" + transportation_info + "\n"
388
- "Recommended Activities:\n" + activities_info + "\n"
389
- "Dining Recommendations:\n" + dining_info + "\n"
390
- )
391
- itinerary = run_task(itinerary_task, combined_info)
392
- print("✓ Itinerary creation completed")
393
- print("✓ Itinerary generation completed")
394
-
395
- return itinerary
396
-
397
- # -------------------------------------------------------------------------------
398
- # Save Itinerary to File
399
- # -------------------------------------------------------------------------------
400
- def save_itinerary_to_file(itinerary: str, user_input: dict, output_dir: str = None) -> str:
401
- """
402
- Saves the generated itinerary to a text file and returns the filepath.
403
- """
404
- date_str = datetime.now().strftime("%Y-%m-%d")
405
- filename = f"{user_input['destination'].replace(' ', '_')}_{date_str}_itinerary.txt"
406
-
407
- if output_dir:
408
- if not os.path.exists(output_dir):
409
- try:
410
- os.makedirs(output_dir)
411
- logging.info(f"Created output directory: {output_dir}")
412
- except Exception as e:
413
- logging.error(f"Error creating directory {output_dir}: {e}")
414
- return ""
415
- filepath = os.path.join(output_dir, filename)
416
- else:
417
- filepath = filename
418
-
419
- try:
420
- with open(filepath, "w", encoding="utf-8") as f:
421
- f.write(itinerary)
422
- logging.info(f"Your itinerary has been saved as: {filepath}")
423
- return filepath
424
- except Exception as e:
425
- logging.error(f"Error saving itinerary: {e}")
426
- return ""
427
-
428
- # -------------------------------------------------------------------------------
429
- # Main Function
430
- # -------------------------------------------------------------------------------
431
- def main() -> None:
432
- """
433
- Main entry point for the travel itinerary generator application.
434
- """
435
- print("Welcome to BlockX Travel Itinerary Generator!")
436
- print("This AI-powered tool will create a personalized travel itinerary based on your preferences.")
437
-
438
- user_input = get_user_input()
439
-
440
- print("\nWhere would you like to save the itinerary?")
441
- print("Press Enter to save in the current directory, or specify a path:")
442
- output_dir = input("> ").strip() or None
443
-
444
- itinerary = generate_travel_itinerary(user_input)
445
-
446
- filepath = save_itinerary_to_file(itinerary, user_input, output_dir)
447
-
448
- if filepath:
449
- print(f"\nYour personalized travel itinerary is ready! Open {filepath} to view it.")
450
- print("Thank you for using BlockX Travel Itinerary Generator!")
451
-
452
- if __name__ == "__main__":
453
- main()