Spaces:
Sleeping
Sleeping
Update text2generation.py
Browse files- text2generation.py +33 -19
text2generation.py
CHANGED
|
@@ -3,23 +3,37 @@ import asyncio
|
|
| 3 |
import httpx
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
|
| 6 |
-
load_dotenv()
|
| 7 |
|
| 8 |
-
async def generate_long_answer(question):
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import httpx
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
|
| 6 |
+
load_dotenv() # Load .env file if you use one
|
| 7 |
|
| 8 |
+
async def generate_long_answer(question: str) -> str:
|
| 9 |
+
headers = {
|
| 10 |
+
"Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
|
| 11 |
+
"Content-Type": "application/json",
|
| 12 |
+
"HTTP-Referer": "https://sreepathi-ravikumar-sample.hf.space", # or your real referrer
|
| 13 |
+
"X-Title": "Educational AI Assistant"
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
payload = {
|
| 17 |
+
"model": "deepseek/deepseek-chat-v3-0324:free",
|
| 18 |
+
"messages": [{
|
| 19 |
+
"role": "user",
|
| 20 |
+
"content": f"Provide a comprehensive educational answer:\n\n{question}"
|
| 21 |
+
}],
|
| 22 |
+
"temperature": 0.3,
|
| 23 |
+
"max_tokens": 700
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
async with httpx.AsyncClient(timeout=30.0, http2=True) as client:
|
| 28 |
+
response = await client.post(
|
| 29 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
| 30 |
+
headers=headers,
|
| 31 |
+
json=payload
|
| 32 |
+
)
|
| 33 |
+
response.raise_for_status()
|
| 34 |
+
return response.json()["choices"][0]["message"]["content"]
|
| 35 |
+
|
| 36 |
+
except httpx.HTTPStatusError as http_err:
|
| 37 |
+
return f"HTTP error: {http_err.response.status_code} - {http_err.response.text}"
|
| 38 |
+
except Exception as e:
|
| 39 |
+
return f"Error generating answer: {str(e)}"
|