Spaces:
Sleeping
Sleeping
Update text2generation.py
Browse files- text2generation.py +23 -32
text2generation.py
CHANGED
|
@@ -1,39 +1,30 @@
|
|
| 1 |
import os
|
| 2 |
-
import asyncio
|
| 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 |
-
|
| 28 |
-
response =
|
| 29 |
-
"https://openrouter.ai/api/v1/chat/completions",
|
| 30 |
-
headers=
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
)
|
| 33 |
-
|
| 34 |
-
|
| 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)}"
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import httpx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
def generate_long_answer(question):
|
| 5 |
+
"""Generate detailed answers using OpenRouter's DeepSeek API"""
|
| 6 |
try:
|
| 7 |
+
with httpx.Client(timeout=10.0) as client:
|
| 8 |
+
response = client.post(
|
| 9 |
+
url="https://openrouter.ai/api/v1/chat/completions",
|
| 10 |
+
headers={
|
| 11 |
+
"Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
|
| 12 |
+
"Content-Type": "application/json",
|
| 13 |
+
"HTTP-Referer": "https://sreepathi-ravikumar-sample.hf.space",
|
| 14 |
+
"X-Title": "Educational AI Assistant"
|
| 15 |
+
},
|
| 16 |
+
json={
|
| 17 |
+
"model": "deepseek/deepseek-chat-v3-0324:free",
|
| 18 |
+
"messages": [{
|
| 19 |
+
"role": "user",
|
| 20 |
+
"content": f"Provide a comprehensive educational answer with examples:\n\n{question}"
|
| 21 |
+
}],
|
| 22 |
+
"temperature": 0.3,
|
| 23 |
+
"max_tokens": 2000
|
| 24 |
+
}
|
| 25 |
)
|
| 26 |
+
response.raise_for_status()
|
| 27 |
+
return response.json()['choices'][0]['message']['content']
|
| 28 |
|
|
|
|
|
|
|
| 29 |
except Exception as e:
|
| 30 |
+
return f"Error generating answer: {str(e)}"
|