Update app.py
Browse files
app.py
CHANGED
@@ -6,6 +6,7 @@ from fastapi.encoders import jsonable_encoder
|
|
6 |
from bs4 import BeautifulSoup
|
7 |
import requests
|
8 |
import urllib.parse
|
|
|
9 |
|
10 |
app = FastAPI()
|
11 |
|
@@ -244,111 +245,7 @@ async def ask_website(url: str, question: str, model: str = "llama-3-70b"):
|
|
244 |
raise HTTPException(status_code=500, detail=f"Error fetching or processing URL: {e}")
|
245 |
except Exception as e:
|
246 |
raise HTTPException(status_code=500, detail=f"Error during question answering: {e}")
|
247 |
-
|
248 |
-
import requests
|
249 |
-
|
250 |
-
def get_gemini_content(question, model="flash"):
|
251 |
-
"""
|
252 |
-
Sends a request to the Gemini API and returns the content of the response.
|
253 |
-
|
254 |
-
Args:
|
255 |
-
question: The question to ask the Gemini API.
|
256 |
-
model: The Gemini model to use (flash or pro). Defaults to "flash".
|
257 |
-
|
258 |
-
Returns:
|
259 |
-
The content string from the API response, or None if the request fails.
|
260 |
-
"""
|
261 |
-
|
262 |
-
if model == "pro":
|
263 |
-
url = f"https://gemini-pro.developer-house.workers.dev/?question={question}"
|
264 |
-
else:
|
265 |
-
url = f"https://gemini-flash.developer-house.workers.dev/?question={question}"
|
266 |
-
response = requests.get(url)
|
267 |
-
|
268 |
-
if response.status_code == 200:
|
269 |
-
data = response.json()
|
270 |
-
return data['content']
|
271 |
-
else:
|
272 |
-
print(f"API request failed with status code: {response.status_code}")
|
273 |
-
return None
|
274 |
-
|
275 |
-
@app.get("/api/gemini")
|
276 |
-
async def gemini(q: str, model: str = "flash"):
|
277 |
-
"""Get answers from Gemini models."""
|
278 |
-
try:
|
279 |
-
content = get_gemini_content(q, model)
|
280 |
-
if content:
|
281 |
-
return JSONResponse(content=jsonable_encoder({"answer": content}))
|
282 |
-
else:
|
283 |
-
raise HTTPException(status_code=500, detail="Gemini API request failed.")
|
284 |
-
except Exception as e:
|
285 |
-
raise HTTPException(status_code=500, detail=f"Error during Gemini request: {e}")
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
@app.get("/api/web_gemini")
|
290 |
-
async def web_gemini(q: str, model: str = "flash"):
|
291 |
-
"""Search the web and get answers from Gemini models."""
|
292 |
-
try:
|
293 |
-
with WEBS() as webs:
|
294 |
-
search_results = webs.text(keywords=q, max_results=3)
|
295 |
-
extracted_results = []
|
296 |
-
for result in search_results:
|
297 |
-
if 'href' in result:
|
298 |
-
link = result['href']
|
299 |
-
try:
|
300 |
-
response = requests.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"})
|
301 |
-
response.raise_for_status()
|
302 |
-
visible_text = extract_text_from_webpage(response.text)
|
303 |
-
if len(visible_text) > 10000:
|
304 |
-
visible_text = visible_text[:10000] + "..."
|
305 |
-
extracted_results.append({"link": link, "text": visible_text})
|
306 |
-
except requests.exceptions.RequestException as e:
|
307 |
-
print(f"Error fetching or processing {link}: {e}")
|
308 |
-
extracted_results.append({"link": link, "text": None})
|
309 |
-
else:
|
310 |
-
extracted_results.append({"link": None, "text": None})
|
311 |
-
|
312 |
-
content = jsonable_encoder({"extracted_results": extracted_results})
|
313 |
-
|
314 |
-
# Call Gemini API based on the selected model
|
315 |
-
if model == "pro":
|
316 |
-
url = f"https://gemini-pro.developer-house.workers.dev/?question=Based on the following text from Google Search, answer this question in Paragraph: [QUESTION] {q} [TEXT] {content}"
|
317 |
-
else:
|
318 |
-
url = f"https://gemini-flash.developer-house.workers.dev/?question=Based on the following text from Google Search, answer this question in Paragraph: [QUESTION] {q} [TEXT] {content}"
|
319 |
-
|
320 |
-
response = requests.get(url)
|
321 |
-
response.raise_for_status()
|
322 |
-
data = response.json()
|
323 |
-
return data['content']
|
324 |
-
|
325 |
-
except requests.exceptions.RequestException as e:
|
326 |
-
raise HTTPException(status_code=500, detail=f"Error during web search or Gemini request: {e}")
|
327 |
-
|
328 |
-
@app.get("/api/ask_website_gemini")
|
329 |
-
async def ask_website_gemini(
|
330 |
-
url: str,
|
331 |
-
q: str,
|
332 |
-
model: str = "flash"
|
333 |
-
):
|
334 |
-
"""Perform a text search."""
|
335 |
-
try:
|
336 |
-
# Extract text from the given URL
|
337 |
-
response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"})
|
338 |
-
response.raise_for_status()
|
339 |
-
visible_text = extract_text_from_webpage(response.text)
|
340 |
-
if len(visible_text) > 30000: # Adjust max_chars based on your needs
|
341 |
-
visible_text = visible_text[:30000] + "..."
|
342 |
-
if model=="pro":
|
343 |
-
url = f"https://gemini-pro.developer-house.workers.dev/?question= Based on the following text, answer this question in Paragraph: [QUESTION] {question} [TEXT] {visible_text}"
|
344 |
-
else:
|
345 |
-
url = f"https://gemini-flash.developer-house.workers.dev/?question={q}"
|
346 |
-
response = requests.get(url)
|
347 |
-
data = response.json()
|
348 |
-
return data['content']
|
349 |
-
except requests.exceptions.RequestException as e:
|
350 |
-
raise HTTPException(status_code=500, detail=f"Gemini API request failed: {e}")
|
351 |
-
|
352 |
@app.get("/api/maps")
|
353 |
async def maps(
|
354 |
q: str,
|
@@ -419,6 +316,214 @@ def get_ascii_weather(location: str):
|
|
419 |
else:
|
420 |
return {"error": f"Unable to fetch weather data. Status code: {response.status_code}"}
|
421 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
422 |
# Run the API server if this script is executed
|
423 |
if __name__ == "__main__":
|
424 |
import uvicorn
|
|
|
6 |
from bs4 import BeautifulSoup
|
7 |
import requests
|
8 |
import urllib.parse
|
9 |
+
import os
|
10 |
|
11 |
app = FastAPI()
|
12 |
|
|
|
245 |
raise HTTPException(status_code=500, detail=f"Error fetching or processing URL: {e}")
|
246 |
except Exception as e:
|
247 |
raise HTTPException(status_code=500, detail=f"Error during question answering: {e}")
|
248 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
249 |
@app.get("/api/maps")
|
250 |
async def maps(
|
251 |
q: str,
|
|
|
316 |
else:
|
317 |
return {"error": f"Unable to fetch weather data. Status code: {response.status_code}"}
|
318 |
|
319 |
+
|
320 |
+
import os
|
321 |
+
from typing import Optional
|
322 |
+
from webscout import WEBS
|
323 |
+
from webscout.DWEBS import (
|
324 |
+
GoogleSearcher,
|
325 |
+
QueryResultsExtractor,
|
326 |
+
BatchWebpageFetcher,
|
327 |
+
BatchWebpageContentExtractor,
|
328 |
+
OSEnver,
|
329 |
+
)
|
330 |
+
from webscout.Provider import DeepInfra
|
331 |
+
from rich.console import Console
|
332 |
+
from rich.markdown import Markdown
|
333 |
+
from tiktoken import get_encoding
|
334 |
+
|
335 |
+
class AISearchEngine:
|
336 |
+
def __init__(
|
337 |
+
self,
|
338 |
+
google_search_result_num: int = 3,
|
339 |
+
duckduckgo_search_result_num: int = 3,
|
340 |
+
ai_model_1: str = 'microsoft/WizardLM-2-8x22B', # First AI model
|
341 |
+
ai_model_2: str = 'Qwen/Qwen2-72B-Instruct', # Second AI model for summarization
|
342 |
+
ai_max_tokens: int = 8192,
|
343 |
+
proxy: Optional[str] = None,
|
344 |
+
max_google_content_tokens: int = 60000 # Maximum tokens for Google content
|
345 |
+
):
|
346 |
+
self.console = Console()
|
347 |
+
self.enver = OSEnver()
|
348 |
+
self.enver.set_envs(proxies=proxy)
|
349 |
+
self.google_searcher = GoogleSearcher()
|
350 |
+
self.query_results_extractor = QueryResultsExtractor()
|
351 |
+
self.batch_webpage_fetcher = BatchWebpageFetcher()
|
352 |
+
self.batch_webpage_content_extractor = BatchWebpageContentExtractor()
|
353 |
+
self.web_search_client = WEBS(proxy=proxy)
|
354 |
+
self.google_search_result_num = google_search_result_num
|
355 |
+
self.duckduckgo_search_result_num = duckduckgo_search_result_num
|
356 |
+
self.max_google_content_tokens = max_google_content_tokens
|
357 |
+
self.encoding = get_encoding("cl100k_base") # Use tiktoken for tokenization
|
358 |
+
|
359 |
+
# Detailed system prompt for the first DeepInfra AI model (WizardLM)
|
360 |
+
self.system_prompt_1 = """You are a highly advanced AI assistant, designed to be exceptionally helpful and informative. Your primary function is to provide comprehensive, accurate, and insightful answers to user queries, even if they are complex or open-ended.
|
361 |
+
|
362 |
+
You have access to powerful tools:
|
363 |
+
- **Google Search Results:** These provide detailed content extracted from relevant web pages.
|
364 |
+
- **DuckDuckGo Search Summaries:** These offer additional perspectives and quick summaries of findings from another search engine.
|
365 |
+
|
366 |
+
Your top priorities are:
|
367 |
+
1. **Accuracy:** Ensure your responses are factually correct and grounded in the provided source material. Verify information whenever possible.
|
368 |
+
2. **Relevance:** Focus on directly addressing the user's question. Don't stray into irrelevant tangents.
|
369 |
+
3. **Clarity:** Present information in a clear, organized, and easy-to-understand manner. Use bullet points, numbered lists, or concise paragraphs to structure your response.
|
370 |
+
4. **Source Citation:** Whenever you use information from the web search results, clearly cite your source using the webpage title and URL. This helps the user understand where the information is coming from.
|
371 |
+
|
372 |
+
Here's a detailed breakdown of how to use the search results effectively:
|
373 |
+
- **Google (Extracted Content):** Treat this as your primary source. Analyze the content thoroughly to find the most relevant information. Don't hesitate to quote directly from the source when appropriate.
|
374 |
+
- **DuckDuckGo (Summaries):** Use these to broaden your understanding and potentially find additional perspectives. The summaries provide a quick overview of the top results, which can be helpful for identifying key themes or different angles on the topic.
|
375 |
+
|
376 |
+
Additional Guidelines:
|
377 |
+
- **Vague Queries:** If the user's query is unclear or lacks specifics, politely ask clarifying questions to better understand their needs.
|
378 |
+
- **Information Gaps:** If you can't find a satisfactory answer in the provided search results, acknowledge this honestly. Let the user know that you need more information to help them or that the specific answer is not available in the current search results.
|
379 |
+
- **Neutrality:** Maintain a neutral tone and avoid expressing personal opinions, beliefs, or emotions.
|
380 |
+
- **No Self-Promotion:** Do not refer to yourself as an AI or a language model. Focus on providing helpful information to the user.
|
381 |
+
|
382 |
+
Remember, your ultimate goal is to be a reliable and helpful assistant to the user. Use your knowledge and the provided search results to their fullest potential to achieve this goal."""
|
383 |
+
|
384 |
+
self.ai_client_1 = DeepInfra(
|
385 |
+
model=ai_model_1,
|
386 |
+
system_prompt=self.system_prompt_1,
|
387 |
+
max_tokens=ai_max_tokens,
|
388 |
+
is_conversation=False, # Disable conversation history
|
389 |
+
timeout=100 # Set timeout to 100 seconds
|
390 |
+
)
|
391 |
+
|
392 |
+
# System prompt for the second AI (Qwen) for professional summarization
|
393 |
+
self.system_prompt_2 = """You are a highly skilled AI assistant, specifically designed to condense and refine information into professional summaries. Your primary function is to transform the detailed responses of another AI model into clear, concise, and easily digestible reports.
|
394 |
+
|
395 |
+
Your objective is to craft summaries that are:
|
396 |
+
- **Accurate:** Faithfully represent the key points and findings of the original AI response without introducing any new information or interpretations.
|
397 |
+
- **Concise:** Distill the information into its most essential elements, eliminating unnecessary details or redundancy. Aim for brevity without sacrificing clarity.
|
398 |
+
- **Informative:** Ensure the summary provides a comprehensive overview of the main points, insights, and relevant sources.
|
399 |
+
- **Professional:** Use a formal and objective tone. Avoid casual language, personal opinions, or subjective statements.
|
400 |
+
|
401 |
+
Here's a breakdown of the key elements to include in your summaries:
|
402 |
+
- **Main Points:** Identify and succinctly state the most important arguments, conclusions, or findings presented in the AI's response.
|
403 |
+
- **Key Insights:** Highlight any particularly insightful observations, trends, or analyses that emerge from the AI's response.
|
404 |
+
- **Source Attribution:** If the original AI cited any sources (web pages, articles, etc.), list them clearly in your summary, using proper citation format (e.g., title and URL).
|
405 |
+
|
406 |
+
Formatting Guidelines:
|
407 |
+
- **Structure:** Organize your summary using bullet points or a numbered list for maximum clarity and readability.
|
408 |
+
- **Length:** Keep your summaries concise, aiming for a length that is significantly shorter than the original AI response.
|
409 |
+
|
410 |
+
Remember, your role is to provide a refined and professional distillation of the AI's output, making it readily accessible and understandable for a professional audience."""
|
411 |
+
|
412 |
+
self.ai_client_2 = DeepInfra(
|
413 |
+
model=ai_model_2,
|
414 |
+
system_prompt=self.system_prompt_2,
|
415 |
+
max_tokens=ai_max_tokens,
|
416 |
+
is_conversation=False,
|
417 |
+
timeout=100
|
418 |
+
)
|
419 |
+
|
420 |
+
def search_google(self, query: str) -> dict:
|
421 |
+
"""Search Google and extract results."""
|
422 |
+
self.console.print(f"[bold blue]Searching Google for:[/] {query}")
|
423 |
+
html_path = self.google_searcher.search(query, result_num=self.google_search_result_num)
|
424 |
+
search_results = self.query_results_extractor.extract(html_path)
|
425 |
+
self.console.print(f"[bold blue]Extracted {len(search_results['query_results'])} Google results.[/]")
|
426 |
+
return search_results
|
427 |
+
|
428 |
+
def search_duckduckgo(self, query: str) -> list[dict]:
|
429 |
+
"""Search DuckDuckGo and extract results."""
|
430 |
+
self.console.print(f"[bold blue]Searching DuckDuckGo for:[/] {query}")
|
431 |
+
search_results = self.web_search_client.text(keywords=query, max_results=self.duckduckgo_search_result_num)
|
432 |
+
self.console.print(f"[bold blue]Extracted {len(search_results)} DuckDuckGo results.[/]")
|
433 |
+
return search_results
|
434 |
+
|
435 |
+
def fetch_and_extract_content(self, google_results: list[dict]) -> list[dict]:
|
436 |
+
"""Fetch and extract content from Google search result URLs only, with truncation."""
|
437 |
+
urls = [result['url'] for result in google_results]
|
438 |
+
|
439 |
+
self.console.print(f"[bold blue]Fetching {len(urls)} webpages...[/]")
|
440 |
+
url_and_html_path_list = self.batch_webpage_fetcher.fetch(urls)
|
441 |
+
html_paths = [item['html_path'] for item in url_and_html_path_list]
|
442 |
+
self.console.print(f"[bold blue]Extracting content from {len(html_paths)} webpages...[/]")
|
443 |
+
html_path_and_content_list = self.batch_webpage_content_extractor.extract(html_paths)
|
444 |
+
|
445 |
+
# Truncate the combined content to the maximum token limit
|
446 |
+
combined_content = ""
|
447 |
+
current_token_count = 0
|
448 |
+
for item in html_path_and_content_list:
|
449 |
+
content = item['extracted_content']
|
450 |
+
token_count = len(self.encoding.encode(content))
|
451 |
+
if current_token_count + token_count <= self.max_google_content_tokens:
|
452 |
+
combined_content += content + "\n\n"
|
453 |
+
current_token_count += token_count
|
454 |
+
else:
|
455 |
+
# Truncate the current content to fit within the limit
|
456 |
+
remaining_tokens = self.max_google_content_tokens - current_token_count
|
457 |
+
truncated_content = self.encoding.decode(self.encoding.encode(content)[:remaining_tokens])
|
458 |
+
combined_content += truncated_content
|
459 |
+
break
|
460 |
+
|
461 |
+
# Update the content in the list with the truncated combined content
|
462 |
+
html_path_and_content_list = [{'html_path': '', 'extracted_content': combined_content}]
|
463 |
+
|
464 |
+
return html_path_and_content_list
|
465 |
+
|
466 |
+
def ask_ai_1(self, query: str, web_content: str, duckduckgo_results: list[dict]) -> str:
|
467 |
+
"""Ask the first AI model (WizardLM) a question."""
|
468 |
+
self.console.print(f"[bold blue]Asking AI 1:[/] {query}")
|
469 |
+
|
470 |
+
duckduckgo_summary = "\n\n".join([
|
471 |
+
f"**{result['title']}** ({result['href']})\n{result['body']}"
|
472 |
+
for result in duckduckgo_results
|
473 |
+
])
|
474 |
+
|
475 |
+
prompt = (
|
476 |
+
f"Based on the following Google search results (with extracted content):\n\n"
|
477 |
+
f"{web_content}\n\n"
|
478 |
+
f"And the following DuckDuckGo search summaries:\n\n"
|
479 |
+
f"{duckduckgo_summary}\n\n"
|
480 |
+
f"Answer the following question: {query}"
|
481 |
+
)
|
482 |
+
|
483 |
+
ai_response = self.ai_client_1.chat(prompt)
|
484 |
+
# self.console.print(f"[bold blue]AI 1 Response:[/]\n{ai_response}")
|
485 |
+
return ai_response
|
486 |
+
|
487 |
+
def ask_ai_2(self, ai_1_response: str) -> str:
|
488 |
+
"""Ask the second AI model (Qwen) to summarize the first AI's response."""
|
489 |
+
self.console.print(f"[bold blue]Asking AI 2 to summarize AI 1's response...[/]")
|
490 |
+
prompt = f"Please summarize the following text in a professional format:\n\n{ai_1_response}"
|
491 |
+
ai_response = self.ai_client_2.chat(prompt)
|
492 |
+
# self.console.print(f"[bold blue]AI 2 Summary:[/]\n{ai_response}")
|
493 |
+
return ai_response
|
494 |
+
|
495 |
+
def run(self, query: str):
|
496 |
+
"""Run the AI search engine."""
|
497 |
+
google_results = self.search_google(query)['query_results']
|
498 |
+
duckduckgo_results = self.search_duckduckgo(query)
|
499 |
+
html_path_and_content_list = self.fetch_and_extract_content(google_results)
|
500 |
+
web_content = "\n\n".join([item['extracted_content'] for item in html_path_and_content_list])
|
501 |
+
|
502 |
+
# Get response from the first AI
|
503 |
+
ai_1_response = self.ask_ai_1(query, web_content, duckduckgo_results)
|
504 |
+
|
505 |
+
# Summarize the first AI's response using the second AI
|
506 |
+
ai_2_summary = self.ask_ai_2(ai_1_response)
|
507 |
+
self.console.print("[bold green]Full Response[/]:", end="")
|
508 |
+
self.console.print(Markdown(ai_1_response))
|
509 |
+
|
510 |
+
self.console.print("[bold red]Summary[/]:", end="")
|
511 |
+
self.console.print(Markdown(ai_2_summary))
|
512 |
+
|
513 |
+
# Initialize the AI search engine outside of the endpoint
|
514 |
+
ai_search_engine = AISearchEngine()
|
515 |
+
|
516 |
+
@app.post("/api/ai-search")
|
517 |
+
async def ai_search(query: str):
|
518 |
+
"""
|
519 |
+
Performs an AI-powered search using Google, DuckDuckGo, and two large language models.
|
520 |
+
"""
|
521 |
+
try:
|
522 |
+
ai_search_engine.run(query)
|
523 |
+
return {"message": "AI search completed. Check your console for the results."}
|
524 |
+
except Exception as e:
|
525 |
+
raise HTTPException(status_code=500, detail=f"Error during AI search: {e}")
|
526 |
+
|
527 |
# Run the API server if this script is executed
|
528 |
if __name__ == "__main__":
|
529 |
import uvicorn
|