-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.py
More file actions
211 lines (167 loc) · 5.26 KB
/
Copy pathbackend.py
File metadata and controls
211 lines (167 loc) · 5.26 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
import os
import certifi
from dotenv import load_dotenv
load_dotenv()
os.environ["SSL_CERT_FILE"] = certifi.where()
os.environ["REQUESTS_CA_BUNDLE"] = certifi.where()
from typing import TypedDict, Annotated
import operator
import uuid
import psycopg
from psycopg.rows import dict_row
from langgraph.graph import StateGraph, START, END
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
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"
)
if "sslmode=" not in database_url:
separator = "&" if "?" in database_url else "?"
database_url = f"{database_url}{separator}sslmode=require"
return database_url
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
if not GROQ_API_KEY:
raise ValueError("GROQ_API_KEY is missing. Please add it to your .env file.")
llm = ChatGroq(
model="llama-3.3-70b-versatile",
api_key=GROQ_API_KEY
)
class TravelState(TypedDict):
messages: Annotated[list[AnyMessage], operator.add]
user_query: str
flight_results: str
hotel_results: str
itinerary: str
llm_calls: int
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
}
def hotel_agent(state: TravelState):
query = f"Best hotels for {state['user_query']}"
hotel_results = tavily_search(query)
return {
"hotel_results": hotel_results,
"messages": [
AIMessage(content="Hotel information fetched.")
],
"llm_calls": state.get("llm_calls", 0) + 1
}
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']}
Make the itinerary practical, budget-aware, and easy to follow.
"""
response = llm.invoke([
SystemMessage(content="You are an expert travel planner."),
HumanMessage(content=prompt)
])
return {
"itinerary": response.content,
"messages": [response],
"llm_calls": state.get("llm_calls", 0) + 1
}
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']}
Itinerary:
{state['itinerary']}
Format the final answer beautifully using these sections:
1. Trip Summary
2. Flight Information
3. Hotel Suggestions
4. Day-by-Day Itinerary
5. Estimated Budget
6. Final Recommendations
Important:
- Be clear and practical.
- Mention that live flight API may not provide ticket prices if pricing is unavailable.
- 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
}
graph = StateGraph(TravelState)
graph.add_node("flight_agent", flight_agent)
graph.add_node("hotel_agent", hotel_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", "itinerary_agent")
graph.add_edge("itinerary_agent", "final_agent")
graph.add_edge("final_agent", END)
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)
# FastAPI
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", ""),
"itinerary": result.get("itinerary", ""),
"llm_calls": result.get("llm_calls", 0),
}