Last active
August 27, 2024 16:04
-
-
Save geobabbler/0c8a043ccd0dc0a3af80db67214ffbe9 to your computer and use it in GitHub Desktop.
Simple RAG is ChatGPT and DuckDuckGo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import openai | |
import urllib | |
import json | |
from duckduckgo_search import DDGS | |
# Set your OpenAI API key here | |
openai.api_key = "your-openai-api-key" | |
def search_duckduckgo(query): | |
""" | |
Perform a search query using DuckDuckGo and return the search results. | |
""" | |
retval = [] | |
try: | |
res = DDGS().text(query, max_results=5) | |
body_values = [obj['body'] for obj in res] | |
return body_values | |
except Exception as ex: | |
#print(ex) | |
retval = [] | |
return retval | |
def generate_response_with_rag(question, retrieved_texts): | |
""" | |
Generate a response using ChatGPT, incorporating retrieved texts. | |
""" | |
prompt = ( | |
f"You are an AI assistant. Below is a question and some relevant information retrieved from the web.\n\n" | |
f"Question: {question}\n\n" | |
"Retrieved Information:\n" | |
f"{' '.join(retrieved_texts)}\n\n" | |
"Using the information above, provide a response to the question of less than 200 words." | |
) | |
response = openai.chat.completions.create( | |
model="gpt-4o-mini", | |
messages=[{"role": "user", "content": f"{prompt}"}] | |
) | |
return response.choices[0].message.content | |
def main(): | |
# User input: the question they want answered | |
question = input("Enter your question: ") | |
# Step 1: Retrieve information using DuckDuckGo | |
retrieved_texts = search_duckduckgo(question) | |
if not retrieved_texts: | |
print("No relevant information found.") | |
retrieved_texts = [] | |
#return | |
# Step 2: Generate a response using the retrieved information and ChatGPT | |
response = generate_response_with_rag(question, retrieved_texts) | |
# Output the response | |
print("\nGenerated Response:\n") | |
print(response) | |
# Step 3: Generate a response without the retrieved information and ChatGPT | |
response = generate_response_with_rag(question, []) | |
# Output the response | |
print("\nGenerated Response:\n") | |
print(response) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment