PD03 commited on
Commit
f2283a2
·
verified ·
1 Parent(s): 8ca0d22

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -0
app.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import os
3
+ import json
4
+ import gradio as gr
5
+ import logging
6
+
7
+ # Setup logging
8
+ logging.basicConfig(level=logging.INFO)
9
+ logger = logging.getLogger(__name__)
10
+
11
+ # Hugging Face API setup
12
+ HF_API_TOKEN = os.getenv("HF_API_TOKEN")
13
+ HF_API_URL = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct"
14
+ hf_headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
15
+
16
+ # SAP configuration
17
+ SAP_API_KEY = os.getenv('SAP_API_KEY')
18
+ SAP_BASE_URL = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap"
19
+ sap_headers = {
20
+ "APIKey": SAP_API_KEY,
21
+ "Accept": "application/json"
22
+ }
23
+
24
+ def fetch_sales_orders(top=20):
25
+ url = f"{SAP_BASE_URL}/API_SALES_ORDER_SRV/A_SalesOrder?$top={top}"
26
+ response = requests.get(url, headers=sap_headers)
27
+ return response.json().get('d', {}).get('results', [])
28
+
29
+ def fetch_purchase_orders(top=20):
30
+ url = f"{SAP_BASE_URL}/API_PURCHASEORDER_PROCESS_SRV/A_PurchaseOrder?$top={top}"
31
+ response = requests.get(url, headers=sap_headers)
32
+ return response.json().get('d', {}).get('results', [])
33
+
34
+ def generate_response(question, context, data_type):
35
+ context_str = json.dumps(context, indent=2)
36
+ if len(context_str) > 4000: # Limit context size
37
+ context_str = context_str[:4000] + "... (truncated)"
38
+
39
+ prompt = f"""
40
+ You are a helpful SAP data analyst. Answer the user's question based on the provided data.
41
+
42
+ Data Type: {data_type}
43
+
44
+ Available Data:
45
+ {context_str}
46
+
47
+ User Question: {question}
48
+
49
+ Instructions:
50
+ 1. Provide a clear, concise answer based on the data.
51
+ 2. Include specific numbers, dates, or values when relevant.
52
+ 3. If the data doesn't contain enough information, mention this.
53
+ 4. Format your response clearly and concisely.
54
+
55
+ Answer:
56
+ """
57
+
58
+ payload = {"inputs": prompt, "parameters": {"max_new_tokens": 500, "temperature": 0.1}}
59
+ response = requests.post(HF_API_URL, headers=hf_headers, json=payload)
60
+
61
+ if response.status_code == 200:
62
+ output = response.json()
63
+ generated_text = output[0]['generated_text']
64
+ return generated_text.replace(prompt, "").strip()
65
+ else:
66
+ logger.error(f"Hugging Face API Error: {response.status_code}, {response.text}")
67
+ return "Error generating response from Hugging Face."
68
+
69
+ def chat_with_sap(question, history):
70
+ sales_orders = fetch_sales_orders()
71
+ purchase_orders = fetch_purchase_orders()
72
+
73
+ context = {"sales_orders": sales_orders, "purchase_orders": purchase_orders}
74
+ data_type = "Sales and Purchase Orders"
75
+
76
+ response = generate_response(question, context, data_type)
77
+ history.append((question, response))
78
+ return history
79
+
80
+ # Gradio UI
81
+ with gr.Blocks(title="SAP Order Analytics with LLAMA-3") as demo:
82
+ gr.Markdown("""
83
+ # 🚀 SAP Order Analytics Agent (LLAMA-3)
84
+
85
+ This agent analyzes SAP Sales and Purchase Orders. Example queries:
86
+ - "List recent sales orders"
87
+ - "Total net amount of purchase orders"
88
+ - "Sales orders for a specific customer"
89
+ """)
90
+
91
+ chatbot = gr.Chatbot(height=500)
92
+ msg = gr.Textbox(label="Your Question", placeholder="Ask your SAP query here...")
93
+ submit_btn = gr.Button("Send", variant="primary")
94
+ clear_btn = gr.Button("Clear")
95
+
96
+ submit_btn.click(chat_with_sap, [msg, chatbot], [chatbot])
97
+ msg.submit(chat_with_sap, [msg, chatbot], [chatbot])
98
+ clear_btn.click(lambda: [], None, chatbot)
99
+ submit_btn.click(lambda: "", None, msg)
100
+ msg.submit(lambda: "", None, msg)
101
+
102
+ if __name__ == "__main__":
103
+ demo.launch(debug=True)