Skip to content

Commit 4838314

Browse files
committed
updated function_app.py and whitespace fixes
1 parent 195ec99 commit 4838314

File tree

4 files changed

+69
-50
lines changed

4 files changed

+69
-50
lines changed

samples-v2/openai_agents/basic/order_return_validation.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -29,39 +29,39 @@ def validate_return_reason(return_request: OrderReturnRequest) -> ReturnValidati
2929
Validate if an order return reason is legitimate based on company policy.
3030
Valid reasons include: defective product, wrong item received, damaged in shipping,
3131
not as described, quality issues, size/fit issues (for clothing).
32-
Invalid reasons include: changed mind after 30 days, buyer's remorse,
32+
Invalid reasons include: changed mind after 30 days, buyer's remorse,
3333
found cheaper elsewhere, impulse purchase regret.
3434
"""
35-
35+
3636
# Simulate policy validation logic
3737
valid_reasons = [
38-
"defective", "damaged", "wrong item", "not as described",
39-
"quality issues", "size issue", "fit issue", "broken",
38+
"defective", "damaged", "wrong item", "not as described",
39+
"quality issues", "size issue", "fit issue", "broken",
4040
"missing parts", "expired"
4141
]
42-
42+
4343
invalid_reasons = [
4444
"changed mind", "buyer's remorse", "found cheaper",
4545
"impulse purchase", "don't need", "financial reasons"
4646
]
47-
47+
4848
reason_lower = return_request.return_reason.lower()
49-
49+
5050
# Check for valid reasons
5151
is_valid = any(valid_reason in reason_lower for valid_reason in valid_reasons)
52-
52+
5353
# Check for invalid reasons
5454
if any(invalid_reason in reason_lower for invalid_reason in invalid_reasons):
5555
is_valid = False
56-
56+
5757
# Calculate confidence based on keyword matching
5858
confidence = 0.8 if is_valid else 0.7
59-
59+
6060
validation_reason = (
61-
"Return reason matches company policy for valid returns" if is_valid
61+
"Return reason matches company policy for valid returns" if is_valid
6262
else "Return reason does not meet company return policy criteria"
6363
)
64-
64+
6565
return ReturnValidationResult(
6666
is_valid=is_valid,
6767
reason=validation_reason,
@@ -72,7 +72,7 @@ def validate_return_reason(return_request: OrderReturnRequest) -> ReturnValidati
7272

7373
def main(return_request_data: dict):
7474
"""Main function to run the order return validation agent"""
75-
75+
7676
agent = Agent(
7777
name="Order Return Validation Specialist",
7878
instructions="""
@@ -81,44 +81,44 @@ def main(return_request_data: dict):
8181
2. Determine if the return reason is valid according to company policy
8282
3. Provide clear reasoning for your decision
8383
4. Be fair but firm in applying policy guidelines
84-
84+
8585
Valid return reasons typically include:
8686
- Defective or broken products
8787
- Wrong item shipped
88-
- Damaged during shipping
88+
- Damaged during shipping
8989
- Product not as described
9090
- Quality issues
9191
- Size/fit problems (for applicable items)
92-
92+
9393
Invalid return reasons typically include:
9494
- Changed mind without valid cause
9595
- Found item cheaper elsewhere
9696
- Buyer's remorse
9797
- Financial hardship
9898
- General dissatisfaction without specific issue
99-
99+
100100
Always use the validate_return_reason tool to check the policy compliance.
101101
Based on the tool result, clearly state if the return is VALID or INVALID.
102102
End your response with either "Return is VALID" or "Return is INVALID".
103103
""",
104104
tools=[validate_return_reason],
105105
)
106-
106+
107107
# Convert dict to OrderReturnRequest
108108
return_request = OrderReturnRequest(**return_request_data)
109-
109+
110110
user_message = f"""
111111
Please validate this return request:
112-
112+
113113
Order ID: {return_request.order_id}
114-
Customer ID: {return_request.customer_id}
114+
Customer ID: {return_request.customer_id}
115115
Product Category: {return_request.product_category}
116116
Purchase Date: {return_request.purchase_date}
117117
Return Reason: {return_request.return_reason}
118-
118+
119119
Is this a valid return request according to our company policy?
120120
"""
121-
121+
122122
result = Runner.run_sync(agent, user_message)
123123
# Parse the agent's response to extract validation decision
124124
agent_response = result.final_output

samples-v2/openai_agents/basic/refund_processing.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,11 @@ def process_refund(order_id: str, refund_amount: float, customer_id: str) -> Ref
2222
Process a refund for a validated return request.
2323
This simulates calling payment processing systems.
2424
"""
25-
25+
2626
# Simulate refund processing
2727
import uuid
2828
transaction_id = f"REF-{uuid.uuid4().hex[:8].upper()}"
29-
29+
3030
return RefundResult(
3131
success=True,
3232
refund_amount=refund_amount,
@@ -35,14 +35,13 @@ def process_refund(order_id: str, refund_amount: float, customer_id: str) -> Ref
3535
processing_time="3-5 business days"
3636
)
3737

38-
39-
@function_tool
38+
@function_tool
4039
def get_order_details(order_id: str) -> Dict[str, Any]:
4140
"""
4241
Retrieve order details for refund processing.
4342
This simulates calling order management systems.
4443
"""
45-
44+
4645
# Simulate order lookup
4746
return {
4847
"order_id": order_id,
@@ -58,40 +57,40 @@ def get_order_details(order_id: str) -> Dict[str, Any]:
5857

5958
def main(validation_data: dict):
6059
"""Main function to process refund for validated return"""
61-
60+
6261
agent = Agent(
63-
name="Refund Processing Specialist",
62+
name="Refund Processing Specialist",
6463
instructions="""
6564
You are a refund processing specialist. Your job is to:
6665
1. Retrieve the order details for the validated return
6766
2. Calculate the appropriate refund amount (usually full product cost + tax)
6867
3. Process the refund through our payment systems
6968
4. Provide confirmation details to the customer
70-
69+
7170
Always retrieve order details first, then process the refund.
7271
Be precise with refund amounts and provide clear transaction information.
7372
End your response with "REFUND SUCCESS" if the refund is processed successfully.
7473
""",
7574
tools=[get_order_details, process_refund],
7675
)
77-
76+
7877
order_id = validation_data.get("order_id")
7978
customer_id = validation_data.get("customer_id", "unknown")
80-
79+
8180
user_message = f"""
8281
Process a refund for the validated return:
8382
Order ID: {order_id}
8483
Customer ID: {customer_id}
85-
84+
8685
Please:
8786
1. Get the order details
88-
2. Calculate the refund amount (product cost + tax, excluding shipping)
87+
2. Calculate the refund amount (product cost + tax, excluding shipping)
8988
3. Process the refund
9089
4. Provide confirmation details
9190
"""
9291

9392
result = Runner.run_sync(agent, user_message)
94-
93+
9594
# Parse the agent's response to extract refund status
9695
agent_response = result.final_output
9796
is_successful = "refund" in str(agent_response).lower() and "success" in str(agent_response).lower()
@@ -101,7 +100,7 @@ def main(validation_data: dict):
101100
"success": is_successful,
102101
"refund_amount": 93.00, # Product + Tax (86.01 + 7.99)
103102
"transaction_id": f"REF-{hash(str(validation_data.get('order_id', ''))) % 10000:04d}",
104-
"refund_method": "original_payment_method",
103+
"refund_method": "original_payment_method",
105104
"processing_time": "3-5 business days"
106105
}
107106

samples-v2/openai_agents/function_app.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from openai import AsyncAzureOpenAI
1111

1212
from agents import set_default_openai_client
13+
from order_return_orchestrators import register_order_return_orchestrators
1314

1415

1516
#region Regular Azure OpenAI setup
@@ -36,6 +37,7 @@ def get_azure_token():
3637

3738

3839
app = df.DFApp(http_auth_level=func.AuthLevel.FUNCTION)
40+
register_order_return_orchestrators(app)
3941

4042
@app.route(route="orchestrators/{functionName}")
4143
@app.durable_client_input(client_name="client")
@@ -46,6 +48,24 @@ async def orchestration_starter(req: func.HttpRequest, client):
4648
response = client.create_check_status_response(req, instance_id)
4749
return response
4850

51+
@app.route(route="order_return_processor")
52+
@app.durable_client_input(client_name="client")
53+
async def orchestration_order_return_processor(req: func.HttpRequest, client):
54+
# Extract input data from request body
55+
input_data = None
56+
try:
57+
if req.get_body():
58+
input_data = req.get_json()
59+
except Exception as e:
60+
return func.HttpResponse(
61+
f"Invalid JSON in request body: {str(e)}",
62+
status_code=400
63+
)
64+
65+
# Starting a new orchestration instance with input data
66+
instance_id = await client.start_new("order_return_processor", client_input=input_data)
67+
response = client.create_check_status_response(req, instance_id)
68+
return response
4969

5070
@app.orchestration_trigger(context_name="context")
5171
@app.durable_openai_agent_orchestrator

samples-v2/openai_agents/order_return_orchestrators.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
def register_order_return_orchestrators(app: df.DFApp):
88
"""Register all order return related orchestrators and activities with the app"""
9-
9+
1010
@app.orchestration_trigger(context_name="context")
1111
def order_return_processor(context: df.DurableOrchestrationContext):
1212
"""
@@ -15,20 +15,20 @@ def order_return_processor(context: df.DurableOrchestrationContext):
1515
2. If valid, processes refund via another orchestration
1616
3. If invalid, routes for human review
1717
"""
18-
18+
1919
# Get the input data (order return request)
2020
return_request_input = context.get_input()
21-
21+
2222
if not return_request_input:
2323
return {
2424
"status": "error",
2525
"message": "No return request data provided"
2626
}
27-
27+
2828
# Step 1: Validate the return reason using AI agent
2929
validation_task = context.call_sub_orchestrator("order_return_validation", return_request_input)
3030
validation_result = yield validation_task
31-
31+
3232
# Extract validation decision from agent response
3333
is_valid = False
3434
if validation_result:
@@ -46,7 +46,7 @@ def order_return_processor(context: df.DurableOrchestrationContext):
4646
"validation_result": validation_result
4747
})
4848
refund_result = yield refund_task
49-
49+
5050
return {
5151
"status": "approved_and_processed",
5252
"validation": validation_result,
@@ -61,15 +61,15 @@ def order_return_processor(context: df.DurableOrchestrationContext):
6161
"reason": "Return reason does not meet policy criteria"
6262
})
6363
review_result = yield human_review_task
64-
64+
6565
return {
6666
"status": "pending_human_review",
6767
"validation": validation_result,
6868
"human_review": review_result,
6969
"message": "Return requires human review"
7070
}
7171

72-
@app.orchestration_trigger(context_name="context")
72+
@app.orchestration_trigger(context_name="context")
7373
@app.durable_openai_agent_orchestrator
7474
def order_return_validation(context):
7575
"""Sub-orchestration that validates return reasons using AI agent"""
@@ -78,7 +78,7 @@ def order_return_validation(context):
7878
return basic.order_return_validation.main(return_request)
7979

8080
@app.orchestration_trigger(context_name="context")
81-
@app.durable_openai_agent_orchestrator
81+
@app.durable_openai_agent_orchestrator
8282
def refund_processor(context):
8383
"""Sub-orchestration that processes refunds using AI agent"""
8484
import basic.refund_processing
@@ -88,20 +88,20 @@ def refund_processor(context):
8888
@app.activity_trigger(input_name="review_data")
8989
async def route_for_human_review(review_data: dict) -> dict:
9090
"""Activity function that routes invalid returns for human review"""
91-
91+
9292
# In a real implementation, this would:
9393
# - Create a ticket in a support system
9494
# - Send notification to review team
9595
# - Update order status in database
9696
# - Send email to customer about review process
97-
97+
9898
review_ticket_id = f"REV-{uuid.uuid4().hex[:8].upper()}"
99-
99+
100100
# Simulate creating review ticket
101101
print(f"[HUMAN REVIEW] Created review ticket {review_ticket_id}")
102102
print(f"[HUMAN REVIEW] Order ID: {review_data['return_request'].get('order_id')}")
103103
print(f"[HUMAN REVIEW] Reason: {review_data.get('reason')}")
104-
104+
105105
return {
106106
"review_ticket_id": review_ticket_id,
107107
"status": "pending_review",

0 commit comments

Comments
 (0)