Update app.py
Browse files
app.py
CHANGED
|
@@ -3,16 +3,17 @@ import requests
|
|
| 3 |
import os
|
| 4 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 5 |
|
| 6 |
-
|
|
|
|
| 7 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 8 |
-
model = AutoModelForCausalLM.from_pretrained(model_id
|
| 9 |
llm = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 10 |
|
| 11 |
-
|
| 12 |
# --- SAP Sales Order Header tool ---
|
| 13 |
-
def
|
|
|
|
| 14 |
api_url = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_SALES_ORDER_SRV/A_SalesOrder?$top=5&$inlinecount=allpages"
|
| 15 |
-
api_key = os.getenv("SAP_SANDBOX_API_KEY", "YOUR_API_KEY")
|
| 16 |
headers = {
|
| 17 |
"APIKey": api_key,
|
| 18 |
"Accept": "application/json"
|
|
@@ -23,45 +24,60 @@ def query_sales_order_header():
|
|
| 23 |
data = r.json()
|
| 24 |
results = data.get('d', {}).get('results', [])
|
| 25 |
if not results:
|
| 26 |
-
return
|
| 27 |
-
|
| 28 |
-
for order in results:
|
| 29 |
-
summaries.append(
|
| 30 |
-
f"Order: {order['SalesOrder']} | "
|
| 31 |
-
f"Type: {order['SalesOrderType']} | "
|
| 32 |
-
f"Org: {order['SalesOrganization']} | "
|
| 33 |
-
f"Date: {order['SalesOrderDate']} | "
|
| 34 |
-
f"SoldTo: {order['SoldToParty']} | "
|
| 35 |
-
f"Net: {order['TotalNetAmount']} {order['TransactionCurrency']} | "
|
| 36 |
-
f"Status: {order['OverallSDProcessStatus']}"
|
| 37 |
-
)
|
| 38 |
-
return "\n".join(summaries)
|
| 39 |
except Exception as e:
|
| 40 |
return f"Error fetching Sales Orders: {e}"
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
def chat_agent(message, history):
|
| 44 |
-
#
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
history = history or []
|
| 53 |
history.append((message, response))
|
| 54 |
return history, history
|
| 55 |
|
| 56 |
-
#
|
| 57 |
with gr.Blocks() as demo:
|
| 58 |
gr.Markdown(
|
| 59 |
"""
|
| 60 |
-
# SAP Sales Order Chat Agent
|
| 61 |
-
Ask about SAP sales orders
|
| 62 |
-
Example:
|
| 63 |
-
- `Show me the latest SAP sales orders.`
|
| 64 |
-
- `Tell me about SAP order values.`
|
|
|
|
|
|
|
|
|
|
| 65 |
"""
|
| 66 |
)
|
| 67 |
chatbot = gr.Chatbot()
|
|
|
|
| 3 |
import os
|
| 4 |
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 5 |
|
| 6 |
+
# ---- Hugging Face model: use a public chat/instruct model ----
|
| 7 |
+
model_id = "HuggingFaceH4/zephyr-7b-beta" # You can use another public instruct/chat model if you prefer
|
| 8 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 9 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 10 |
llm = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 11 |
|
|
|
|
| 12 |
# --- SAP Sales Order Header tool ---
|
| 13 |
+
def fetch_sales_order_headers():
|
| 14 |
+
"""Fetches the top 5 SAP sales orders from the sandbox API and returns as a list of dicts."""
|
| 15 |
api_url = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_SALES_ORDER_SRV/A_SalesOrder?$top=5&$inlinecount=allpages"
|
| 16 |
+
api_key = os.getenv("SAP_SANDBOX_API_KEY", "YOUR_API_KEY") # Set in Space secrets!
|
| 17 |
headers = {
|
| 18 |
"APIKey": api_key,
|
| 19 |
"Accept": "application/json"
|
|
|
|
| 24 |
data = r.json()
|
| 25 |
results = data.get('d', {}).get('results', [])
|
| 26 |
if not results:
|
| 27 |
+
return []
|
| 28 |
+
return results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
except Exception as e:
|
| 30 |
return f"Error fetching Sales Orders: {e}"
|
| 31 |
|
| 32 |
+
def format_sales_orders_for_llm(orders):
|
| 33 |
+
"""Converts the SAP sales order list to readable context for the LLM."""
|
| 34 |
+
if isinstance(orders, str):
|
| 35 |
+
return orders # Pass through error message
|
| 36 |
+
context = "Here are the latest SAP sales orders:\n"
|
| 37 |
+
for i, order in enumerate(orders, 1):
|
| 38 |
+
context += (
|
| 39 |
+
f"{i}. Order: {order['SalesOrder']}, "
|
| 40 |
+
f"Type: {order['SalesOrderType']}, "
|
| 41 |
+
f"Org: {order['SalesOrganization']}, "
|
| 42 |
+
f"Date: {order['SalesOrderDate']}, "
|
| 43 |
+
f"SoldTo: {order['SoldToParty']}, "
|
| 44 |
+
f"Net: {order['TotalNetAmount']} {order['TransactionCurrency']}, "
|
| 45 |
+
f"Status: {order['OverallSDProcessStatus']}\n"
|
| 46 |
+
)
|
| 47 |
+
return context
|
| 48 |
+
|
| 49 |
def chat_agent(message, history):
|
| 50 |
+
# Step 1: Fetch SAP data every time
|
| 51 |
+
sales_orders = fetch_sales_order_headers()
|
| 52 |
+
context = format_sales_orders_for_llm(sales_orders)
|
| 53 |
+
# Step 2: Prompt LLM with both the question and the context
|
| 54 |
+
prompt = (
|
| 55 |
+
f"{context}\n"
|
| 56 |
+
f"User asked: {message}\n"
|
| 57 |
+
"Based on the above SAP sales orders, answer the user's question as accurately as possible. "
|
| 58 |
+
"If the question asks for sorting, filtering, maximum values, customer-specific info, or other details, do it based on the orders above. "
|
| 59 |
+
"If the question is unclear, summarize the available sales orders."
|
| 60 |
+
)
|
| 61 |
+
# Step 3: Generate LLM answer
|
| 62 |
+
llm_output = llm(prompt, max_new_tokens=256)[0]["generated_text"]
|
| 63 |
+
# Remove the prompt from the response if present
|
| 64 |
+
response = llm_output.replace(prompt, "").strip()
|
| 65 |
history = history or []
|
| 66 |
history.append((message, response))
|
| 67 |
return history, history
|
| 68 |
|
| 69 |
+
# ---- Gradio UI ----
|
| 70 |
with gr.Blocks() as demo:
|
| 71 |
gr.Markdown(
|
| 72 |
"""
|
| 73 |
+
# SAP Sales Order Chat Agent (Smart Reasoning)
|
| 74 |
+
Ask about SAP sales orders, values, filtering, sorting, etc.
|
| 75 |
+
Example questions:
|
| 76 |
+
- `Show me the latest SAP sales orders.`
|
| 77 |
+
- `Tell me about SAP order values.`
|
| 78 |
+
- `Show me top 2 sales orders with maximum value.`
|
| 79 |
+
- `Which order has the highest net value?`
|
| 80 |
+
- `List orders by customer.`
|
| 81 |
"""
|
| 82 |
)
|
| 83 |
chatbot = gr.Chatbot()
|