Spaces:
Sleeping
Sleeping
File size: 14,906 Bytes
fb9c225 7d65266 fb9c225 9c97925 fb9c225 7d65266 fb9c225 7d65266 fb9c225 7d65266 fb9c225 7d65266 fb9c225 7d65266 fb9c225 7d65266 fb9c225 7d65266 fb9c225 7d65266 fb9c225 7d65266 fb9c225 7d65266 fb9c225 8019865 fb9c225 8019865 7d65266 fb9c225 7d65266 fb9c225 7d65266 8019865 fb9c225 8019865 fb9c225 7d65266 fb9c225 7827851 fb9c225 7d65266 fb9c225 7d65266 fb9c225 9582674 fb9c225 9582674 fb9c225 9582674 fb9c225 7d65266 fb9c225 7d65266 fb9c225 | 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 | from dotenv import load_dotenv
import sqlite3
import json
from datetime import datetime
from typing import TypedDict, Annotated, Sequence, Literal
from rapidfuzz import process
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
from langgraph.prebuilt import ToolNode
from langchain_core.messages import messages_to_dict
from langchain_core.tools import tool
from pydantic import BaseModel, Field
import operator
import Initialize_db as db
import time
load_dotenv()
# Database configuration
DB_PATH = "movie_booking_details.db"
# Initialize LLM
llm = ChatOpenAI(model="gpt-4o-mini",temperature=0)
# ============================================================================
# State Definition
# ============================================================================
class AgentState(TypedDict):
"""State for the movie booking agent."""
messages: Annotated[Sequence[BaseMessage], operator.add]
booking_response: dict
requires_tools: bool
tool_outputs: dict
current_step: int
# ============================================================================
# Database Functions
# ============================================================================
# def execute_query(sql: str) -> list:
# """Execute SQL query and return results."""
# try:
# print(sql)
# conn = sqlite3.connect(DB_PATH)
# cur = conn.cursor()
# cur.execute(sql)
# results = [i for i in cur.fetchall()]
# if len(results) == 1 and len(results[0]) == 1:
# results = results[0][0]
# conn.close()
# return results
# except Exception as e:
# print(f"[SQL Error] {e}")
# return []
def fuzzy_search(user_input: str, data_list: dict) -> str:
"""Perform fuzzy matching on input."""
match, score, _ = process.extractOne(user_input.lower(), data_list.keys())
if score > 80:
return data_list[match]
else:
print(f"{user_input} matched {match} with score {score}")
return None
# ============================================================================
# Tool Definitions
# ============================================================================
# @tool
# def movie_entity_correction(movie_name: str) -> str:
# """Corrects fuzzy or misspelled movie names.
# Args:
# movie_name: The movie name to correct
# Returns:
# Corrected movie name or None if not found
# """
# conn = sqlite3.connect(DB_PATH)
# cur = conn.cursor()
# cur.execute("SELECT DISTINCT name FROM movies")
# results = {i[0].lower(): i[0] for i in cur.fetchall()}
# conn.close()
# result = fuzzy_search(movie_name, results)
# return result if result else f"Movie '{movie_name}' not found"
@tool
def movie_entity_correction(movie_name: str) -> str:
"""Corrects fuzzy or misspelled movie names.
Args:
movie_name: The movie name to correct
Returns:
Corrected movie name or None if not found
"""
results = db.get_results_as_dframe("SELECT DISTINCT name FROM movies")
results = {i.lower(): i for i in results['name']}
print(results)
result = fuzzy_search(movie_name, results)
return result if result else f"Movie '{movie_name}' not found"
# @tool
# def theatre_entity_correction(theatre_name: str) -> str:
# """Corrects fuzzy or misspelled theatre names.
# Args:
# theatre_name: The theatre name to correct
# Returns:
# Corrected theatre name or None if not found
# """
# conn = sqlite3.connect(DB_PATH)
# cur = conn.cursor()
# cur.execute("SELECT DISTINCT name FROM theatres")
# results = {i[0].lower(): i[0] for i in cur.fetchall()}
# conn.close()
# result = fuzzy_search(theatre_name, results)
# return result if result else f"Theatre '{theatre_name}' not found"
@tool
def theatre_entity_correction(theatre_name: str) -> str:
"""Corrects fuzzy or misspelled theatre names.
Args:
theatre_name: The theatre name to correct
Returns:
Corrected theatre name or None if not found
"""
results = db.get_results_as_dframe("SELECT DISTINCT name FROM theatres")
results = {i.lower(): i for i in results['name']}
result = fuzzy_search(theatre_name, results)
return result if result else f"Theatre '{theatre_name}' not found"
@tool
def query_database(query: str) -> str:
"""Executes a SQL query and returns results.
Args:
query: SQL query to execute
Returns:
Query results as string
"""
result = db.get_results_as_dframe(query)
return str(result) if not result.empty else "No results found"
def verify_show(movie: str, theatre: str, showtime: str) -> str:
"""Verifies if a show exists at the specified time.
Args:
movie: Movie name
theatre: Theatre name
showtime: Showtime in format 'YYYY-MM-DD HH:MM:SS'
Returns:
Verification status
"""
sql = f"""SELECT showtime FROM showtimes
WHERE movie_id = (SELECT id FROM movies WHERE name = '{movie}')
AND theatre_id = (SELECT id FROM theatres WHERE name = '{theatre}')
AND showtime = '{showtime}'"""
results = db.get_results_as_dframe(sql)
return "verified_exist" if len(results) == 1 else "not_exists"
@tool
def book_ticket(movie: str, theatre: str, showtime: str) -> str:
"""Books a ticket for the specified show.
Args:
movie: Movie name
theatre: Theatre name
showtime: Showtime in format 'YYYY-MM-DD HH:MM:SS'
Returns:
Booking confirmation or error message
"""
verification = verify_show( movie, theatre, showtime)
if verification == "verified_exist":
price = db.get_results_as_dframe(f"""SELECT showtime,price FROM showtimes
WHERE movie_id = (SELECT id FROM movies WHERE name = '{movie}')
AND theatre_id = (SELECT id FROM theatres WHERE name = '{theatre}')
AND showtime = '{showtime}'""")['price'][0]
# Extract image URL from movie_data (handles both old and new format)
image_url = ""
if movie in db.movie_data:
movie_info = db.movie_data[movie]
if isinstance(movie_info, dict):
image_url = movie_info.get('image_url', '')
else:
image_url = movie_info
return json.dumps({
"status": "success",
"movie": movie,
"theatre": theatre,
"showtime": showtime,
"price":price,
"image_url": image_url,
"message": f"Book the ticket and enjoy the show!\n\nMovie: {movie}\nTheatre: {theatre}\nTime: {showtime}"
})
else:
return json.dumps({
"status": "failed",
"message": "Show details do not exist"
})
# Collect all tools
tools = [
movie_entity_correction,
theatre_entity_correction,
query_database,
book_ticket
]
# Bind tools to LLM
llm_with_tools = llm.bind_tools(tools)
# ============================================================================
# Graph Nodes
# ============================================================================
def analyze_query(state: AgentState) -> AgentState:
"""Analyze user query and decide if tools are needed."""
start = time.time()
system_prompt = f"""You are a helpful movie booking assistant with access to tools.
Current date: {datetime.now()}
Database schema(SQL):
- movies(id: int, name: str, genre: str)
- theatres(id: int, name: str)
- showtimes(id: int, movie_id: int, theatre_id: int, showtime: timestamp, price: float)
You have access to these tools:
- movie_entity_correction: Correct movie names
- theatre_entity_correction: Correct theatre names
- query_database: Execute SQL queries
- book_ticket: Helping user to provide a movie details for booking
For queries that need information from the database, use the appropriate tools.
For casual conversation or when you can answer directly, respond naturally without tools.
Important instructions:
- Use **descriptive variable names** for values returned by previous steps (e.g., `corrected_theatre_name`, `corrected_movie_name`).
- **Do not hardcode** resolved values into later steps β always use the variable name (e.g., use `corrected_theatre_name`).
- While fetching the show times please also show the theatre names
- correct the entities names like theatre, movie before quering in sql db
- always keep in mind about the current date while showing movie details because no one wants to book ticket before current time
Examples of when to use tools:
- "Show me theatres playing Avatar" β Use movie_entity_correction, then query_database
- "Book Avatar at PVR at 7 PM" β Use movie_entity_correction, theatre_entity_correction, then for help book_ticket
- "What movies are available?" β Use query_database
Examples of when NOT to use tools:
- "Hello" β Respond directly
- "Thank you" β Respond directly
"""
messages = [SystemMessage(content=system_prompt)] + state["messages"]
response = llm_with_tools.invoke(messages)
end = time.time()
print(response.content,'\n', "Time Taken - ", end-start)
return {
"messages": [response],
"requires_tools": bool(response.tool_calls)
}
def execute_tools(state: AgentState) -> AgentState:
"""Execute tool calls from the LLM."""
tool_node = ToolNode(tools)
result = tool_node.invoke(state)
return result
def generate_response(state: AgentState) -> AgentState:
"""Generate final natural language response."""
last_message = state["messages"][-1]
# Check if this is a tool result
if hasattr(last_message, 'tool_calls'):
# Get tool results
# system_prompt = f"""You are a friendly movie booking assistant.
# Based on the tool results, provide a natural, helpful response to the user.
# If a booking was successful, congratulate them and provide the details.
# If information was found, present it clearly.
# If nothing was found, politely inform the user and offer to help in another way.
# Current date: {datetime.now()}
# """
# messages = [SystemMessage(content=system_prompt)] + state["messages"]
# response = llm.invoke(messages)
# Check for booking success
booking_response = {"movie": None}
for msg in reversed(state["messages"]):
if hasattr(msg, 'content') and 'status' in str(msg.content):
try:
booking_data = json.loads(msg.content)
if booking_data.get("status") == "success":
booking_response = {
"movie": booking_data.get("movie"),
"theatre": booking_data.get("theatre"),
"showtime": booking_data.get("showtime"),
"price": booking_data.get("price"),
"image_url": booking_data.get("image_url")
}
break
except:
pass
return {
"booking_response": booking_response
}
return {"booking_response": {"movie": None}}
def should_continue(state: AgentState) -> Literal["tools", "respond"]:
"""Decide whether to use tools or respond directly."""
last_message = state["messages"][-1]
if hasattr(last_message, 'tool_calls') and last_message.tool_calls:
return "tools"
return "respond"
# ============================================================================
# Build Graph
# ============================================================================
def create_movie_booking_graph():
"""Create and compile the LangGraph workflow."""
workflow = StateGraph(AgentState)
# Add nodes
workflow.add_node("analyze", analyze_query)
workflow.add_node("tools", execute_tools)
workflow.add_node("respond", generate_response)
# Set entry point
workflow.set_entry_point("analyze")
# Add conditional edges
workflow.add_conditional_edges(
"analyze",
should_continue,
{
"tools": "tools",
"respond": "respond"
}
)
# Tools go back to analyze for potential follow-up
workflow.add_edge("tools", "analyze")
# End after responding
workflow.add_edge("respond", END)
return workflow.compile()
# ============================================================================
# Main Execution
# ============================================================================
app = create_movie_booking_graph()
def check_book_ticket_success(messages):
"""Check if booking was successful in the messages."""
messages_dict = messages_to_dict(messages)
for i in messages_dict:
if i['type']=='tool':
if i['data']['name']=="book_ticket":
return False
return True
def run_agent(conversation_history, user_input):
"""Run the movie booking agent."""
if conversation_history is None:
conversation_history = []
history_length = len(conversation_history)
conversation_history.append(HumanMessage(content=user_input))
# Run the graph
initial_state = {
"messages": conversation_history.copy(),
"booking_response": {"movie": None},
"requires_tools": False,
"tool_outputs": {},
"current_step": 0
}
result = app.invoke(initial_state)
result['messages'] = result['messages'][history_length:]
if check_book_ticket_success(result['messages']):
result["booking_response"]["movie"] = None
# Get final response
final_message = result["messages"][-1]
assistant_response = final_message.content
conversation_history.append(AIMessage(content=assistant_response))
print(f"\nπ€ Bot: {assistant_response}\n")
# Show booking confirmation if successful
if result["booking_response"]["movie"] is not None:
print("β
Booking confirmed!")
print(f" Movie: {result['booking_response']['movie']}")
print(f" Theatre: {result['booking_response']['theatre']}")
print(f" Time: {result['booking_response']['showtime']}")
print(f" Price: {result['booking_response']['price']}")
print(f" Image URL: {result['booking_response']['image_url']}\n")
return result, assistant_response
if __name__ == "__main__":
user_input = input("User: ")
result = run_agent(conversation_history=None, user_input=user_input) |