File size: 21,126 Bytes
448205d 53f0f8c 448205d 53f0f8c 448205d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 | """
Advanced Examples & Patterns for Multi-Agent Procurement System
Demonstrates:
1. Custom conditional routing
2. Error handling and recovery
3. Async execution
4. State persistence queries
5. Parallel vendor evaluation
6. Budget refinement loops
"""
import asyncio
from typing import Optional
from datetime import datetime
import json
from langchain_groq import ChatGroq
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command
from procurement_system import (
ProcurementState,
ProcurementAgents,
build_procurement_graph,
ProcurementWorkflowExecutor,
create_llm,
)
# =============================================================================
# EXAMPLE 1: Multi-Stage Approval with Escalation
# =============================================================================
class EscalationApprovalGate:
"""
Enhanced approval gate with escalation logic:
- Budget < $5000: Auto-approve
- Budget $5000-$10000: Manager approval
- Budget > $10000: Executive approval
"""
@staticmethod
def determine_approval_level(budget: float) -> str:
"""
Route approval based on budget threshold.
Args:
budget: Procurement budget
Returns:
Approval level: "auto", "manager", or "executive"
"""
if budget < 5000:
return "auto"
elif budget <= 10000:
return "manager"
else:
return "executive"
@staticmethod
def approval_gate_escalation(state: ProcurementState) -> Command:
"""
Advanced approval gate with multi-level routing.
Args:
state: Current procurement state
Returns:
Command routing to appropriate approval level
"""
budget = state["budget_limit"]
approval_level = EscalationApprovalGate.determine_approval_level(budget)
new_log = f"[{datetime.now().isoformat()}] EscalationGate: Budget ${budget:,.2f} requires {approval_level.upper()} approval"
# Route based on approval level
if approval_level == "auto":
# Auto-approve small procurements
return Command(
update={
"human_approved": True,
"logs": [new_log + " (AUTO-APPROVED)"]
},
goto="legal_node"
)
elif approval_level == "manager":
return Command(
update={"logs": [new_log]},
goto="manager_approval"
)
else: # executive
return Command(
update={"logs": [new_log]},
goto="executive_approval"
)
# =============================================================================
# EXAMPLE 2: Budget Refinement Loop
# =============================================================================
class BudgetRefinement:
"""
Handles budget overages by suggesting refinements and re-routing to analysis.
"""
@staticmethod
def refinement_node(state: ProcurementState, llm: ChatGroq) -> Command:
"""
When budget is exceeded, suggest alternatives to procurement requester.
Refinement options:
1. Reduce scope (fewer features/users)
2. Select lower-cost vendor
3. Negotiate terms with selected vendor
4. Increase budget
Args:
state: Current state with budget-exceeded vendor
llm: Language model for generating suggestions
Returns:
Command with refinement options
"""
vendor = state["selected_vendor"]
budget = state["budget_limit"]
shortfall = vendor.get("price_per_month", 0) - budget
new_log = f"[{datetime.now().isoformat()}] RefinementNode: Budget shortfall ${shortfall:,.2f}"
# Use LLM to generate refinement options
from langchain_core.prompts import PromptTemplate
refinement_prompt = PromptTemplate(
input_variables=["vendor", "budget", "shortfall"],
template="""
Budget refinement required.
Selected vendor: {vendor_name} - ${vendor_price}/month
Budget limit: ${budget}
Shortfall: ${shortfall}
Generate 3 refinement options for the procurement requester:
1. Scope reduction suggestions
2. Alternative vendor from list
3. Negotiation talking points for vendor
Format as JSON with "options" array.
"""
)
prompt_text = refinement_prompt.format(
vendor_name=vendor.get("name", "Unknown"),
vendor_price=vendor.get("price_per_month", 0),
budget=budget,
shortfall=shortfall
)
response = llm.invoke(prompt_text)
refinement_options = response.content
new_log += " | Refinement options generated"
# In production, these would be sent to procurement requester
# They would choose an option, state would update, and graph would continue
return Command(
update={
"logs": [new_log],
"contract_draft": f"Refinement Options:\n{refinement_options}"
},
goto=END
)
# =============================================================================
# EXAMPLE 3: Async Workflow Execution
# =============================================================================
async def execute_workflow_async(
graph,
procurement_request: str,
budget_limit: float
) -> dict:
"""
Async execution of procurement workflow for concurrent processing.
Enables:
- Running multiple workflows in parallel
- Non-blocking I/O for approval waits
- Better resource utilization
Args:
graph: Compiled LangGraph
procurement_request: Procurement need
budget_limit: Budget limit
Returns:
Final workflow state
"""
thread_id = f"async_procurement_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
config = {"configurable": {"thread_id": thread_id}}
initial_state = {
"procurement_request": procurement_request,
"vendor_options": [],
"selected_vendor": {},
"budget_limit": budget_limit,
"analysis_approved": False,
"human_approved": False,
"contract_draft": "",
"logs": ["Async workflow initiated"]
}
# Stream execution asynchronously
final_state = None
async for event in graph.astream(initial_state, config):
print(f"Async Event: {event}")
# Get state at interruption
final_state = graph.get_state(config)
return final_state.values
async def run_multiple_workflows():
"""
Execute multiple procurement workflows concurrently.
Use case: Process multiple department requests in parallel.
"""
llm = create_llm()
graph, _, _ = build_procurement_graph(llm)
# Create multiple concurrent workflows
workflows = [
execute_workflow_async(graph, "Cloud infrastructure", 5000),
execute_workflow_async(graph, "Software licensing", 3000),
execute_workflow_async(graph, "Security tools", 2000),
]
# Execute all in parallel
results = await asyncio.gather(*workflows)
print("\n" + "="*80)
print("CONCURRENT WORKFLOWS COMPLETED")
print("="*80)
for i, result in enumerate(results, 1):
print(f"Workflow {i}: {result['selected_vendor'].get('name', 'N/A')}")
print("="*80)
return results
# =============================================================================
# EXAMPLE 4: State Query & History Tracking
# =============================================================================
class WorkflowStateInspector:
"""
Query and analyze workflow state at any point in execution.
"""
def __init__(self, graph, thread_id: str):
"""
Initialize inspector for a specific workflow.
Args:
graph: Compiled LangGraph
thread_id: Thread ID of workflow to inspect
"""
self.graph = graph
self.thread_id = thread_id
self.config = {"configurable": {"thread_id": thread_id}}
def get_current_state(self) -> dict:
"""Retrieve current state of workflow."""
state = self.graph.get_state(self.config)
return state.values
def get_state_history(self) -> list:
"""Retrieve all state snapshots for this workflow."""
# Note: MemorySaver doesn't track history by default
# Production with PostgresSaver would query checkpoint history
current = self.get_current_state()
return [current]
def get_decision_trail(self) -> list:
"""Extract decision points from logs."""
state = self.get_current_state()
logs = state.get("logs", [])
decisions = []
for log in logs:
if "Route" in log or "APPROVED" in log or "REJECTED" in log:
decisions.append(log)
return decisions
def estimate_contract_ready_date(self) -> Optional[str]:
"""
Based on current state, estimate when contract will be ready.
"""
state = self.get_current_state()
if state.get("contract_draft"):
return "READY" # Contract already generated
elif state.get("human_approved"):
return "PENDING" # Awaiting legal node execution
elif state.get("analysis_approved"):
return "AWAITING_APPROVAL" # Waiting for human
else:
return "BLOCKED" # Budget or analysis issue
def generate_audit_report(self) -> str:
"""Generate comprehensive audit report of workflow."""
state = self.get_current_state()
report = f"""
PROCUREMENT WORKFLOW AUDIT REPORT
Generated: {datetime.now().isoformat()}
Thread ID: {self.thread_id}
PROCUREMENT DETAILS
ββ Request: {state.get('procurement_request')[:100]}...
ββ Budget: ${state.get('budget_limit', 0):,.2f}
ββ Status: {"COMPLETE" if state.get('contract_draft') else "IN_PROGRESS"}
DECISION HISTORY
"""
for i, log in enumerate(state.get("logs", []), 1):
report += f"ββ {i}. {log}\n"
report += f"""
VENDOR SELECTION
ββ Candidates Evaluated: {len(state.get('vendor_options', []))}
ββ Selected: {state.get('selected_vendor', {}).get('name', 'N/A')}
ββ Price: ${state.get('selected_vendor', {}).get('price_per_month', 0):,.2f}/month
ββ Status: {"APPROVED" if state.get('human_approved') else "PENDING_APPROVAL"}
CONTRACT STATUS
ββ Generated: {"YES" if state.get('contract_draft') else "NO"}
END REPORT
"""
return report
# =============================================================================
# EXAMPLE 5: Vendor Comparison Matrix
# =============================================================================
class VendorComparison:
"""
Generate detailed vendor comparison for procurement stakeholders.
"""
@staticmethod
def build_comparison_matrix(state: ProcurementState, llm: ChatGroq) -> str:
"""
Create side-by-side vendor comparison.
Args:
state: State with vendor_options populated
llm: Language model for analysis
Returns:
Markdown formatted comparison table
"""
vendors = state.get("vendor_options", [])
budget = state.get("budget_limit", 0)
from langchain_core.prompts import PromptTemplate
comparison_prompt = PromptTemplate(
input_variables=["vendors", "budget"],
template="""
Create a markdown comparison matrix for these vendors against budget ${budget}.
Vendors:
{vendors}
Generate a table comparing:
- Vendor name
- Price per month
- Reputation score
- Key capabilities
- Within budget (β/β)
- Risk assessment
Format as markdown table.
"""
)
vendors_json = json.dumps(vendors, indent=2)
prompt_text = comparison_prompt.format(vendors=vendors_json, budget=budget)
response = llm.invoke(prompt_text)
return response.content
# =============================================================================
# EXAMPLE 6: Error Recovery with Retry Logic
# =============================================================================
def robust_research_node(state: ProcurementState, llm: ChatGroq, max_retries: int = 3) -> Command:
"""
Research node with built-in retry logic and error handling.
Args:
state: Current state
llm: Language model
max_retries: Maximum retry attempts
Returns:
Command with state updates
"""
from procurement_system import mock_vendor_search
request = state["procurement_request"]
new_logs = []
for attempt in range(max_retries):
try:
vendors = mock_vendor_search(request)
if not vendors:
raise ValueError("No vendors returned from search")
new_log = f"[{datetime.now().isoformat()}] ResearchNode: Attempt {attempt + 1}: Found {len(vendors)} vendors"
new_logs.append(new_log)
return Command(
update={
"vendor_options": vendors,
"logs": new_logs
},
goto="analysis_node"
)
except Exception as e:
error_log = f"[{datetime.now().isoformat()}] ResearchNode: Attempt {attempt + 1} failed: {str(e)}"
new_logs.append(error_log)
if attempt == max_retries - 1:
# Final attempt failed
new_logs.append("ResearchNode: All retry attempts exhausted")
return Command(
update={"logs": new_logs},
goto=END
)
# Retry
# =============================================================================
# EXAMPLE 7: Custom Metrics & KPIs
# =============================================================================
class ProcurementMetrics:
"""
Track and analyze procurement workflow metrics.
"""
@staticmethod
def calculate_procurement_cycle_time(state: ProcurementState) -> float:
"""
Calculate time from request to approval.
Args:
state: Final state with logs
Returns:
Cycle time in seconds
"""
logs = state.get("logs", [])
if len(logs) < 2:
return 0
# Extract timestamps from logs
try:
first_time = logs[0].split("]")[0].strip("[")
last_time = logs[-1].split("]")[0].strip("[")
from datetime import datetime
t1 = datetime.fromisoformat(first_time)
t2 = datetime.fromisoformat(last_time)
return (t2 - t1).total_seconds()
except:
return 0
@staticmethod
def calculate_vendor_variance(state: ProcurementState) -> dict:
"""
Calculate variance between vendor prices.
Args:
state: State with vendor_options
Returns:
Variance metrics
"""
vendors = state.get("vendor_options", [])
if not vendors:
return {}
prices = [v.get("price_per_month", 0) for v in vendors]
avg_price = sum(prices) / len(prices)
min_price = min(prices)
max_price = max(prices)
return {
"avg_price": avg_price,
"min_price": min_price,
"max_price": max_price,
"range": max_price - min_price,
"variance_percentage": ((max_price - min_price) / avg_price * 100) if avg_price > 0 else 0
}
@staticmethod
def calculate_budget_utilization(state: ProcurementState) -> float:
"""
Calculate percentage of budget utilized by selected vendor.
Args:
state: Final state
Returns:
Utilization percentage
"""
vendor = state.get("selected_vendor", {})
budget = state.get("budget_limit", 1)
vendor_price = vendor.get("price_per_month", 0)
utilization = (vendor_price / budget) * 100
return round(utilization, 2)
# =============================================================================
# EXAMPLE 8: Integration with External Systems
# =============================================================================
class ExternalSystemIntegration:
"""
Integrate procurement system with external platforms.
"""
@staticmethod
async def send_approval_notification_via_slack(
state: ProcurementState,
slack_webhook: str
) -> bool:
"""
Send approval request via Slack when graph pauses.
Args:
state: Current procurement state
slack_webhook: Slack webhook URL
Returns:
Success status
"""
import requests
vendor = state.get("selected_vendor", {})
message = {
"text": "π Procurement Approval Required",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"""*Vendor:* {vendor.get('name')}
*Price:* ${vendor.get('price_per_month'):,.2f}/month
*Reputation:* {vendor.get('reputation_score')}/10
*Approve?*"""
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "Approve"},
"value": "approve",
"style": "primary"
},
{
"type": "button",
"text": {"type": "plain_text", "text": "Reject"},
"value": "reject",
"style": "danger"
}
]
}
]
}
try:
response = requests.post(slack_webhook, json=message)
return response.status_code == 200
except Exception as e:
print(f"Slack notification failed: {str(e)}")
return False
@staticmethod
async def sync_contract_to_docusign(
contract_draft: str,
recipient_email: str
) -> bool:
"""
Sync generated contract to DocuSign for e-signature.
Args:
contract_draft: Generated contract markdown
recipient_email: Email of contract recipient
Returns:
Success status
"""
# Mock implementation
print(f"[DocuSign] Uploading contract for {recipient_email}")
# In production, would call DocuSign API
return True
# =============================================================================
# MAIN: Run Examples
# =============================================================================
async def main():
"""Run advanced examples."""
print("\n" + "="*80)
print("ADVANCED PROCUREMENT SYSTEM EXAMPLES")
print("="*80 + "\n")
# Initialize LLM and graph
llm = create_llm()
graph, memory, agents = build_procurement_graph(llm)
# Example 1: Basic workflow
print("Example 1: Basic Workflow Execution\n")
executor = ProcurementWorkflowExecutor(graph, memory)
state, _ = executor.start_workflow(
procurement_request="Cloud infrastructure with auto-scaling",
budget_limit=5500.0,
)
# Example 2: State inspection
print("\nExample 2: Workflow State Inspection\n")
inspector = WorkflowStateInspector(graph, executor.thread_id)
print("Decision Trail:")
for decision in inspector.get_decision_trail():
print(f" - {decision}")
print(f"\nEstimated Contract Ready: {inspector.estimate_contract_ready_date()}")
# Example 3: Metrics
print("\nExample 3: Procurement Metrics\n")
metrics = ProcurementMetrics()
print(f"Budget Utilization: {metrics.calculate_budget_utilization(state)}%")
variance = metrics.calculate_vendor_variance(state)
if variance:
print(f"Vendor Price Variance: {variance['variance_percentage']:.2f}%")
# Example 4: Audit report
print("\nExample 4: Audit Report\n")
audit = inspector.generate_audit_report()
print(audit)
# Example 5: Async execution (if needed)
print("\nExample 5: Note - Async execution available via run_multiple_workflows()")
print("(Uncomment asyncio.run(run_multiple_workflows()) to test)")
print("\n" + "="*80)
print("ADVANCED EXAMPLES COMPLETED")
print("="*80 + "\n")
if __name__ == "__main__":
# Run async examples if needed
# asyncio.run(run_multiple_workflows())
# Run examples
import sys
if sys.version_info >= (3, 7):
asyncio.run(main())
else:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
|