-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
918 lines (702 loc) · 24.4 KB
/
Copy pathmain.py
File metadata and controls
918 lines (702 loc) · 24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
import asyncio
import json
import os
import certifi
from dotenv import load_dotenv
from typing import TypedDict, Annotated , Any
import operator
import uuid
import psycopg
from psycopg.rows import dict_row
from langgraph.graph import StateGraph, START, END
from langgraph.types import interrupt , Command
from langgraph.checkpoint.postgres import PostgresSaver
from langchain_core.messages import (
AnyMessage,
HumanMessage,
AIMessage,
SystemMessage,
)
from langchain_groq import ChatGroq
# from tools.tavily_tool import tavily_search
from tools.flight_tool import search_flights
from mcp_client import tavily_mcp_search , extract_destination , forecast_mcp_search , weather_mcp_search
load_dotenv()
os.environ["SSL_CERT_FILE"] = certifi.where()
os.environ["REQUESTS_CA_BUNDLE"] = certifi.where()
# LLM
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("GROQ_API_KEY not found")
llm = ChatGroq(
groq_api_key=GROQ_API_KEY,
model_name="llama-3.3-70b-versatile",
temperature=0
)
def get_database_url():
database_url = os.getenv("DATABASE_URL")
if not database_url:
raise ValueError(
"DATABASE_URL is missing. Please add your Render PostgreSQL External Database URL to .env"
)
# why require sslmode=require? Because Render's PostgreSQL External Database requires SSL connections. If you don't add this, you'll get an error like: "psycopg.errors.ConnectionException: SSL error: wrong version number"
# if "sslmode=" not in database_url:
# separator = "&" if "?" in database_url else "?"
# database_url = f"{database_url}{separator}sslmode=require"
return database_url
# class TravelState(TypedDict):
# messages: Annotated[list[AnyMessage], operator.add]
# user_query: str
# flight_results: str
# hotel_results: str
# itinerary: str
# llm_calls: int
# weather_results: str
class TravelState(TypedDict, total=False):
messages: Annotated[list[AnyMessage], operator.add]
user_query: str
# Supervisor + guardrail state
guardrail_allowed: bool
guardrail_reason: str
selected_agents: list[str]
trip_constraints: dict[str, Any]
supervisor_reasoning: str
# Original specialist results
flight_results: str
hotel_results: str
weather_results: str
itinerary: str
# New budget + HITL state
budget_results: str
approval_request: str
approved: bool
human_feedback: str
final_response: str
llm_calls: int
# NEED THE HELPER FUNCTION AND HELPER VARIABLE
# =========================
# Shared helpers
# =========================
KNOWN_AGENTS = {
"flight_agent",
"hotel_agent",
"weather_agent",
"budget_agent",
"itinerary_agent",
}
AGENT_ORDER = [
"flight_agent",
"hotel_agent",
"weather_agent",
"budget_agent",
"itinerary_agent",
]
# WHENEVER I NEED TO CALL ANY LLM I CAN CALL IT WITH THIS FUNCTION. IT WILL HANDLE THE SYSTEM PROMPT AND USER PROMPT AND RETURN THE RESPONSE CONTENT AS A STRING.
def _llm_text(system_prompt: str, user_prompt: str) -> str:
response = llm.invoke(
[
SystemMessage(content=system_prompt),
HumanMessage(content=user_prompt),
]
)
return str(response.content)
# WHAT IS THIS FUNCTION DOING? IT TAKES A STRING AND EXTRACTS THE FIRST COMPLETE JSON OBJECT FROM IT. IF THERE IS NO COMPLETE JSON OBJECT, IT RAISES A VALUE ERROR. OTHERWISE, IT RETURNS THE JSON OBJECT AS A DICTIONARY.
# CONVERT IT INTO JSON
def _json_from_llm(text: str) -> dict[str, Any]:
"""Extract the first complete JSON object returned by the model."""
start = text.find("{")
end = text.rfind("}")
if start == -1 or end == -1 or end < start:
raise ValueError("The model did not return a JSON object.")
return json.loads(text[start : end + 1])
def _empty_constraints() -> dict[str, Any]:
return {
"destination": "",
"origin": "",
"duration": "",
"budget": "",
"travel_style": "",
"special_preferences": [],
}
# =========================
# Supervisor Agent + Input Guardrail
# =========================
def supervisor_agent(state: TravelState):
query = state["user_query"]
llm_calls = state.get("llm_calls", 0)
guardrail_prompt = f"""
Determine whether the following request belongs to travel planning or travel
information. Valid requests can include destinations, flights, hotels, weather,
budgets, visas, transportation, sightseeing, food, packing, or itineraries.
Block clearly unrelated requests and requests asking for harmful or illegal
instructions. Do not block a valid travel request merely because some details
are missing.
Return strict JSON only:
{{
"allowed": true,
"reason": ""
}}
User request:
{query}
"""
# Fail open on parser/model errors so a temporary JSON-format issue does not
# break the original travel-planning behavior.
try:
guardrail_raw = _llm_text(
"You are the input guardrail for a travel-planning application. "
"Return strict JSON only.",
guardrail_prompt,
)
guardrail_result = _json_from_llm(guardrail_raw)
allowed = bool(guardrail_result.get("allowed", True))
guardrail_reason = str(guardrail_result.get("reason", "")).strip()
llm_calls += 1
except Exception as exc:
print(f"Guardrail fallback used: {exc}")
allowed = True
guardrail_reason = "Guardrail validation fallback allowed the request."
if not allowed:
reason = guardrail_reason or (
"TripMate AI can only help with travel-planning requests. "
"Please ask about a destination, flight, hotel, weather, budget, "
"or itinerary."
)
return {
"guardrail_allowed": False,
"guardrail_reason": reason,
"selected_agents": [],
"trip_constraints": _empty_constraints(),
"supervisor_reasoning": reason,
"final_response": reason,
"messages": [AIMessage(content=f"Guardrail blocked request: {reason}")],
"llm_calls": llm_calls,
}
supervisor_prompt = f"""
You are the supervisor of a multi-agent travel-planning system.
Choose only the specialist agents needed for the request.
Available agents:
- flight_agent: flights, airports, airlines, routes, airfare, or booking advice
- hotel_agent: hotels, accommodation, neighborhoods, or places to stay
- weather_agent: weather, climate, season, forecast, or packing advice
- budget_agent: cost, affordability, price limits, or budget feasibility
- itinerary_agent: creates the integrated travel plan and must always be included
Return strict JSON only using this schema:
{{
"selected_agents": ["flight_agent", "hotel_agent", "weather_agent", "budget_agent", "itinerary_agent"],
"trip_constraints": {{
"destination": "",
"origin": "",
"duration": "",
"budget": "",
"travel_style": "",
"special_preferences": []
}},
"reasoning": ""
}}
User request:
{query}
"""
try:
supervisor_raw = _llm_text(
"You route work to travel specialist agents. Return strict JSON only.",
supervisor_prompt,
)
parsed = _json_from_llm(supervisor_raw)
requested_agents = parsed.get("selected_agents", [])
selected_agents = [
name for name in AGENT_ORDER
if name in requested_agents and name in KNOWN_AGENTS
]
# The itinerary agent integrates whichever specialist results were selected.
if "itinerary_agent" not in selected_agents:
selected_agents.append("itinerary_agent")
constraints = _empty_constraints()
parsed_constraints = parsed.get("trip_constraints", {})
if isinstance(parsed_constraints, dict):
constraints.update(parsed_constraints)
reasoning = str(parsed.get("reasoning", "")).strip()
llm_calls += 1
except Exception as exc:
print(f"Supervisor fallback used: {exc}")
# Original workflow behavior is preserved as the fallback.
selected_agents = AGENT_ORDER.copy()
constraints = _empty_constraints()
reasoning = (
"Supervisor parsing failed, so the original full travel workflow "
"was selected as a safe fallback."
)
return {
"guardrail_allowed": True,
"guardrail_reason": guardrail_reason,
"selected_agents": selected_agents,
"trip_constraints": constraints,
"supervisor_reasoning": reasoning,
"messages": [AIMessage(content="Supervisor created the agent plan.")],
"llm_calls": llm_calls,
}
# =========================
# Guardrail blocked response
# =========================
def guardrail_blocked_agent(state: TravelState):
reason = state.get("final_response") or state.get("guardrail_reason") or (
"This request was blocked by the travel input guardrail."
)
return {
"final_response": reason,
"messages": [AIMessage(content=reason)],
}
# =========================
# Flight Agent
# =========================
def flight_agent(state: TravelState):
query = state["user_query"]
flight_data = search_flights(query)
return {
"flight_results": flight_data,
"messages": [
AIMessage(content="Flight results fetched.")
],
"llm_calls": state.get("llm_calls", 0) + 1
}
# =========================
# Hotel Agent
# =========================
def hotel_agent(state: TravelState):
query = f"Best hotels for {state['user_query']}"
# hotel_results = tavily_search(query)
hotel_results = asyncio.run(tavily_mcp_search(query))
return {
"hotel_results": hotel_results,
"messages": [
AIMessage(content="Hotel information fetched.")
],
"llm_calls": state.get("llm_calls", 0) + 1
}
# =========================
# Weather Agent
# =========================
def weather_agent(state: TravelState):
city = extract_destination(state["user_query"])
weather_data = asyncio.run(
weather_mcp_search(city)
)
forecast_data = asyncio.run(
forecast_mcp_search(city)
)
return {
"weather_results": f"""
Current Weather:
{weather_data}
Forecast:
{forecast_data}
""",
"messages": [
AIMessage(
content="Weather information fetched"
)
]
}
# =========================
# Budget Agent - new specialist
# =========================
def budget_agent(state: TravelState):
prompt = f"""
Analyze whether this trip is realistic for the user's budget.
User Query:
{state['user_query']}
Trip Constraints:
{state.get('trip_constraints', {})}
Flight Results:
{state.get('flight_results', '')}
Hotel Results:
{state.get('hotel_results', '')}
Weather Results:
{state.get('weather_results', '')}
Return:
1. Estimated cost categories
2. Budget risk areas
3. Money-saving suggestions
4. Overall feasibility
If exact live prices are unavailable, clearly label estimates as approximate.
"""
response = llm.invoke(
[
SystemMessage(content="You are a practical travel budget analyst."),
HumanMessage(content=prompt),
]
)
return {
"budget_results": response.content,
"messages": [AIMessage(content="Budget assessment generated.")],
"llm_calls": state.get("llm_calls", 0) + 1,
}
# =========================
# Itinerary Agent
# =========================
def itinerary_agent(state: TravelState):
prompt = f"""
Create a complete travel itinerary.
User Query:
{state['user_query']}
Flight Results:
{state['flight_results']}
Hotel Results:
{state['hotel_results']}
Weather Results:
{state['weather_results']}
Make the itinerary practical, budget-aware, and easy to follow.
"""
response = llm.invoke([
SystemMessage(content="You are an expert travel planner."),
HumanMessage(content=prompt)
])
approval_request = (
"Please review the generated draft itinerary. Approve it to create the "
"final polished plan, or provide feedback for revision."
)
return {
"itinerary": response.content,
"approval_request": approval_request,
"messages": [AIMessage(content="Draft itinerary created for human review.")],
"llm_calls": state.get("llm_calls", 0) + 1,
}
# =========================
# Human-in-the-Loop approval
# =========================
def human_approval_agent(state: TravelState):
# Do not wrap interrupt() in try/except. LangGraph uses it to pause execution.
review = interrupt(
{
"question": "Do you approve this itinerary?",
"draft_itinerary": state.get("itinerary", ""),
"approval_request": state.get("approval_request", ""),
"selected_agents": state.get("selected_agents", []),
"supervisor_reasoning": state.get("supervisor_reasoning", ""),
"expected_response": {
"approved": True,
"feedback": "Optional revision feedback",
},
}
)
approved = bool(review.get("approved", False))
human_feedback = str(review.get("feedback", "")).strip()
return {
"approved": approved,
"human_feedback": human_feedback,
"messages": [AIMessage(content="Human approval step completed.")],
}
# =========================
# Final Response Agent
# =========================
# def final_agent(state: TravelState):
# final_prompt = f"""
# Generate the final travel response for the user.
# User Request:
# {state['user_query']}
# Flights:
# {state['flight_results']}
# Hotels:
# {state['hotel_results']}
# Weather:
# {state['weather_results']}
# Itinerary:
# {state['itinerary']}
# Format the final answer beautifully using these sections:
# 1. Trip Summary
# 2. Flight Information
# 3. Hotel Suggestions
# 4. Weather Information
# 5. Day-by-Day Itinerary
# 6. Estimated Budget
# 7. Final Recommendations
# Important:
# - Be clear and practical.
# - Mention that live flight API may not provide ticket prices if pricing is unavailable.
# - Include weather-based travel advice.
# - Keep the response useful for real travel planning.
# """
# response = llm.invoke([
# SystemMessage(content="You are a professional AI travel booking assistant."),
# HumanMessage(content=final_prompt)
# ])
# return {
# "messages": [response],
# "llm_calls": state.get("llm_calls", 0) + 1
# }
# =========================
# Final Response Agent - original format kept, HITL feedback added
# =========================
def final_agent(state: TravelState):
if state.get("approved", False):
review_instruction = (
"The user approved the draft. Preserve its decisions while polishing it."
)
else:
review_instruction = f"""
The user requested a revision. Apply this feedback carefully:
{state.get('human_feedback', '') or 'Improve the draft before finalizing it.'}
"""
final_prompt = f"""
Generate the final travel response for the user.
Human Review:
{review_instruction}
User Request:
{state['user_query']}
Supervisor Constraints:
{state.get('trip_constraints', {})}
Flights:
{state.get('flight_results', '')}
Hotels:
{state.get('hotel_results', '')}
Weather:
{state.get('weather_results', '')}
Budget Analysis:
{state.get('budget_results', '')}
Draft Itinerary:
{state.get('itinerary', '')}
Format the final answer beautifully using these sections:
1. Trip Summary
2. Flight Information
3. Hotel Suggestions
4. Weather Information
5. Day-by-Day Itinerary
6. Estimated Budget
7. Final Recommendations
Important:
- Be clear and practical.
- Mention that live flight APIs may not provide ticket prices when pricing is unavailable.
- Include weather-based travel advice.
- Keep the response useful for real travel planning.
- Incorporate the human feedback when revision was requested.
"""
response = llm.invoke(
[
SystemMessage(
content="You are a professional AI travel booking assistant."
),
HumanMessage(content=final_prompt),
]
)
return {
"final_response": response.content,
"messages": [response],
"llm_calls": state.get("llm_calls", 0) + 1,
}
# =========================
# Dynamic Supervisor Routing---- EACH OF THE AGENT IS TREATED AS A NODE IN THE GRAPH. THE ROUTE_MAP IS USED TO MAP THE AGENT NAME TO THE FUNCTION THAT HANDLES THAT AGENT'S LOGIC. THIS ALLOWS FOR FLEXIBLE ROUTING BASED ON THE STATE OF THE TRAVEL REQUEST AND WHICH AGENTS HAVE BEEN SELECTED BY THE SUPERVISOR.
# =========================
ROUTE_MAP = {
"guardrail_blocked": "guardrail_blocked",
"flight_agent": "flight_agent",
"hotel_agent": "hotel_agent",
"weather_agent": "weather_agent",
"budget_agent": "budget_agent",
"itinerary_agent": "itinerary_agent",
}
def _selected_agents(state: TravelState) -> list[str]:
selected = state.get("selected_agents", [])
return [agent for agent in AGENT_ORDER if agent in selected]
def route_from_supervisor(state: TravelState) -> str:
if not state.get("guardrail_allowed", True):
return "guardrail_blocked"
selected = _selected_agents(state)
return selected[0] if selected else "itinerary_agent"
def route_after_agent(current_agent: str):
def route(state: TravelState) -> str:
selected = _selected_agents(state)
current_index = AGENT_ORDER.index(current_agent)
for next_agent in AGENT_ORDER[current_index + 1 :]:
if next_agent in selected:
return next_agent
return "itinerary_agent"
return route
# =========================
# Build Graph PREVIOUS
# =========================
# graph = StateGraph(TravelState)
# graph.add_node("flight_agent", flight_agent)
# graph.add_node("hotel_agent", hotel_agent)
# graph.add_node("weather_agent", weather_agent)
# graph.add_node("itinerary_agent", itinerary_agent)
# graph.add_node("final_agent", final_agent)
# graph.add_edge(START, "flight_agent")
# graph.add_edge("flight_agent", "hotel_agent")
# graph.add_edge("hotel_agent", "weather_agent")
# graph.add_edge("weather_agent", "itinerary_agent")
# graph.add_edge("itinerary_agent", "final_agent")
# graph.add_edge("final_agent", END)
# =========================
# Build Graph -- UPDATED GRAPH
# =========================
graph = StateGraph(TravelState)
graph.add_node("supervisor", supervisor_agent)
graph.add_node("guardrail_blocked", guardrail_blocked_agent)
graph.add_node("flight_agent", flight_agent)
graph.add_node("hotel_agent", hotel_agent)
graph.add_node("weather_agent", weather_agent)
graph.add_node("budget_agent", budget_agent)
graph.add_node("itinerary_agent", itinerary_agent)
graph.add_node("human_approval", human_approval_agent)
graph.add_node("final_agent", final_agent)
graph.add_edge(START, "supervisor")
graph.add_conditional_edges("supervisor", route_from_supervisor, ROUTE_MAP)
graph.add_conditional_edges(
"flight_agent", route_after_agent("flight_agent"), ROUTE_MAP
)
graph.add_conditional_edges(
"hotel_agent", route_after_agent("hotel_agent"), ROUTE_MAP
)
graph.add_conditional_edges(
"weather_agent", route_after_agent("weather_agent"), ROUTE_MAP
)
graph.add_conditional_edges(
"budget_agent", route_after_agent("budget_agent"), ROUTE_MAP
)
graph.add_edge("itinerary_agent", "human_approval")
graph.add_edge("human_approval", "final_agent")
graph.add_edge("final_agent", END)
graph.add_edge("guardrail_blocked", END)
# =========================
# PostgreSQL Checkpointer
# =========================
DATABASE_URL = get_database_url()
_conn = psycopg.connect(
DATABASE_URL,
autocommit=True,
row_factory=dict_row
)
checkpointer = PostgresSaver(_conn)
checkpointer.setup()
travel_graph = graph.compile(checkpointer=checkpointer)
"""
# =========================
# Function for FastAPI -- PREVIOUS
# =========================
def run_travel_agent(user_input: str, thread_id: str | None = None):
if not thread_id:
thread_id = f"user_{uuid.uuid4().hex}"
config = {
"configurable": {
"thread_id": thread_id
}
}
result = travel_graph.invoke(
{
"messages": [
HumanMessage(content=user_input)
],
"user_query": user_input,
"flight_results": "",
"hotel_results": "",
"itinerary": "",
"llm_calls": 0
},
config=config
)
final_answer = result["messages"][-1].content
return {
"thread_id": thread_id,
"answer": final_answer,
"flight_results": result.get("flight_results", ""),
"hotel_results": result.get("hotel_results", ""),
"weather_results": result.get("weather_results", ""),
"itinerary": result.get("itinerary", ""),
"llm_calls": result.get("llm_calls", 0),
}
"""
# =========================
# FastAPI-facing helpers
# =========================
def _interrupt_payload(result: dict[str, Any]) -> dict[str, Any] | None:
interrupts = result.get("__interrupt__", [])
if not interrupts:
return None
first_interrupt = interrupts[0]
payload = getattr(first_interrupt, "value", first_interrupt)
return payload if isinstance(payload, dict) else {"value": payload}
def _serialize_result(
result: dict[str, Any],
thread_id: str,
) -> dict[str, Any]:
messages = result.get("messages", [])
last_message = messages[-1].content if messages else ""
answer = result.get("final_response") or last_message
interrupt_payload = _interrupt_payload(result)
if interrupt_payload:
answer = interrupt_payload.get("draft_itinerary") or result.get(
"itinerary", ""
)
return {
"thread_id": thread_id,
"answer": answer,
"requires_approval": interrupt_payload is not None,
"approval_request": (
interrupt_payload.get("approval_request", "")
if interrupt_payload
else result.get("approval_request", "")
),
"flight_results": result.get("flight_results", ""),
"hotel_results": result.get("hotel_results", ""),
"weather_results": result.get("weather_results", ""),
"budget_results": result.get("budget_results", ""),
"itinerary": (
interrupt_payload.get("draft_itinerary", "")
if interrupt_payload
else result.get("itinerary", "")
),
"selected_agents": result.get("selected_agents", []),
"trip_constraints": result.get("trip_constraints", {}),
"supervisor_reasoning": result.get("supervisor_reasoning", ""),
"guardrail_allowed": result.get("guardrail_allowed", True),
"guardrail_reason": result.get("guardrail_reason", ""),
"approved": result.get("approved"),
"human_feedback": result.get("human_feedback", ""),
"llm_calls": result.get("llm_calls", 0),
}
def run_travel_agent(user_input: str, thread_id: str | None = None):
"""Start a new travel-planning run and pause at human approval."""
if not thread_id:
thread_id = f"user_{uuid.uuid4().hex}"
config = {"configurable": {"thread_id": thread_id}}
result = travel_graph.invoke(
{
"messages": [HumanMessage(content=user_input)],
"user_query": user_input,
"guardrail_allowed": True,
"guardrail_reason": "",
"selected_agents": [],
"trip_constraints": _empty_constraints(),
"supervisor_reasoning": "",
"flight_results": "",
"hotel_results": "",
"weather_results": "",
"budget_results": "",
"itinerary": "",
"approval_request": "",
"approved": False,
"human_feedback": "",
"final_response": "",
"llm_calls": 0,
},
config=config,
)
return _serialize_result(result, thread_id)
def resume_travel_agent(
thread_id: str,
approved: bool,
feedback: str = "",
):
"""Resume the paused LangGraph thread after human review."""
if not thread_id:
raise ValueError("thread_id is required to resume a travel plan.")
config = {"configurable": {"thread_id": thread_id}}
result = travel_graph.invoke(
Command(
resume={
"approved": approved,
"feedback": feedback.strip(),
}
),
config=config,
)
return _serialize_result(result, thread_id)