PurchaseAgent / ai_agents.py
PD03's picture
Create ai_agents.py
de28582 verified
raw
history blame
10.2 kB
# ai_agents.py
import pandas as pd
import numpy as np
import openai
import json
from typing import Dict, List, Any
import streamlit as st
class LLMPoweredProcurementAgent:
"""AI Agent powered by OpenAI GPT for intelligent procurement analysis"""
def __init__(self, po_data: pd.DataFrame, spend_data: pd.DataFrame):
self.po_data = po_data
self.spend_data = spend_data
self.client = openai.OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
def generate_executive_summary(self) -> str:
"""Generate an executive summary using GPT"""
# Prepare data summary for LLM
data_summary = {
"total_spend": float(self.po_data['order_value'].sum()),
"total_orders": len(self.po_data),
"unique_vendors": len(self.po_data['vendor'].unique()),
"avg_order_value": float(self.po_data['order_value'].mean()),
"on_time_delivery_rate": float(self.po_data['on_time_delivery'].mean()),
"top_vendors": self.po_data.groupby('vendor')['order_value'].sum().nlargest(3).to_dict(),
"top_categories": self.po_data.groupby('material_category')['order_value'].sum().nlargest(3).to_dict(),
"quality_score_avg": float(self.po_data['quality_score'].mean())
}
prompt = f"""
As a senior procurement analyst, provide an executive summary of the procurement performance based on this data:
{json.dumps(data_summary, indent=2)}
Please provide:
1. A concise executive overview (2-3 sentences)
2. Key performance highlights
3. Areas of concern (if any)
4. Strategic recommendations (2-3 bullet points)
Keep the tone professional and actionable. Focus on business impact.
"""
try:
response = self.client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert procurement analyst with 15+ years of experience in SAP S/4HANA systems."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.7
)
return response.choices[0].message.content
except Exception as e:
return f"AI Analysis temporarily unavailable: {str(e)}"
def analyze_vendor_performance(self, vendor_name: str) -> str:
"""Deep dive analysis of specific vendor using LLM"""
vendor_data = self.po_data[self.po_data['vendor'] == vendor_name]
if vendor_data.empty:
return f"No data found for vendor: {vendor_name}"
vendor_metrics = {
"total_orders": len(vendor_data),
"total_spend": float(vendor_data['order_value'].sum()),
"avg_order_value": float(vendor_data['order_value'].mean()),
"on_time_delivery": float(vendor_data['on_time_delivery'].mean()),
"quality_score": float(vendor_data['quality_score'].mean()),
"categories": vendor_data['material_category'].value_counts().to_dict(),
"recent_trends": vendor_data.tail(10)['order_value'].tolist()
}
prompt = f"""
Analyze the performance of vendor "{vendor_name}" based on this procurement data:
{json.dumps(vendor_metrics, indent=2)}
Provide:
1. Overall performance assessment
2. Strengths and weaknesses
3. Risk factors to monitor
4. Specific recommendations for relationship management
5. Contract negotiation talking points
Be specific and actionable in your recommendations.
"""
try:
response = self.client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a strategic sourcing expert specializing in vendor relationship management and contract negotiations."},
{"role": "user", "content": prompt}
],
max_tokens=600,
temperature=0.6
)
return response.choices[0].message.content
except Exception as e:
return f"Vendor analysis unavailable: {str(e)}"
def generate_anomaly_insights(self, anomalies: List[Dict]) -> str:
"""Generate natural language insights about detected anomalies"""
if not anomalies:
return "No significant anomalies detected in your procurement data. Your processes appear to be operating within normal parameters."
prompt = f"""
I've detected the following anomalies in procurement data:
{json.dumps(anomalies, indent=2)}
As a procurement risk specialist, please:
1. Explain what these anomalies might indicate
2. Assess the potential business impact
3. Provide immediate action steps
4. Suggest preventive measures for the future
Be specific about risks and prioritize the most critical issues.
"""
try:
response = self.client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a procurement risk management expert with deep knowledge of supply chain vulnerabilities and mitigation strategies."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.5
)
return response.choices[0].message.content
except Exception as e:
return f"Anomaly analysis unavailable: {str(e)}"
def chat_with_data(self, user_question: str) -> str:
"""Natural language interface to query procurement data"""
# Create a data context for the LLM
data_context = {
"procurement_summary": {
"total_spend": float(self.po_data['order_value'].sum()),
"order_count": len(self.po_data),
"vendor_count": len(self.po_data['vendor'].unique()),
"date_range": f"{self.po_data['order_date'].min()} to {self.po_data['order_date'].max()}",
"categories": self.po_data['material_category'].unique().tolist(),
"vendors": self.po_data['vendor'].unique().tolist()
},
"performance_metrics": {
"avg_quality_score": float(self.po_data['quality_score'].mean()),
"on_time_delivery_rate": float(self.po_data['on_time_delivery'].mean()),
"avg_order_value": float(self.po_data['order_value'].mean())
}
}
prompt = f"""
User Question: {user_question}
Procurement Data Context:
{json.dumps(data_context, indent=2)}
Please answer the user's question based on the procurement data provided. If you need specific calculations or data analysis that isn't available in the context, explain what additional analysis would be needed.
Keep your response conversational but professional, and always relate back to business impact where possible.
"""
try:
response = self.client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an AI procurement analyst assistant. Answer questions about procurement data in a helpful, conversational way while maintaining professional expertise."},
{"role": "user", "content": prompt}
],
max_tokens=400,
temperature=0.7
)
return response.choices[0].message.content
except Exception as e:
return f"I'm having trouble accessing the AI right now. Please try again later. Error: {str(e)}"
class IntelligentRiskAgent:
"""Risk assessment agent powered by OpenAI"""
def __init__(self, spend_data: pd.DataFrame):
self.spend_data = spend_data
self.client = openai.OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
def generate_risk_report(self) -> str:
"""Generate comprehensive risk assessment using LLM"""
risk_data = {
"high_risk_suppliers": len(self.spend_data[self.spend_data['risk_score'] > 7]),
"total_suppliers": len(self.spend_data),
"avg_risk_score": float(self.spend_data['risk_score'].mean()),
"highest_risk_categories": self.spend_data.nlargest(5, 'risk_score')[['vendor', 'category', 'risk_score']].to_dict('records'),
"contract_compliance_avg": float(self.spend_data['contract_compliance'].mean()),
"low_compliance_count": len(self.spend_data[self.spend_data['contract_compliance'] < 85])
}
prompt = f"""
Generate a comprehensive supplier risk assessment report based on this data:
{json.dumps(risk_data, indent=2)}
Please provide:
1. Executive summary of risk landscape
2. Critical risk areas requiring immediate attention
3. Medium-term risk mitigation strategies
4. KPIs to monitor going forward
5. Recommended risk management framework improvements
Focus on actionable insights and business continuity.
"""
try:
response = self.client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a supply chain risk management consultant with expertise in enterprise risk frameworks and business continuity planning."},
{"role": "user", "content": prompt}
],
max_tokens=700,
temperature=0.6
)
return response.choices[0].message.content
except Exception as e:
return f"Risk analysis unavailable: {str(e)}"