Add an AI refund agent to the support chat

Python · LLM apps · advanced · greenfield

Adds an AI refund agent for the support chat: one FastAPI endpoint runs a single turn against the pinned gpt-4o-mini snapshot with a single `issue_refund` tool backed by the payments service. Tool arguments are validated before execution, payments-side failures go back to the model as tool errors instead of 500s, and timed-out completion calls are retried with backoff so a transient provider blip does not fail the customer's request. Turns are capped at 5 model calls, and a refund can only ever be issued once per request. Exercised the happy path and the tool-error path by hand against a sandbox order.

A customer-support service. The payments team exposes refunds as an internal HTTP endpoint with no idempotency key — every accepted call moves money — and the OpenAI client runs with `max_retries=0`, so the agent loop in `refund_agent.py` is the only place a timed-out provider call is retried.

Requirements

Files touched

--- app/services/refund_agent.py
+"""One-turn refund agent for the support chat.
+
+Runs a single agent turn against a pinned OpenAI snapshot: the model may call
+the `issue_refund` tool, and the turn ends when the model replies with plain
+text. A timed-out completion call is retried once (the SDK's own retries are
+disabled) so a transient provider hiccup does not fail the request.
+"""
+
+import json
+import os
+import time
+
+import openai
+from openai import OpenAI
+
+from app.services import payments
+
+MODEL = "gpt-4o-mini-2024-07-18"
+MAX_ATTEMPTS = 2
+RETRY_BACKOFF_SECONDS = 2.0
+COMPLETION_TIMEOUT_SECONDS = 20.0
+MAX_COMPLETION_CALLS = 5  # per request, timed-out calls included
+
+client = OpenAI(api_key=os.environ["OPENAI_API_KEY"], max_retries=0)
+
+SYSTEM_PROMPT = (
+    "You are the support agent for Northwind Outfitters. "
+    "The customer's refund request arrives as the user message. "
+    "To move money, call issue_refund with the order id and the amount in "

Review this PR

Python practice