Spaces:
Sleeping
Sleeping
Update src/llm_client.py
Browse files- src/llm_client.py +33 -0
src/llm_client.py
CHANGED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
def ask_granite(query, context):
|
| 5 |
+
"""
|
| 6 |
+
Connects to the NavyDevilDoc/private-granite Space.
|
| 7 |
+
"""
|
| 8 |
+
hf_token = os.environ.get("HF_TOKEN")
|
| 9 |
+
if not hf_token:
|
| 10 |
+
return "Error: HF_TOKEN is missing."
|
| 11 |
+
|
| 12 |
+
api_url = "https://navydevildoc-private-granite.hf.space/generate"
|
| 13 |
+
|
| 14 |
+
payload = {
|
| 15 |
+
"text": f"USER QUESTION: {query}\n\nDOCUMENT CONTEXT:\n{context[:6000]}",
|
| 16 |
+
"persona": "You are a question answering Subject Matter Expert. Answer strictly based on the provided context.",
|
| 17 |
+
"model": "granite4:latest", # Or gemma3:latest
|
| 18 |
+
"max_tokens": 5000
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
headers = {
|
| 22 |
+
"Authorization": f"Bearer {hf_token}",
|
| 23 |
+
"Content-Type": "application/json"
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
response = requests.post(api_url, json=payload, headers=headers, timeout=120)
|
| 28 |
+
if response.status_code == 200:
|
| 29 |
+
return response.json().get("response", "Error: Empty response.")
|
| 30 |
+
else:
|
| 31 |
+
return f"Error {response.status_code}: {response.text}"
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return f"Connection Error: {str(e)}"
|