AightBits

DeepSeek-R1 RAG Example

Feb 10th, 2025
585
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.55 KB | Source Code | 0 0
  1. import requests
  2. import json
  3. import re
  4. import time
  5. import urllib.parse
  6. from duckduckgo_search import DDGS
  7.  
  8. # Function to perform DuckDuckGo search using the duckduckgo_search library
  9. def duckduckgo_search(query, num_results=3):
  10.     try:
  11.         ddgs = DDGS()
  12.         results = ddgs.text(query, max_results=num_results)
  13.  
  14.         search_results = []
  15.         for result in results:
  16.             title = result.get('title', 'No title')
  17.             link = result.get('href', 'No link')
  18.             snippet = result.get('body', 'No snippet')
  19.             search_results.append({"title": title, "link": link, "snippet": snippet})
  20.  
  21.         return search_results
  22.     except Exception as e:
  23.         print(f"Error fetching DuckDuckGo search results: {e}")
  24.         return []
  25.  
  26. # Function to communicate with DeepSeek-R1 model
  27. def query_llm(prompt):
  28.     url = "http://localhost:5000/v1/chat/completions"
  29.     headers = {
  30.         "Content-Type": "application/json",
  31.         "Authorization": "Bearer YOUR_API_KEY"  # Replace with API key if needed
  32.     }
  33.  
  34.     payload = {
  35.         "model": "deepseek-reasoner",
  36.         "messages": [{"role": "system", "content": "<think>\n"}, {"role": "user", "content": prompt}],
  37.         "temperature": 0.6,
  38.         "top_p": 0.95,
  39.         "max_tokens": 2000
  40.     }
  41.  
  42.     response = requests.post(url, headers=headers, json=payload)
  43.     if response.status_code == 200:
  44.         return response.json()
  45.     else:
  46.         print(f"Error: API call failed with status code {response.status_code}")
  47.         return None
  48.  
  49. # Extract relevant response from LLM output
  50. def parse_llm_response(response_text):
  51.     """Extracts CoT (<think> tags) and final answer separately."""
  52.     start_index = response_text.find("<think>")
  53.     end_index = response_text.find("</think>", start_index + len("<think>")) if start_index != -1 else -1
  54.  
  55.     if start_index != -1 and end_index != -1:
  56.         cot_block = response_text[start_index + len("<think>"): end_index].strip()
  57.         answer_part = response_text[end_index + len("</think>"):].strip()
  58.         return cot_block, answer_part
  59.     else:
  60.         return "", response_text.strip()
  61.  
  62. def main():
  63.     # 1. Get the user's input
  64.     user_prompt = input("Enter your prompt: ")
  65.  
  66.     # **PASS 1: Generate proper search queries**
  67.     print("\n[PASS 1] Generating search queries...\n")
  68.    
  69.     search_prompt = f"""
  70.    Given the user's question below, generate **exactly 3** precise DuckDuckGo search queries that retrieve **real-time** information.
  71.    **Do NOT attempt to answer the question directly.** Just provide search queries.
  72.  
  73.    User Question: {user_prompt}
  74.  
  75.    Output format:
  76.    - <search query 1>
  77.    - <search query 2>
  78.    - <search query 3>
  79.    """
  80.    
  81.     llm_response_1 = query_llm(search_prompt)
  82.     if not llm_response_1:
  83.         return
  84.    
  85.     generated_text_1 = llm_response_1.get("choices", [{}])[0].get("message", {}).get("content", "")
  86.     cot_block_1, search_queries = parse_llm_response(generated_text_1)
  87.  
  88.     # Extract clean search queries
  89.     search_queries_list = [q.strip("- ").replace('"', '') for q in search_queries.split("\n") if q.strip()]
  90.     print(f"\nIdentified search queries:\n{search_queries_list}")
  91.  
  92.     retrieved_search_results = []
  93.     source_links = []
  94.  
  95.     # **Perform DuckDuckGo searches and extract search result summaries**
  96.     for query in search_queries_list:
  97.         print(f"\nSearching DuckDuckGo for: {query}...")
  98.         search_results = duckduckgo_search(query, num_results=3)
  99.  
  100.         if search_results:
  101.             retrieved_search_results.extend(search_results)
  102.             source_links.extend([r["link"] for r in search_results])
  103.         else:
  104.             print(f"No results found for query: {query}")
  105.  
  106.     # **PASS 2: Pass retrieved search results + user query**
  107.     print("\n[PASS 2] Processing final response...\n")
  108.  
  109.     if retrieved_search_results:
  110.         search_results_text = "\n\n".join([f"{r['title']} - {r['link']}\nSnippet: {r['snippet']}" for r in retrieved_search_results])
  111.         final_prompt = f"""
  112.        Use the following **real-time** DuckDuckGo search results to **accurately answer** the user's question.
  113.  
  114.        ### Search Results:
  115.        {search_results_text}
  116.  
  117.        ### User Query:
  118.        {user_prompt}
  119.  
  120.        Provide a well-reasoned response based on these search results.
  121.        """
  122.     else:
  123.         final_prompt = f"""
  124.        No relevant search results were found.
  125.  
  126.        ### User Query:
  127.        {user_prompt}
  128.  
  129.        Provide an informative answer based on prior knowledge instead.
  130.        """
  131.  
  132.     llm_response_2 = query_llm(final_prompt)
  133.     if not llm_response_2:
  134.         return
  135.    
  136.     generated_text_2 = llm_response_2.get("choices", [{}])[0].get("message", {}).get("content", "")
  137.     cot_block_2, final_answer = parse_llm_response(generated_text_2)
  138.  
  139.     # **Display final answer including formatted prompt**
  140.     print("\n========================")
  141.     print("Final Prompt Sent to LLM:")
  142.     print("========================\n")
  143.     print(final_prompt)
  144.  
  145.     print("\n========================")
  146.     print("CoT Reasoning:")
  147.     print("========================\n")
  148.     print(cot_block_2)
  149.  
  150.     print("\n========================")
  151.     print("Final Answer:")
  152.     print("========================\n")
  153.     print(final_answer)
  154.  
  155.     # **Display source links**
  156.     if source_links:
  157.         print("\n========================")
  158.         print("Sources Used:")
  159.         print("========================")
  160.         for link in source_links:
  161.             print(link)
  162.  
  163. if __name__ == "__main__":
  164.     main()
Advertisement
Add Comment
Please, Sign In to add comment