-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.py
More file actions
244 lines (148 loc) · 6.61 KB
/
graph.py
File metadata and controls
244 lines (148 loc) · 6.61 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
import requests
import os
from dotenv import load_dotenv
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
from crawler import Crawler
from models import ReviewAnalysis, State
from prompts import RecommendationPrompts
from chroma_cache import Cache
REVIEW_KEYWORDS = ["review", "verdict", "critics", "analysis", "rating"]
REVIEW_DOMAINS = ["ign.com", "rottentomatoes.com", "metacritic.com", "theverge.com", "polygon.com", "gamespot.com", "filmcompanion.in"]
SUMMARY_DOMAINS = ["wikipedia.org", "imdb.com", "fandom.com", "rottentomatoes.com", "metacritic.com"]
class Graph:
def __init__(self):
load_dotenv
self.crawler = Crawler()
self.llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.1)
self.prompts = RecommendationPrompts()
self.graph = self._build_graph()
self.cache = Cache()
def _build_graph(self):
graph = StateGraph(State)
graph.add_node("check_cache_step", self.search_cache)
graph.add_node("router", self.router)
graph.add_node("search_media_step", self.search_media)
graph.add_node("search_analyze_step", self.search_reviews)
graph.add_node("recommend_step", self.recommendation_step)
graph.set_entry_point("check_cache_step")
graph.add_edge("check_cache_step", "router")
graph.add_conditional_edges(
"router",
lambda state: state.next,
path_map={"cache_hit": END, "cache_miss" : "search_media_step"}
)
graph.add_edge("search_media_step", "search_analyze_step")
graph.add_edge("search_analyze_step", "recommend_step")
graph.add_edge("recommend_step", END)
return graph.compile()
def search_cache(self, state: State):
cached_summary = self.cache.semantic_lookup(state.title)
if cached_summary:
print(f"[Semantic Cache HIT] Summary and Analysis for '{state.title}'" )
stored_summary = cached_summary[0]['summary']
stored_analysis = cached_summary[0]['analysis']
return {"summary": stored_summary, "analysis": stored_analysis}
print(f"[Semantic Cache MISS] Summary for '{state.title}'")
return {}
def router(self, state: State):
if state.summary and state.analysis:
return {"next": "cache_hit"}
return {"next": "cache_miss"}
async def search_media(self, state: State):
search_query = f"{state.title}"
headers = {
"X-API-KEY": os.getenv("SERPER_API_KEY"),
"Content-Type": "application/json"
}
payload = {"q": search_query}
response = requests.post("https://google.serper.dev/search", headers=headers, json=payload)
response.raise_for_status()
data = response.json()
for result in data.get("organic", []):
url = result.get("link", "").lower()
if any(domain in url for domain in SUMMARY_DOMAINS):
search_link = result["link"]
break
scraped = await self.crawler.scrape_review_pages(search_link)
messages = [
SystemMessage(content=self.prompts.SUMMARY_SYSTEM),
HumanMessage(content=self.prompts.summary_analysis_user(state.title, scraped))
]
response = self.llm.invoke(messages)
return {"summary": response.content}
async def search_reviews(self, state: State):
search_query = f"{state.title} reviews"
results = []
headers = {
"X-API-KEY": os.getenv("SERPER_API_KEY"),
"Content-Type": "application/json"
}
payload = {"q": search_query}
try:
response = requests.post("https://google.serper.dev/search", headers=headers, json=payload)
response.raise_for_status()
data = response.json()
filtered_links = []
for item in data.get("organic", []):
url = item.get("link", "").lower()
snippet = (item.get("snippet") or "").lower()
if "youtube.com" in url or "youtu.be" in url:
continue
if any(k in url for k in REVIEW_KEYWORDS) or any(k in snippet for k in REVIEW_KEYWORDS) or any(domain in url for domain in REVIEW_DOMAINS):
filtered_links.append(item.get("link"))
if len(filtered_links) >= 6:
break
# Top 3 organic results
for url in filtered_links:
scraped = await self.crawler.scrape_review_pages(url)
if scraped:
results.append({
"url": url,
"content": scraped
})
except Exception as e:
print(f"[Serper Error] {e}")
reviews = []
for result in results:
analysis = self.analyze_reviews(state.title, result['content'])
reviews.append(analysis)
return {"reviews": reviews}
def analyze_reviews(self, name: str, content: str) -> ReviewAnalysis:
structured_llm = self.llm.with_structured_output(ReviewAnalysis)
messages = [
SystemMessage(content=self.prompts.REVIEW_ANALYSIS_SYSTEM),
HumanMessage(content=self.prompts.review_analysis_user(name, content))
]
try:
analysis = structured_llm.invoke(messages)
return analysis
except Exception as e:
print(e)
return ReviewAnalysis(
title="Unknown",
platform="Unknown",
average_rating="",
original_rating="",
summary="",
sentiment=None,
pros="",
cons="",
website=""
)
def recommendation_step(self, state: State):
title = state.title
summary = state.summary
reviews = state.reviews
messages = [
SystemMessage(content=self.prompts.RECOMMENDATION_SYSTEM),
HumanMessage(content=self.prompts.recommendation_user(title, reviews))
]
response = self.llm.invoke(messages)
self.cache.store_review(title=title, summary=summary, analysis=response.content)
return {"analysis": response.content}
async def run(self, query: str) -> State:
initial_state = State(title=query)
final_state = await self.graph.ainvoke(initial_state)
return State(**final_state)