Spaces:
Sleeping
Sleeping
Create rag.py
Browse files
rag.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from duckduckgo_search import DDGS
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 3 |
+
|
| 4 |
+
def search_web(query):
|
| 5 |
+
with DDGS() as ddgs:
|
| 6 |
+
results = ddgs.text(query, max_results=5)
|
| 7 |
+
return "\n".join([r["body"] for r in results])
|
| 8 |
+
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained("google/gemma-7b-it")
|
| 10 |
+
model = AutoModelForCausalLM.from_pretrained("google/gemma-7b-it")
|
| 11 |
+
|
| 12 |
+
def ask(question):
|
| 13 |
+
context = search_web(question)
|
| 14 |
+
prompt = f"Use this information:\n{context}\n\nQuestion: {question}\nAnswer:"
|
| 15 |
+
|
| 16 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 17 |
+
output = model.generate(**inputs, max_new_tokens=200)
|
| 18 |
+
return tokenizer.decode(output[0], skip_special_tokens=True)
|
| 19 |
+
|
| 20 |
+
if __name__ == "__main__":
|
| 21 |
+
print(ask("When was the Eiffel Tower built?"))
|
| 22 |
+
python rag.py
|