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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
import requests
|
| 4 |
+
import os
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
# =========================
|
| 9 |
+
# ENV VARIABLES (use HF Secrets)
|
| 10 |
+
# =========================
|
| 11 |
+
client_id = "sb-cap1-3c4588e0trial-dev!t617058"
|
| 12 |
+
client_secret = "acbe78be-ead5-4b12-b3b4-32fdb27d0f5f$hFj-hDXxwHkNHC-CAvv-OKSr3KH96nLL4KqwIg7M8D8="
|
| 13 |
+
token_url = "https://3c4588e0trial.authentication.us10.hana.ondemand.com/oauth/token"
|
| 14 |
+
cap_service_url_customers = "https://3c4588e0trial-dev-cap1-srv.cfapps.us10-001.hana.ondemand.com/odata/v4/sales/Customers"
|
| 15 |
+
cap_service_url_products = "https://3c4588e0trial-dev-cap1-srv.cfapps.us10-001.hana.ondemand.com/odata/v4/sales/Products"
|
| 16 |
+
cap_service_url_saleorders = "https://3c4588e0trial-dev-cap1-srv.cfapps.us10-001.hana.ondemand.com/odata/v4/sales/SalesOrders"
|
| 17 |
+
cap_service_url_saleorderitems = "https://3c4588e0trial-dev-cap1-srv.cfapps.us10-001.hana.ondemand.com/odata/v4/sales/SalesOrderItems"
|
| 18 |
+
|
| 19 |
+
# =========================
|
| 20 |
+
# GLOBAL VARIABLES
|
| 21 |
+
# =========================
|
| 22 |
+
access_token = None
|
| 23 |
+
cached_customers = None
|
| 24 |
+
cached_products = None
|
| 25 |
+
cached_salesorders = None
|
| 26 |
+
cached_salesorderitems = None
|
| 27 |
+
last_refresh = 0
|
| 28 |
+
|
| 29 |
+
# =========================
|
| 30 |
+
# LOAD MODEL (once)
|
| 31 |
+
# =========================
|
| 32 |
+
print("Loading model...")
|
| 33 |
+
|
| 34 |
+
pipe = pipeline(
|
| 35 |
+
"text-generation",
|
| 36 |
+
model="Qwen/Qwen2.5-0.5B-Instruct",
|
| 37 |
+
device="cpu"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# =========================
|
| 41 |
+
# TOKEN FUNCTION
|
| 42 |
+
# =========================
|
| 43 |
+
def generate_sap_xsuaa_token():
|
| 44 |
+
global access_token
|
| 45 |
+
|
| 46 |
+
print("Generating SAP token...")
|
| 47 |
+
|
| 48 |
+
auth_response = requests.post(
|
| 49 |
+
token_url,
|
| 50 |
+
data={"grant_type": "client_credentials"},
|
| 51 |
+
auth=(client_id, client_secret)
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
if auth_response.status_code != 200:
|
| 55 |
+
print("Token Error:", auth_response.text)
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
access_token = auth_response.json().get("access_token")
|
| 59 |
+
print("Token generated!")
|
| 60 |
+
return access_token
|
| 61 |
+
|
| 62 |
+
# =========================
|
| 63 |
+
# FETCH SAP DATA
|
| 64 |
+
# =========================
|
| 65 |
+
def fetch_sap_data():
|
| 66 |
+
global access_token
|
| 67 |
+
|
| 68 |
+
if not access_token:
|
| 69 |
+
generate_sap_xsuaa_token()
|
| 70 |
+
|
| 71 |
+
headers = {
|
| 72 |
+
"Authorization": f"Bearer {access_token}",
|
| 73 |
+
"Accept": "application/json"
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
res1 = requests.get(cap_service_url_customers, headers=headers)
|
| 77 |
+
res2 = requests.get(cap_service_url_products, headers=headers)
|
| 78 |
+
res3 = requests.get(cap_service_url_saleorders, headers=headers)
|
| 79 |
+
res4 = requests.get(cap_service_url_saleorderitems, headers=headers)
|
| 80 |
+
|
| 81 |
+
# Retry if token expired
|
| 82 |
+
if res1.status_code in [400,401,403]:
|
| 83 |
+
print("Token expired. Regenerating...")
|
| 84 |
+
access_token = None
|
| 85 |
+
generate_sap_xsuaa_token()
|
| 86 |
+
|
| 87 |
+
headers["Authorization"] = f"Bearer {access_token}"
|
| 88 |
+
res1 = requests.get(cap_service_url_customers, headers=headers)
|
| 89 |
+
res2 = requests.get(cap_service_url_products, headers=headers)
|
| 90 |
+
res3 = requests.get(cap_service_url_saleorders, headers=headers)
|
| 91 |
+
res4 = requests.get(cap_service_url_saleorderitems, headers=headers)
|
| 92 |
+
|
| 93 |
+
df_customers = pd.DataFrame(res1.json()["value"])
|
| 94 |
+
df_products = pd.DataFrame(res2.json()["value"])
|
| 95 |
+
df_saleorders = pd.DataFrame(res3.json()["value"])
|
| 96 |
+
df_saleorderitems = pd.DataFrame(res4.json()["value"])
|
| 97 |
+
|
| 98 |
+
# Keep only important columns
|
| 99 |
+
df_customers = df_customers[["ID","name","country","industry"]]
|
| 100 |
+
df_products = df_products[["ID","name","category","price","currency"]]
|
| 101 |
+
df_saleorders = df_saleorders[["ID","customer_ID","orderDate","status"]]
|
| 102 |
+
df_saleorderitems = df_saleorderitems[["ID","parent_ID","product_ID","quantity","netAmount"]]
|
| 103 |
+
|
| 104 |
+
return df_customers, df_products, df_saleorders, df_saleorderitems
|
| 105 |
+
|
| 106 |
+
# =========================
|
| 107 |
+
# CACHE LOGIC
|
| 108 |
+
# =========================
|
| 109 |
+
|
| 110 |
+
def get_cached_data():
|
| 111 |
+
global cached_customers, cached_products,cached_salesorders,cached_salesorderitems, last_refresh
|
| 112 |
+
|
| 113 |
+
# Refresh every 5 minutes
|
| 114 |
+
if time.time() - last_refresh > 300 or cached_authors is None:
|
| 115 |
+
print("Refreshing SAP data...")
|
| 116 |
+
cached_customers, cached_products,cached_salesorders,cached_salesorderitems = fetch_sap_data()
|
| 117 |
+
last_refresh = time.time()
|
| 118 |
+
|
| 119 |
+
return cached_customers, cached_products,cached_salesorders,cached_salesorderitems
|
| 120 |
+
|
| 121 |
+
# =========================
|
| 122 |
+
# MAIN FUNCTION (LLM)
|
| 123 |
+
# =========================
|
| 124 |
+
# def generate_response(user_prompt, system_prompt):
|
| 125 |
+
def generate_response(user_prompt):
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
# Get cached SAP data
|
| 129 |
+
df_customers, df_products, df_saleorders, df_saleorderitems = get_cached_data()
|
| 130 |
+
|
| 131 |
+
# Reduce size (IMPORTANT)
|
| 132 |
+
customers_text = str(df_customers)[:500]
|
| 133 |
+
products_text = str(df_products)[:500]
|
| 134 |
+
saleorders_text = str(df_saleorders)[:500]
|
| 135 |
+
saleorderitems_text = str(df_saleorderitems)[:500]
|
| 136 |
+
|
| 137 |
+
# Build prompt
|
| 138 |
+
|
| 139 |
+
system_prompt = f"""
|
| 140 |
+
If you don't know the answer, say you don't know.
|
| 141 |
+
And do not give the books id, instead give the name of the author or title of the book.
|
| 142 |
+
You are an intelligent Corporate SAP Assistant bot running inside Microsoft Teams.
|
| 143 |
+
Your sole purpose is to answer the user's questions based strictly on the live database records provided to you.
|
| 144 |
+
Customers Data: {customers_text}
|
| 145 |
+
Products Data: {products_text}
|
| 146 |
+
Sale orders Data: {saleorders_text}
|
| 147 |
+
Sale order items Data: {saleorderitems_text}
|
| 148 |
+
|
| 149 |
+
CRITICAL RULES:
|
| 150 |
+
1. NO HALLUCINATIONS: You must base your answer ONLY on the data provided.
|
| 151 |
+
2. MISSING DATA: If the provided data does not contain the answer, do not guess. Say: "I could not find that information in the current SAP database."
|
| 152 |
+
3. FORMATTING: You must output your response in Markdown. Use bold text for important nouns and bullet points for lists to make it easy to read in Microsoft Teams.
|
| 153 |
+
4. TONE: Be concise, highly professional, and helpful. Do not include internal thought processes.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
prompt = f"""
|
| 157 |
+
{system_prompt}
|
| 158 |
+
User: {user_prompt}
|
| 159 |
+
Assistant:
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
# Generate response
|
| 163 |
+
result = pipe(
|
| 164 |
+
prompt,
|
| 165 |
+
min_new_tokens=1,
|
| 166 |
+
max_new_tokens=150,
|
| 167 |
+
# temperature=0.3, # Temperature controls randomness
|
| 168 |
+
do_sample=False, # controls HOW the next word is selected. If False then Always picks most probable next word and No randomness in answer. And if you use True then Picks from multiple possible words
|
| 169 |
+
# repetition_penalty=1.1,
|
| 170 |
+
return_full_text=False
|
| 171 |
+
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
generated_text = result[0]["generated_text"]
|
| 175 |
+
|
| 176 |
+
# Clean output
|
| 177 |
+
response = generated_text.replace(prompt, "").strip()
|
| 178 |
+
|
| 179 |
+
return response
|
| 180 |
+
|
| 181 |
+
except Exception as e:
|
| 182 |
+
return f"Error: {str(e)}"
|
| 183 |
+
|
| 184 |
+
# =========================
|
| 185 |
+
# GRADIO UI + API
|
| 186 |
+
# =========================
|
| 187 |
+
with gr.Blocks() as demo:
|
| 188 |
+
|
| 189 |
+
user_input = gr.Textbox(label="User Question")
|
| 190 |
+
|
| 191 |
+
# system_input = gr.Textbox(
|
| 192 |
+
# value="You are a helpful SAP assistant.",
|
| 193 |
+
# label="System Prompt"
|
| 194 |
+
# )
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
output = gr.Textbox(label="Response")
|
| 198 |
+
|
| 199 |
+
btn = gr.Button("Generate")
|
| 200 |
+
|
| 201 |
+
btn.click(
|
| 202 |
+
fn=generate_response,
|
| 203 |
+
# inputs=[user_input, system_input],
|
| 204 |
+
inputs=[user_input],
|
| 205 |
+
outputs=output,
|
| 206 |
+
api_name="predict"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
# REQUIRED for API exposure
|
| 210 |
+
demo.queue()
|
| 211 |
+
|
| 212 |
+
demo.launch()
|