raghavNCI commited on
Commit
8e9fd43
·
1 Parent(s): 28e882c

first version of ask

Browse files
Files changed (2) hide show
  1. question.py +56 -0
  2. requirements.txt +3 -1
question.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/routes/question.py
2
+ import os
3
+ import requests
4
+ from fastapi import APIRouter, Query
5
+ from pydantic import BaseModel
6
+ from typing import List
7
+ from redis_client import redis_client as r
8
+ from transformers import pipeline
9
+ import re
10
+ from dotenv import load_dotenv
11
+
12
+ load_dotenv()
13
+
14
+ GNEWS_API_KEY = os.getenv("GNEWS_API_KEY")
15
+
16
+ router = APIRouter()
17
+
18
+ qa_model = pipeline("text2text-generation", model="google/flan-t5-base") # replace with your preferred model
19
+
20
+ class QuestionInput(BaseModel):
21
+ question: str
22
+
23
+ @router.post("/ask")
24
+ async def ask_question(input: QuestionInput):
25
+ question = input.question
26
+
27
+ # Extract keywords (simple version)
28
+ keywords = re.findall(r"\b\w{4,}\b", question)
29
+ query_string = "+".join(keywords[:5]) # Limit to top 5 keywords
30
+
31
+ gnews_url = f"https://gnews.io/api/v4/search?q={query_string}&lang=en&max=3&expand=content&token={GNEWS_API_KEY}"
32
+ try:
33
+ response = requests.get(gnews_url, timeout=10)
34
+ response.raise_for_status()
35
+ articles = response.json().get("articles", [])
36
+ except Exception as e:
37
+ return {"error": f"GNews API error: {str(e)}"}
38
+
39
+ # Combine article content for context
40
+ context = "\n\n".join([
41
+ article.get("content") or article.get("description") or ""
42
+ for article in articles
43
+ ])
44
+
45
+ # Build prompt
46
+ prompt = f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
47
+ result = qa_model(prompt, max_length=256, do_sample=False)[0]['generated_text']
48
+
49
+ return {
50
+ "question": question,
51
+ "answer": result.strip(),
52
+ "sources": [
53
+ {"title": a["title"], "url": a["url"]}
54
+ for a in articles
55
+ ]
56
+ }
requirements.txt CHANGED
@@ -2,4 +2,6 @@ fastapi
2
  uvicorn[standard]
3
  requests
4
  python-dotenv
5
- redis
 
 
 
2
  uvicorn[standard]
3
  requests
4
  python-dotenv
5
+ redis
6
+ transformers
7
+ torch