ragV98 commited on
Commit
994a0a2
Β·
1 Parent(s): f86aeaf

embed query fix

Browse files
Files changed (1) hide show
  1. routes/api/descriptive.py +174 -75
routes/api/descriptive.py CHANGED
@@ -1,94 +1,193 @@
1
- # routes/api/descriptive.py
2
- from fastapi import APIRouter, HTTPException, status
 
 
 
 
 
 
 
3
  import logging
4
- from typing import Dict, Any
5
 
6
- # Import functions directly from the now standalone detailed_explainer
7
- from components.generators.detailed_explainer import (
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
- router = APIRouter()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- @router.get("/generate-detailed") # <<< CHANGED TO GET REQUEST
20
- async def generate_detailed_headlines_endpoint() -> Dict[str, Any]:
 
 
 
 
 
 
 
 
 
 
 
 
21
  """
22
- Generates detailed explanations for the latest cached summaries.
23
- This step requires initial summaries to be present in Redis cache (from daily_feed.py).
24
- The final detailed feed is then cached by this endpoint using its dedicated key.
25
  """
26
- logging.info("API Call: GET /api/descriptive/generate-detailed initiated.")
 
 
 
 
 
 
 
 
27
  try:
28
- # Step 1: Retrieve the cached initial summaries
29
- initial_summaries = get_cached_daily_feed() # From daily_feed.py
30
 
31
- if not initial_summaries:
32
- logging.warning("No initial summaries found in cache to generate detailed explanations from.")
33
- raise HTTPException(
34
- status_code=status.HTTP_404_NOT_FOUND,
35
- detail="No initial news summaries found in cache. Please run the ingestion/summarization process first (e.g., /api/ingest/run)."
36
- )
37
-
38
- # Step 2: Generate detailed explanations (this is an async call to detailed_explainer)
39
- detailed_feed = await generate_detailed_feed(initial_summaries)
40
-
41
- if not detailed_feed:
42
- raise HTTPException(
43
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
44
- detail="Failed to generate detailed explanations. Check server logs for errors during LLM calls or content retrieval."
45
- )
46
-
47
- # Step 3: Cache the final detailed feed using the function from detailed_explainer
48
- # This function (cache_detailed_feed) internally uses its own Redis client and DETAILED_FEED_CACHE_KEY
49
- cache_detailed_feed(detailed_feed)
50
-
51
- logging.info("API Call: GET /api/descriptive/generate-detailed completed successfully.")
52
-
53
- total_items = sum(len(topic_summaries) for topic_summaries in detailed_feed.values())
54
-
55
- return {"status": "success", "message": "Detailed headlines generated and cached.", "items": total_items}
 
 
 
 
56
 
57
- except HTTPException as he:
58
- raise he
59
  except Exception as e:
60
- logging.error(f"Error in /api/descriptive/generate-detailed: {e}", exc_info=True)
61
- raise HTTPException(
62
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
63
- detail=f"An unexpected error occurred during detailed feed generation: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  )
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- @router.get("/get-detailed") # Endpoint for retrieving detailed headlines
67
- async def get_detailed_headlines_endpoint() -> Dict[str, Dict[int, Dict[str, Any]]]:
 
68
  """
69
- Retrieves the most recently cached *fully detailed* news feed.
70
- Returns 404 if no detailed feed is found in cache.
71
  """
72
- logging.info("API Call: GET /api/descriptive/get-detailed initiated.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  try:
74
- # Retrieve the cached detailed feed using the function from detailed_explainer
75
- cached_detailed_feed = get_cached_detailed_feed()
76
-
77
- if not cached_detailed_feed:
78
- logging.info("No full detailed news feed found in cache.")
79
- raise HTTPException(
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
- except HTTPException as he:
88
- raise he
 
 
 
 
 
 
 
 
 
89
  except Exception as e:
90
- logging.error(f"Error in /api/descriptive/get-detailed: {e}", exc_info=True)
91
- raise HTTPException(
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 {}