embed query fix
Browse files- routes/api/descriptive.py +174 -75
routes/api/descriptive.py
CHANGED
@@ -1,94 +1,193 @@
|
|
1 |
-
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
import logging
|
4 |
-
from typing import Dict, Any
|
5 |
|
6 |
-
|
7 |
-
from
|
8 |
-
generate_detailed_feed,
|
9 |
-
cache_detailed_feed, # Function to cache the detailed feed
|
10 |
-
get_cached_detailed_feed # Function to retrieve the detailed feed
|
11 |
-
)
|
12 |
-
# We also need to get the initial summaries, which are managed by daily_feed.py
|
13 |
-
from components.generators.daily_feed import get_cached_daily_feed
|
14 |
|
15 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
16 |
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
"""
|
22 |
-
|
23 |
-
|
24 |
-
The final detailed feed is then cached by this endpoint using its dedicated key.
|
25 |
"""
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
try:
|
28 |
-
|
29 |
-
initial_summaries = get_cached_daily_feed() # From daily_feed.py
|
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 |
-
except HTTPException as he:
|
58 |
-
raise he
|
59 |
except Exception as e:
|
60 |
-
logging.error(f"Error
|
61 |
-
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
-
|
67 |
-
|
|
|
68 |
"""
|
69 |
-
|
70 |
-
|
71 |
"""
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
try:
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
status_code=status.HTTP_404_NOT_FOUND,
|
81 |
-
detail="No detailed news feed found in cache. Please run /api/descriptive/generate-detailed first."
|
82 |
-
)
|
83 |
-
|
84 |
-
logging.info("API Call: GET /api/descriptive/get-detailed completed successfully.")
|
85 |
-
return cached_detailed_feed
|
86 |
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
except Exception as e:
|
90 |
-
logging.error(f"
|
91 |
-
|
92 |
-
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
93 |
-
detail=f"An unexpected error occurred while retrieving cached detailed feed: {e}"
|
94 |
-
)
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import numpy as np
|
4 |
+
import redis
|
5 |
+
from typing import List, Dict, Any, Optional, Set
|
6 |
+
from openai import OpenAI
|
7 |
+
from llama_index.core.vector_stores.types import VectorStoreQuery, MetadataFilter, MetadataFilters, FilterOperator
|
8 |
+
from llama_index.core.schema import TextNode
|
9 |
+
from components.indexers.news_indexer import get_upstash_vector_store
|
10 |
import logging
|
|
|
11 |
|
12 |
+
from llama_index.core.settings import Settings
|
13 |
+
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
16 |
|
17 |
+
# π Environment variables for this module
|
18 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
19 |
+
REDIS_URL = os.environ.get("UPSTASH_REDIS_URL", "redis://localhost:6379")
|
20 |
+
|
21 |
+
# β
Redis client for this module
|
22 |
+
try:
|
23 |
+
detailed_explainer_redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
|
24 |
+
detailed_explainer_redis_client.ping()
|
25 |
+
logging.info("Redis client initialized for detailed_explainer.py.")
|
26 |
+
except Exception as e:
|
27 |
+
logging.critical(f"β FATAL ERROR: Could not connect to Redis in detailed_explainer.py: {e}")
|
28 |
+
raise
|
29 |
+
|
30 |
+
# Cache Key specific to detailed explanations
|
31 |
+
DETAILED_FEED_CACHE_KEY = "detailed_news_feed_cache"
|
32 |
+
|
33 |
+
# Ensure Settings.embed_model is configured globally.
|
34 |
+
try:
|
35 |
+
if not hasattr(Settings, 'embed_model') or Settings.embed_model is None:
|
36 |
+
logging.info("Settings.embed_model not yet configured, initializing with default HuggingFaceEmbedding.")
|
37 |
+
# Ensure this uses the same model as in news_ingest.py for consistency
|
38 |
+
Settings.embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/paraphrase-MiniLM-L3-v2")
|
39 |
+
except Exception as e:
|
40 |
+
logging.error(f"Failed to initialize Settings.embed_model in detailed_explainer: {e}")
|
41 |
+
|
42 |
|
43 |
+
# LLM prompt for detailed explanation
|
44 |
+
EXPLAINER_PROMPT = (
|
45 |
+
"You are an expert news analyst. Based on the following article content, "
|
46 |
+
"generate a concise, detailed explanation (50-60 words) for the headline provided. "
|
47 |
+
"Focus on the 'why it matters' and key context. Do not include any introductory phrases, just the explanation itself."
|
48 |
+
"\n\nHeadline: {headline}"
|
49 |
+
"\n\nArticle Content:\n{article_content}"
|
50 |
+
"\n\nDetailed Explanation (50-60 words):"
|
51 |
+
)
|
52 |
+
|
53 |
+
async def get_detailed_explanation_from_vector(
|
54 |
+
summary_item: Dict[str, Any],
|
55 |
+
vector_store_client: Any
|
56 |
+
) -> Dict[str, Any]:
|
57 |
"""
|
58 |
+
Takes a summary item, queries the vector store for its original article content,
|
59 |
+
and generates a detailed explanation using an LLM.
|
|
|
60 |
"""
|
61 |
+
headline_text = summary_item["summary"]
|
62 |
+
representative_article_link = summary_item["article_link"]
|
63 |
+
representative_title = summary_item["representative_title"]
|
64 |
+
|
65 |
+
detailed_content = ""
|
66 |
+
sources_found: Set[str] = set()
|
67 |
+
|
68 |
+
logging.info(f"Retrieving detailed content for headline: '{headline_text}' (from {representative_article_link})")
|
69 |
+
|
70 |
try:
|
71 |
+
query_text = f"{representative_title} {representative_article_link}" if representative_title else representative_article_link
|
|
|
72 |
|
73 |
+
# --- THE FIX IS HERE: Use .get_query_embedding() ---
|
74 |
+
query_embedding = Settings.embed_model.get_query_embedding(query_text)
|
75 |
+
|
76 |
+
filters = MetadataFilters(
|
77 |
+
filters=[MetadataFilter(key="url", value=representative_article_link, operator=FilterOperator.EQ)]
|
78 |
+
)
|
79 |
+
|
80 |
+
query = VectorStoreQuery(
|
81 |
+
query_embedding=query_embedding,
|
82 |
+
similarity_top_k=5,
|
83 |
+
filters=filters
|
84 |
+
)
|
85 |
+
result = vector_store_client.query(query)
|
86 |
+
|
87 |
+
if result.nodes:
|
88 |
+
for node in result.nodes:
|
89 |
+
node_content = node.get_content().strip()
|
90 |
+
if node_content:
|
91 |
+
detailed_content += node_content + "\n\n"
|
92 |
+
if "source" in node.metadata:
|
93 |
+
sources_found.add(node.metadata["source"])
|
94 |
+
|
95 |
+
if not detailed_content:
|
96 |
+
logging.warning(f"No usable content found in nodes retrieved for URL: {representative_article_link}. Falling back to title+url context.")
|
97 |
+
detailed_content = representative_title + " " + representative_article_link
|
98 |
+
|
99 |
+
else:
|
100 |
+
logging.warning(f"No original article found in vector store for URL: {representative_article_link}. Using summary as context.")
|
101 |
+
detailed_content = summary_item["summary"] + ". " + summary_item.get("explanation", "")
|
102 |
|
|
|
|
|
103 |
except Exception as e:
|
104 |
+
logging.error(f"β Error querying vector store for detailed content for '{representative_article_link}': {e}", exc_info=True)
|
105 |
+
detailed_content = summary_item["summary"] + ". " + summary_item.get("explanation", "")
|
106 |
+
|
107 |
+
# Generate detailed explanation using LLM
|
108 |
+
detailed_explanation_text = ""
|
109 |
+
try:
|
110 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
111 |
+
if not OPENAI_API_KEY:
|
112 |
+
raise ValueError("OPENAI_API_KEY is not set.")
|
113 |
+
|
114 |
+
llm_response = client.chat.completions.create(
|
115 |
+
model="gpt-4o",
|
116 |
+
messages=[
|
117 |
+
{"role": "system", "content": "You are a concise and informative news explainer."},
|
118 |
+
{"role": "user", "content": EXPLAINER_PROMPT.format(
|
119 |
+
headline=headline_text,
|
120 |
+
article_content=detailed_content
|
121 |
+
)},
|
122 |
+
],
|
123 |
+
max_tokens=100,
|
124 |
+
temperature=0.4,
|
125 |
)
|
126 |
+
detailed_explanation_text = llm_response.choices[0].message.content.strip()
|
127 |
+
logging.info(f"Generated detailed explanation for '{headline_text}'.")
|
128 |
+
|
129 |
+
except Exception as e:
|
130 |
+
logging.error(f"β Error generating detailed explanation for '{headline_text}': {e}", exc_info=True)
|
131 |
+
detailed_explanation_text = summary_item.get("explanation", "Could not generate a detailed explanation.")
|
132 |
+
|
133 |
+
return {
|
134 |
+
"title": headline_text,
|
135 |
+
"description": detailed_explanation_text,
|
136 |
+
"sources": list(sources_found) if sources_found else ["General News Sources"]
|
137 |
+
}
|
138 |
|
139 |
+
async def generate_detailed_feed(
|
140 |
+
cached_feed: Dict[str, Dict[int, Dict[str, Any]]]
|
141 |
+
) -> Dict[str, Dict[int, Dict[str, Any]]]:
|
142 |
"""
|
143 |
+
Generates detailed explanations for each summary in the cached feed.
|
144 |
+
Does NOT cache the result internally. The caller is responsible for caching.
|
145 |
"""
|
146 |
+
if not cached_feed:
|
147 |
+
logging.info("No cached feed found to generate detailed explanations from.")
|
148 |
+
return {}
|
149 |
+
|
150 |
+
detailed_feed_structured: Dict[str, Dict[int, Dict[str, Any]]] = {}
|
151 |
+
vector_store = get_upstash_vector_store()
|
152 |
+
|
153 |
+
for topic_key, summaries_map in cached_feed.items():
|
154 |
+
logging.info(f"Processing detailed explanations for topic: {topic_key}")
|
155 |
+
detailed_summaries_for_topic: Dict[int, Dict[str, Any]] = {}
|
156 |
+
|
157 |
+
for summary_id in sorted(summaries_map.keys()):
|
158 |
+
summary_item = summaries_map[summary_id]
|
159 |
+
|
160 |
+
detailed_item = await get_detailed_explanation_from_vector(summary_item, vector_store)
|
161 |
+
|
162 |
+
detailed_summaries_for_topic[summary_id] = detailed_item
|
163 |
+
|
164 |
+
detailed_feed_structured[topic_key] = detailed_summaries_for_topic
|
165 |
+
|
166 |
+
logging.info("β
Detailed explanation generation complete.")
|
167 |
+
return detailed_feed_structured
|
168 |
+
|
169 |
+
|
170 |
+
def cache_detailed_feed(feed_data: Dict[str, Dict[int, Dict[str, Any]]]):
|
171 |
+
"""Caches the given detailed feed data to Redis using its dedicated client."""
|
172 |
try:
|
173 |
+
detailed_explainer_redis_client.set(DETAILED_FEED_CACHE_KEY, json.dumps(feed_data, ensure_ascii=False))
|
174 |
+
detailed_explainer_redis_client.expire(DETAILED_FEED_CACHE_KEY, 86400)
|
175 |
+
logging.info(f"β
Detailed feed cached under key '{DETAILED_FEED_CACHE_KEY}' with 24-hour expiry.")
|
176 |
+
except Exception as e:
|
177 |
+
logging.error(f"β [Redis detailed feed caching error]: {e}", exc_info=True)
|
178 |
+
raise
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
|
180 |
+
|
181 |
+
def get_cached_detailed_feed() -> Dict[str, Dict[int, Dict[str, Any]]]:
|
182 |
+
"""Retrieves the cached detailed feed from Redis using its dedicated client."""
|
183 |
+
try:
|
184 |
+
cached_raw = detailed_explainer_redis_client.get(DETAILED_FEED_CACHE_KEY)
|
185 |
+
if cached_raw:
|
186 |
+
logging.info(f"β
Retrieved cached detailed feed from '{DETAILED_FEED_CACHE_KEY}'.")
|
187 |
+
return json.loads(cached_raw)
|
188 |
+
else:
|
189 |
+
logging.info(f"βΉοΈ No cached detailed feed found under key '{DETAILED_FEED_CACHE_KEY}'.")
|
190 |
+
return {}
|
191 |
except Exception as e:
|
192 |
+
logging.error(f"β [Redis detailed feed retrieval error]: {e}", exc_info=True)
|
193 |
+
return {}
|
|
|
|
|
|