rkihacker commited on
Commit
e1111e0
·
verified ·
1 Parent(s): 2a0098d

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +48 -27
main.py CHANGED
@@ -4,8 +4,13 @@ from fastapi import FastAPI, HTTPException, Query
4
  from dotenv import load_dotenv
5
  import aiohttp
6
  from bs4 import BeautifulSoup
 
7
 
8
  # --- Configuration ---
 
 
 
 
9
  load_dotenv()
10
  LLM_API_KEY = os.getenv("LLM_API_KEY")
11
 
@@ -30,6 +35,15 @@ SNAPZION_HEADERS = {
30
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
31
  }
32
 
 
 
 
 
 
 
 
 
 
33
  # LLM Configuration
34
  LLM_API_URL = "https://api.inference.net/v1/chat/completions"
35
  LLM_MODEL = "meta-llama/llama-3.1-8b-instruct/fp-8"
@@ -38,44 +52,46 @@ LLM_MODEL = "meta-llama/llama-3.1-8b-instruct/fp-8"
38
  app = FastAPI(
39
  title="AI Search Snippets API (Snapzion)",
40
  description="Provides AI-generated summaries from Snapzion search results.",
41
- version="1.0.1"
42
  )
43
 
44
  # --- Core Asynchronous Functions ---
45
 
46
  async def call_snapzion_search(session: aiohttp.ClientSession, query: str) -> list:
47
- """Calls the Snapzion search API and returns a list of organic results."""
48
  try:
49
  async with session.post(SNAPZION_API_URL, headers=SNAPZION_HEADERS, json={"query": query}, timeout=15) as response:
50
  response.raise_for_status()
51
  data = await response.json()
52
  return data.get("organic_results", [])
53
  except Exception as e:
 
54
  raise HTTPException(status_code=503, detail=f"Search service (Snapzion) failed: {e}")
55
 
 
56
  async def scrape_url(session: aiohttp.ClientSession, url: str) -> str:
57
- """Asynchronously scrapes the primary text content from a URL, ignoring PDFs."""
58
  if url.lower().endswith('.pdf'):
59
- return "Content is a PDF, which cannot be scraped."
60
  try:
61
- async with session.get(url, timeout=10) as response:
 
62
  if response.status != 200:
63
- return f"Error: Failed to fetch {url} with status {response.status}"
 
64
  html = await response.text()
65
  soup = BeautifulSoup(html, "html.parser")
66
  for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside']):
67
  tag.decompose()
68
  return " ".join(soup.stripped_strings)
69
  except Exception as e:
70
- return f"Error: Could not scrape {url}. Reason: {e}"
 
71
 
72
  async def get_ai_snippet(query: str, context: str, sources: list) -> str:
73
- """Generates a synthesized answer using an LLM based on the provided context."""
74
  headers = {"Authorization": f"Bearer {LLM_API_KEY}", "Content-Type": "application/json"}
75
  source_list_str = "\n".join([f"[{i+1}] {source['title']}: {source['link']}" for i, source in enumerate(sources)])
76
-
77
  prompt = f"""
78
- Based *only* on the provided context from web pages, provide a concise, factual answer to the user's query. Cite every sentence with the corresponding source number(s), like `[1]`, `[2]`, or `[1, 3]`.
79
 
80
  Sources:
81
  {source_list_str}
@@ -90,7 +106,6 @@ User Query: "{query}"
90
  Answer with citations:
91
  """
92
  data = {"model": LLM_MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": 500}
93
-
94
  async with aiohttp.ClientSession() as session:
95
  try:
96
  async with session.post(LLM_API_URL, headers=headers, json=data, timeout=45) as response:
@@ -98,39 +113,45 @@ Answer with citations:
98
  result = await response.json()
99
  return result['choices'][0]['message']['content']
100
  except Exception as e:
 
101
  raise HTTPException(status_code=502, detail=f"Failed to get response from LLM: {e}")
102
 
103
  # --- API Endpoint ---
104
 
105
  @app.get("/search")
106
  async def ai_search(q: str = Query(..., min_length=3, description="The search query.")):
107
- """
108
- Performs an AI-powered search using Snapzion. It finds relevant web pages,
109
- scrapes their content, and generates a synthesized answer with citations.
110
- """
111
  async with aiohttp.ClientSession() as session:
112
- # 1. Search for relevant web pages using Snapzion
113
  search_results = await call_snapzion_search(session, q)
114
  if not search_results:
115
  raise HTTPException(status_code=404, detail="Could not find any relevant sources for the query.")
116
 
117
- # Limit to the top 4 results for speed and relevance
118
- sources = search_results[:4]
119
-
120
- # 2. Scrape all pages concurrently for speed
121
  scrape_tasks = [scrape_url(session, source["link"]) for source in sources]
122
  scraped_contents = await asyncio.gather(*scrape_tasks)
123
 
124
- # 3. Combine content and snippets for a rich context
125
- full_context = "\n\n".join(
126
- f"Source [{i+1}] (from {sources[i]['link']}):\nOriginal Snippet: {sources[i]['snippet']}\nScraped Content: {content}"
127
- for i, content in enumerate(scraped_contents) if not content.startswith("Error:")
128
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
  if not full_context.strip():
131
- raise HTTPException(status_code=500, detail="Failed to scrape content from all available sources.")
 
132
 
133
- # 4. Generate the final AI snippet
134
  ai_summary = await get_ai_snippet(q, full_context, sources)
135
 
136
  return {"ai_summary": ai_summary, "sources": sources}
 
4
  from dotenv import load_dotenv
5
  import aiohttp
6
  from bs4 import BeautifulSoup
7
+ import logging
8
 
9
  # --- Configuration ---
10
+ # Configure logging to see what's happening
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
+
14
  load_dotenv()
15
  LLM_API_KEY = os.getenv("LLM_API_KEY")
16
 
 
35
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
36
  }
37
 
38
+ # ***** CHANGE 1: Add general-purpose browser headers for scraping *****
39
+ SCRAPING_HEADERS = {
40
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
41
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
42
+ 'Accept-Language': 'en-US,en;q=0.9',
43
+ 'Connection': 'keep-alive',
44
+ 'Upgrade-Insecure-Requests': '1',
45
+ }
46
+
47
  # LLM Configuration
48
  LLM_API_URL = "https://api.inference.net/v1/chat/completions"
49
  LLM_MODEL = "meta-llama/llama-3.1-8b-instruct/fp-8"
 
52
  app = FastAPI(
53
  title="AI Search Snippets API (Snapzion)",
54
  description="Provides AI-generated summaries from Snapzion search results.",
55
+ version="1.1.0" # Version bump for new resilience feature
56
  )
57
 
58
  # --- Core Asynchronous Functions ---
59
 
60
  async def call_snapzion_search(session: aiohttp.ClientSession, query: str) -> list:
 
61
  try:
62
  async with session.post(SNAPZION_API_URL, headers=SNAPZION_HEADERS, json={"query": query}, timeout=15) as response:
63
  response.raise_for_status()
64
  data = await response.json()
65
  return data.get("organic_results", [])
66
  except Exception as e:
67
+ logger.error(f"Snapzion API call failed: {e}")
68
  raise HTTPException(status_code=503, detail=f"Search service (Snapzion) failed: {e}")
69
 
70
+ # ***** CHANGE 2: Improve the scraping function *****
71
  async def scrape_url(session: aiohttp.ClientSession, url: str) -> str:
72
+ """Asynchronously scrapes text from a URL, now with browser headers."""
73
  if url.lower().endswith('.pdf'):
74
+ return "Error: Content is a PDF, which cannot be scraped."
75
  try:
76
+ # Use the new scraping headers to look like a real browser
77
+ async with session.get(url, headers=SCRAPING_HEADERS, timeout=10, ssl=False) as response:
78
  if response.status != 200:
79
+ logger.warning(f"Failed to fetch {url}, status code: {response.status}")
80
+ return f"Error: Failed to fetch with status {response.status}"
81
  html = await response.text()
82
  soup = BeautifulSoup(html, "html.parser")
83
  for tag in soup(['script', 'style', 'nav', 'footer', 'header', 'aside']):
84
  tag.decompose()
85
  return " ".join(soup.stripped_strings)
86
  except Exception as e:
87
+ logger.warning(f"Could not scrape {url}. Reason: {e}")
88
+ return f"Error: Could not scrape. Reason: {e}"
89
 
90
  async def get_ai_snippet(query: str, context: str, sources: list) -> str:
 
91
  headers = {"Authorization": f"Bearer {LLM_API_KEY}", "Content-Type": "application/json"}
92
  source_list_str = "\n".join([f"[{i+1}] {source['title']}: {source['link']}" for i, source in enumerate(sources)])
 
93
  prompt = f"""
94
+ Based *only* on the provided context, provide a concise, factual answer to the user's query. Cite every sentence with the corresponding source number(s), like `[1]` or `[2, 3]`.
95
 
96
  Sources:
97
  {source_list_str}
 
106
  Answer with citations:
107
  """
108
  data = {"model": LLM_MODEL, "messages": [{"role": "user", "content": prompt}], "max_tokens": 500}
 
109
  async with aiohttp.ClientSession() as session:
110
  try:
111
  async with session.post(LLM_API_URL, headers=headers, json=data, timeout=45) as response:
 
113
  result = await response.json()
114
  return result['choices'][0]['message']['content']
115
  except Exception as e:
116
+ logger.error(f"LLM API call failed: {e}")
117
  raise HTTPException(status_code=502, detail=f"Failed to get response from LLM: {e}")
118
 
119
  # --- API Endpoint ---
120
 
121
  @app.get("/search")
122
  async def ai_search(q: str = Query(..., min_length=3, description="The search query.")):
 
 
 
 
123
  async with aiohttp.ClientSession() as session:
 
124
  search_results = await call_snapzion_search(session, q)
125
  if not search_results:
126
  raise HTTPException(status_code=404, detail="Could not find any relevant sources for the query.")
127
 
128
+ sources = search_results[:5] # Use top 5 sources
 
 
 
129
  scrape_tasks = [scrape_url(session, source["link"]) for source in sources]
130
  scraped_contents = await asyncio.gather(*scrape_tasks)
131
 
132
+ # ***** CHANGE 3: Implement the robust fallback logic *****
133
+ successful_scrapes = [content for content in scraped_contents if not content.startswith("Error:")]
134
+
135
+ full_context = ""
136
+ if successful_scrapes:
137
+ logger.info(f"Successfully scraped {len(successful_scrapes)} out of {len(sources)} sources.")
138
+ # Build context from successfully scraped content
139
+ full_context = "\n\n".join(
140
+ f"Source [{i+1}] ({sources[i]['link']}):\n{scraped_contents[i]}"
141
+ for i in range(len(sources)) if not scraped_contents[i].startswith("Error:")
142
+ )
143
+ else:
144
+ # If ALL scrapes failed, fall back to using the snippets from the search API
145
+ logger.warning("All scraping attempts failed. Falling back to using API snippets for context.")
146
+ full_context = "\n\n".join(
147
+ f"Source [{i+1}] ({source['link']}):\n{source['snippet']}"
148
+ for i, source in enumerate(sources)
149
+ )
150
 
151
  if not full_context.strip():
152
+ # This is a final safety net, should rarely be hit now
153
+ raise HTTPException(status_code=500, detail="Could not construct any context from sources or snippets.")
154
 
 
155
  ai_summary = await get_ai_snippet(q, full_context, sources)
156
 
157
  return {"ai_summary": ai_summary, "sources": sources}