diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..76c4719606efabd5d427f558ca9c574d2e2f0f46 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,14 @@ +.git +.agents +.codex +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +venv/ +env/ +logs/ +data/tickets/ +data/embeddings/ +.env diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..844d451910a3554a81a0301936b94bd15a876c3c --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +.env +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +env/ +venv/ +logs/*.log +data/tickets/*.json +data/embeddings/ diff --git a/Dockerfile b/Dockerfile index 3b644b7a2e6a4c1441688cb71cfa7d3d510d0250..24a7a4601b82ff2fae168ad6b397420106077d1f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,3 @@ - FROM python:3.11-slim ENV PYTHONDONTWRITEBYTECODE=1 diff --git a/README.md b/README.md index 9ea3621af41f12d4321faec2007cfaf3faeba7f7..68555eec88b0d760675422491ffa98fcd1efc4fb 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,245 @@ ---- -title: Shopify AI -emoji: 🚀 -colorFrom: red -colorTo: red -sdk: docker -app_port: 8501 -tags: -- streamlit -pinned: false -short_description: Streamlit template space ---- - -# Welcome to Streamlit! - -Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart: - -If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community -forums](https://discuss.streamlit.io). +# Shopify Customer Support Intelligence Agent + + +**Overview:** +- **Shopify_AI** is a modular Python project that orchestrates agents, retrieval-augmented generation (RAG), and service integrations to automate ticket handling, order lookups, policy retrieval, and escalations for Shopify merchants. + +**Key Features:** +- **Multi-agent architecture:** intent, order, policy, reasoning, validation, supervisor agents. +- **RAG support:** embeddings, retriever, and vector store for knowledge search. +- **Pluggable models:** adapters for Gemini, Groq, or other LLMs. +- **Services integration:** Shopify API, ticketing, escalation logic. + +**Architecture Flow** + +```mermaid +flowchart TD + User[Customer / Support Agent] -->|UI / Ticket| Frontend[Frontend / Streamlit or Web UI] + Frontend --> API[API (FastAPI)] + API --> Orchestrator[Supervisor Agent / Orchestrator] + Orchestrator --> Intent[Intent Agent] + Orchestrator --> Order[Order Agent] + Orchestrator --> Policy[Policy Agent] + Orchestrator --> Reasoning[Reasoning Agent] + Orchestrator --> Validation[Validation Agent] + Policy --> RAG[RAG Retriever] + RAG --> VectorStore[Vector Store / Embeddings] + Orchestrator --> Models[Model Router -> LLM Clients] + Models --> Gemini[Gemini Client] + Models --> Groq[Groq Client] + Orchestrator --> Services[Services Layer] + Services --> Shopify[Shopify Service] + Services --> TicketService[Ticket Service & Escalation] + TicketService -->|Create/Update| Data[Data / Logs] + classDef infra fill:#f9f,stroke:#333,stroke-width:1px; + VectorStore,Data,Shopify class infra +``` + +Quick links: +- Project entry: `app/main.py` +- Frontend: `app/frontend.py` +- Agents: `app/agents/` +- RAG: `rag/` +- Models: `models/` + +**Quickstart (Development)** + +Prerequisites: +- Python 3.10+ (use virtualenv) +- pip + +Install dependencies: + +```bash +python -m venv .venv +source .venv/bin/activate # macOS / Linux + .venv\Scripts\Activate # Windows PowerShell +pip install -r requirements.txt +``` + +Run the API locally (example): + +```bash +python -m app.main +# or if using uvicorn/fastapi: +# uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 +``` + +Run tests: + +```bash +pytest -q +``` + +**Docker** + +Use this minimal `Dockerfile` as a template: + +```dockerfile +FROM python:3.11-slim +WORKDIR /app +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt +COPY . /app +ENV PYTHONUNBUFFERED=1 +EXPOSE 8000 +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] +``` + +Build and run locally: + +```bash +docker build -t shopify_ai:latest . +docker run --rm -p 8000:8000 \ + -e OPENAI_API_KEY="your_key" \ + -v $(pwd)/data:/app/data \ + shopify_ai:latest +``` + +docker-compose (example) `docker-compose.yml` snippet: + +```yaml +version: '3.8' +services: + web: + build: . + ports: + - "8000:8000" + environment: + - OPENAI_API_KEY=${OPENAI_API_KEY} + volumes: + - ./:/app +``` + +**Streamlit (optional UI)** + +If you want a quick interactive UI using Streamlit, create a simple `streamlit_app.py` (example): + +```python +import streamlit as st +st.title('Shopify AI — Support Assistant') +question = st.text_input('Customer question') +if st.button('Ask'): + st.write('Sending to API...') + # call your API endpoint here, e.g. requests.post('http://localhost:8000/route', json={...}) + +# Run: `streamlit run streamlit_app.py` +``` + +Run Streamlit: + +```bash +pip install streamlit +streamlit run streamlit_app.py +``` + +**Git / GitHub: commit & push commands** + +Set up and push to GitHub (replace `USERNAME/REPO`): + +```bash +git init +git add . +git commit -m "chore: initial project import" +git branch -M main +git remote add origin git@github.com:USERNAME/REPO.git +git push -u origin main +``` + +If you prefer HTTPS remote: + +```bash +git remote add origin https://github.com/USERNAME/REPO.git +git push -u origin main +``` + +**Repository layout** + +- `app/` — application entrypoints and agents (`app/main.py`, `app/frontend.py`, `app/agents/`) +- `api/` — route definitions and request/response schemas +- `models/` — model clients and router +- `rag/` — embeddings, retriever, vector store +- `services/` — shopify, ticketing, escalation +- `data/` — embeddings, policies, tickets, orders +- `tests/` — unit/integration tests + +**Environment & Secrets** +- Store secrets in environment variables. Example: `OPENAI_API_KEY`, `SHOPIFY_API_KEY`, `SHOPIFY_SECRET`. +- Consider using `.env` and `python-dotenv` in development. + +**Contributing** +- Please open issues and PRs. Follow the repo's coding style and testing. + +**License** +- Add a license file (e.g., MIT) if you plan to open-source this repository. + +---- + +If you'd like, I can also create the `Dockerfile` and a `streamlit_app.py` in the repo now — tell me to proceed. + +This prototype automates Shopify-style customer support tickets with a multi-agent workflow: + +- Supervisor agent decides which steps to run. +- Intent agent classifies the ticket. +- Order agent retrieves sample Shopify order data from `data/orders/orders.json`. +- Policy agent retrieves relevant policy text from `data/policies`. +- Reasoning agent generates a grounded customer response. +- Validation agent checks policy grounding. +- Escalation service sends low-confidence or unsafe cases to human support. + + +## Run Locally + + +```bash +pip install -r requirements.txt +python -m app.rag.ingest +uvicorn app.main:app --reload +``` + +Open `http://127.0.0.1:8000/docs` for the API docs. + +Run the Streamlit frontend in a second terminal: + +```bash +streamlit run app/frontend.py +``` + +## Example Request + +```bash +curl -X POST http://127.0.0.1:8000/api/tickets \ + -H "Content-Type: application/json" \ + -d '{"customer_id":"cust_001","message":"My order #1234 is delayed. Can I get a refund?"}' +``` + +The project runs with deterministic local fallbacks by default. Add API keys in `.env` when wiring real Groq, Gemini, and Shopify integrations. + +## RAG Pipeline + +The policy RAG flow uses: + +- `RecursiveCharacterTextSplitter` for chunking policy, FAQ, and product manual files. +- `BAAI/bge-small-en-v1.5` from Hugging Face through `sentence-transformers`. +- Persistent Chroma DB stored at `data/embeddings/chroma`. +- Metadata per chunk, including source file, document type, chunk index, path, and character count. +- `BAAI/bge-reranker-base` as a cross-encoder reranker after vector retrieval. + +Build or rebuild the vector DB: + +```bash +python -m app.rag.ingest +``` + +Check the vector DB from the API: + +```bash +curl http://127.0.0.1:8000/api/rag/status +``` + +Rebuild from the API: + +```bash +curl -X POST http://127.0.0.1:8000/api/rag/ingest +``` +>>>>>>> 4c7223c (shopify_ai) diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1321eae5c0ba2f826396d3698d34ad2ff23f32bf --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +"""Shopify customer support intelligence platform.""" diff --git a/app/agents/__init__.py b/app/agents/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..511d50c22702201e90011a2ed00afc4e0388143e --- /dev/null +++ b/app/agents/__init__.py @@ -0,0 +1 @@ +"""Agent implementations.""" diff --git a/app/agents/intent_agent.py b/app/agents/intent_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..802e5c674b8b22511171e63a516f4447257756ad --- /dev/null +++ b/app/agents/intent_agent.py @@ -0,0 +1,54 @@ +from app.models.model_router import ModelRouter + + +class IntentAgent: + INTENT_KEYWORDS = { + "refund_request": ["refund", "money back", "reimburse"], + "return_request": ["return", "send back"], + "shipping_status": ["where", "shipping", "shipment", "tracking", "arrived", "delivery", "delayed"], + "payment_issue": ["payment", "card", "charged", "failed"], + "cancellation_request": ["cancel", "cancellation"], + "exchange_request": ["exchange", "replace", "size"], + "warranty_claim": ["warranty", "repair", "defective", "broken"], + } + + def __init__(self, router: ModelRouter | None = None): + self.router = router or ModelRouter() + + def classify(self, message: str) -> dict: + if self.router.intent_model.api_key: + try: + return self._classify_with_groq(message) + except Exception: + pass + return self._classify_locally(message) + + def _classify_with_groq(self, message: str) -> dict: + prompt = f""" +Classify this Shopify customer support ticket. +Return only JSON with keys: intent, priority, confidence. +Allowed intents: refund_request, return_request, shipping_status, payment_issue, +cancellation_request, exchange_request, warranty_claim, general_support. +Allowed priority values: low, normal, high. + +Message: {message} +""" + result = self.router.intent_model.complete_json( + prompt, + system="You are an intent classification agent for ecommerce customer support.", + ) + return { + "intent": result.get("intent", "general_support"), + "priority": result.get("priority", "normal"), + "confidence": float(result.get("confidence", 0.7)), + } + + def _classify_locally(self, message: str) -> dict: + lowered = message.lower() + intent = "general_support" + for candidate, keywords in self.INTENT_KEYWORDS.items(): + if any(keyword in lowered for keyword in keywords): + intent = candidate + break + priority = "high" if any(word in lowered for word in ["urgent", "angry", "refund", "failed", "broken"]) else "normal" + return {"intent": intent, "priority": priority, "confidence": 0.86 if intent != "general_support" else 0.62} diff --git a/app/agents/order_agent.py b/app/agents/order_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..5117d71d2caf55e8f21fab3f4beec0aca86ca86b --- /dev/null +++ b/app/agents/order_agent.py @@ -0,0 +1,11 @@ +from app.services.shopify_service import ShopifyService +from app.utils.helpers import extract_order_id + + +class OrderAgent: + def __init__(self, service: ShopifyService | None = None): + self.service = service or ShopifyService() + + def fetch(self, message: str, order_id: str | None = None) -> dict | None: + resolved_order_id = order_id or extract_order_id(message) + return self.service.get_order(resolved_order_id) diff --git a/app/agents/policy_agent.py b/app/agents/policy_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..6312a5897b3833cb9836c1653606c8c0b00ed259 --- /dev/null +++ b/app/agents/policy_agent.py @@ -0,0 +1,7 @@ +from app.rag.retriever import retrieve_policies + + +class PolicyAgent: + def retrieve(self, message: str, intent: str | None = None) -> list[dict]: + query = f"{intent or ''} {message}".strip() + return retrieve_policies(query, k=4) diff --git a/app/agents/reasoning_agent.py b/app/agents/reasoning_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..74dc8784754ee3b4887498b9e893385d5c839afa --- /dev/null +++ b/app/agents/reasoning_agent.py @@ -0,0 +1,88 @@ +from app.models.model_router import ModelRouter + + +class ReasoningAgent: + def __init__(self, router: ModelRouter | None = None): + self.router = router or ModelRouter() + + def respond(self, message: str, intent: dict, order: dict | None, policies: list[dict]) -> dict: + if self.router.reasoning_model.api_key: + try: + return self._respond_with_groq(message, intent, order, policies) + except Exception: + pass + return self._respond_locally(message, intent, order, policies) + + def _respond_with_groq(self, message: str, intent: dict, order: dict | None, policies: list[dict]) -> dict: + policy_context = "\n\n".join( + f"Source: {policy['source']}\n{policy['content']}" for policy in policies + ) + prompt = f""" +Generate a Shopify customer support response using the order and policy context. +Return only the final customer-facing reply as normal plain text. +Do not return JSON, markdown tables, internal analysis, confidence values, or policy metadata. +Do not promise refunds, replacements, cancellations, or payment actions unless the policy clearly allows it. + +Customer message: +{message} + +Intent: +{intent} + +Order: +{order} + +Policy context: +{policy_context} +""" + response = self.router.reasoning_model.complete( + prompt, + system="You are a careful ecommerce support reasoning agent.", + ).strip() + confidence = min(0.95, intent.get("confidence", 0.7) + (0.08 if order else -0.08) + (0.06 if policies else -0.06)) + return { + "analysis": self._analysis_summary(intent, order, policies, "groq"), + "response": response, + "confidence": round(confidence, 2), + } + + def _respond_locally(self, message: str, intent: dict, order: dict | None, policies: list[dict]) -> dict: + intent_name = intent.get("intent", "general_support") + policy_hint = policies[0]["content"].splitlines()[0] if policies else "Use store support policy." + order_text = self._order_summary(order) + response = self._compose_response(intent_name, order, policy_hint) + confidence = min(0.95, intent.get("confidence", 0.6) + (0.08 if order else -0.08) + (0.06 if policies else -0.06)) + return { + "analysis": self._analysis_summary(intent, order, policies, "local"), + "response": response, + "confidence": round(confidence, 2), + } + + def _analysis_summary(self, intent: dict, order: dict | None, policies: list[dict], mode: str) -> str: + intent_name = intent.get("intent", "general_support") + order_text = self._order_summary(order) + policy_sources = ", ".join(policy["source"] for policy in policies) if policies else "none" + return f"mode={mode}; intent={intent_name}; {order_text}; policy_sources={policy_sources}" + + def _order_summary(self, order: dict | None) -> str: + if not order: + return "No matching order was found." + return f"Order {order['order_id']} is {order['status']} with delivery estimate {order.get('expected_delivery')}." + + def _compose_response(self, intent_name: str, order: dict | None, policy_hint: str) -> str: + greeting = "Thanks for reaching out. " + if not order: + return greeting + "I could not verify the order details from the message, so I am escalating this to our support team for a manual check." + if intent_name == "refund_request": + return ( + greeting + + f"I checked order #{order['order_id']}. Its current status is {order['status']} and the expected delivery date is " + + f"{order.get('expected_delivery')}. {policy_hint} Based on this, I will keep the case open and escalate it if the policy condition is met." + ) + if intent_name == "shipping_status": + return ( + greeting + + f"Order #{order['order_id']} is currently {order['status']}. Tracking: {order.get('tracking_number')}. " + + f"Expected delivery is {order.get('expected_delivery')}." + ) + return greeting + f"I reviewed order #{order['order_id']} and the relevant policy. {policy_hint} A support agent can help with any next step that needs approval." diff --git a/app/agents/supervisor_agent.py b/app/agents/supervisor_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..d96a895726f9e9d9451cee74561a3989718f3b41 --- /dev/null +++ b/app/agents/supervisor_agent.py @@ -0,0 +1,15 @@ +class SupervisorAgent: + def plan(self, message: str, order_id: str | None = None) -> dict: + lowered = message.lower() + needs_order = bool(order_id) or any(word in lowered for word in ["order", "shipment", "tracking", "delivery"]) + needs_policy = any( + word in lowered + for word in ["refund", "return", "shipping", "payment", "cancel", "exchange", "warranty", "gift"] + ) + return { + "run_intent_agent": True, + "run_order_agent": needs_order, + "run_policy_agent": needs_policy or True, + "run_reasoning_agent": True, + "run_validation_agent": True, + } diff --git a/app/agents/validation_agent.py b/app/agents/validation_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..8b1fbbf7815fc6310d3cdcc867c4d6af81d1d46a --- /dev/null +++ b/app/agents/validation_agent.py @@ -0,0 +1,17 @@ +from app.models.model_router import ModelRouter + + +class ValidationAgent: + def __init__(self, router: ModelRouter | None = None): + self.router = router or ModelRouter() + + def validate(self, response: str, policies: list[dict]) -> dict: + context = "\n\n".join(policy["content"] for policy in policies) + try: + result = self.router.validation_model.validate(response, context) + except Exception as exc: + result = { + "valid": bool(context.strip()) and len(response.strip()) > 20, + "issues": [f"Gemini validation unavailable; used local fallback. {type(exc).__name__}"], + } + return {"valid": bool(result.get("valid")), "issues": result.get("issues", [])} diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dff53e5af3f99340bcfd48c954f9ba7d6c2f12fa --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1 @@ +"""API package.""" diff --git a/app/api/routes.py b/app/api/routes.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea4aeebcb46e7948c659cdcb01f4906212e8352 --- /dev/null +++ b/app/api/routes.py @@ -0,0 +1,44 @@ +from fastapi import APIRouter +from fastapi.responses import PlainTextResponse + +from app.api.schemas import TicketRequest, TicketResponse +from app.rag.ingest import ingest_policies +from app.rag.vector_store import collection_count +from app.workflows.langgraph_workflow import CustomerSupportWorkflow + +router = APIRouter(prefix="/api", tags=["support"]) +workflow = CustomerSupportWorkflow() + + +@router.get("/health") +def health() -> dict: + return {"status": "ok"} + + +@router.get("/rag/status") +def rag_status() -> dict: + return {"collection_count": collection_count()} + + +@router.post("/rag/ingest") +def ingest_rag() -> dict: + return ingest_policies(reset=True) + + +@router.post("/tickets", response_model=TicketResponse) +def submit_ticket(request: TicketRequest) -> dict: + return workflow.run( + customer_id=request.customer_id, + message=request.message, + order_id=request.order_id, + ) + + +@router.post("/tickets/text", response_class=PlainTextResponse) +def submit_ticket_text(request: TicketRequest) -> str: + result = workflow.run( + customer_id=request.customer_id, + message=request.message, + order_id=request.order_id, + ) + return result["response"] diff --git a/app/api/schemas.py b/app/api/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..a3cad7f958e5c9ffdd6954ed1f53389883be754c --- /dev/null +++ b/app/api/schemas.py @@ -0,0 +1,27 @@ +from typing import Any + +from pydantic import BaseModel, Field + + +class TicketRequest(BaseModel): + customer_id: str = Field(..., examples=["cust_001"]) + message: str = Field(..., examples=["My order #1234 has not arrived. Can I get a refund?"]) + order_id: str | None = Field(default=None, examples=["1234"]) + + +class AgentTrace(BaseModel): + supervisor: dict[str, Any] + intent: dict[str, Any] + order: dict[str, Any] | None + policies: list[dict[str, Any]] + reasoning: dict[str, Any] + validation: dict[str, Any] + + +class TicketResponse(BaseModel): + ticket_id: str + response: str + confidence: float + escalated: bool + escalation_reason: str | None = None + trace: AgentTrace diff --git a/app/frontend.py b/app/frontend.py new file mode 100644 index 0000000000000000000000000000000000000000..708991349698acee13224a564cc18360f01d95b2 --- /dev/null +++ b/app/frontend.py @@ -0,0 +1,51 @@ +import os + +import httpx +import streamlit as st + + +API_BASE_URL = os.getenv("API_BASE_URL", "http://127.0.0.1:8000") + + +st.set_page_config(page_title="Shopify Support AI", page_icon="AI", layout="centered") + +st.title("Shopify Support AI") + +customer_id = st.text_input("Customer ID", value="cust_001") +order_id = st.text_input("Order ID", value="1234") +message = st.text_area( + "Customer message", + value="My order #1234 is delayed. Can I get a refund?", + height=140, +) +show_debug = st.checkbox("Show agent debug details", value=False) + +if st.button("Submit ticket", type="primary"): + payload = { + "customer_id": customer_id, + "message": message, + "order_id": order_id or None, + } + + try: + with httpx.Client(timeout=30) as client: + response = client.post(f"{API_BASE_URL}/api/tickets", json=payload) + response.raise_for_status() + data = response.json() + except httpx.HTTPError as exc: + st.error(f"Backend request failed: {exc}") + else: + st.subheader("AI Response") + st.write(data["response"]) + + if show_debug: + col1, col2, col3 = st.columns(3) + col1.metric("Ticket", data["ticket_id"]) + col2.metric("Confidence", data["confidence"]) + col3.metric("Escalated", "Yes" if data["escalated"] else "No") + + if data.get("escalation_reason"): + st.warning(data["escalation_reason"]) + + with st.expander("Agent trace"): + st.json(data["trace"]) diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..8f111188ab17dd0a671d7bb451cb6921b2bbb0ac --- /dev/null +++ b/app/main.py @@ -0,0 +1,18 @@ +from fastapi import FastAPI + +from app.api.routes import router +from app.utils.config import get_settings + + +def create_app() -> FastAPI: + settings = get_settings() + app = FastAPI( + title=settings.app_name, + version="0.1.0", + description="Agentic Shopify customer support prototype with policy RAG and escalation.", + ) + app.include_router(router) + return app + + +app = create_app() diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1d28d82136af1f7fa1521f52d91f7fc4cc7b95c4 --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +"""Model client package.""" diff --git a/app/models/gemini_client.py b/app/models/gemini_client.py new file mode 100644 index 0000000000000000000000000000000000000000..bdab47e28067c391d7fe857020f975f02e7e8638 --- /dev/null +++ b/app/models/gemini_client.py @@ -0,0 +1,50 @@ +import json +import re + +import httpx + +from app.utils.logger import get_logger + +logger = get_logger(__name__) + + +class GeminiClient: + def __init__(self, api_key: str | None = None, model: str = "gemini-1.5-flash"): + self.api_key = api_key + self.model = model + + def validate(self, response: str, context: str) -> dict: + if not self.api_key: + logger.info("Gemini API key not configured; using local validation.") + has_policy_context = bool(context.strip()) + return { + "valid": has_policy_context and len(response.strip()) > 20, + "issues": [] if has_policy_context else ["No policy context was supplied."], + } + + prompt = f""" +Validate this customer support response against the policy context. +Return only JSON with keys: valid (boolean), issues (array of strings). + +Policy context: +{context} + +Customer response: +{response} +""" + api_response = httpx.post( + f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent", + params={"key": self.api_key}, + json={"contents": [{"parts": [{"text": prompt}]}]}, + timeout=45, + ) + api_response.raise_for_status() + text = api_response.json()["candidates"][0]["content"]["parts"][0]["text"] + return self._parse_json(text) + + def _parse_json(self, text: str) -> dict: + cleaned = text.strip() + fenced = re.search(r"```(?:json)?\s*(.*?)```", cleaned, flags=re.DOTALL) + if fenced: + cleaned = fenced.group(1).strip() + return json.loads(cleaned) diff --git a/app/models/groq_client.py b/app/models/groq_client.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc000ef91cadb7af88113895cba92fb77adf1e9 --- /dev/null +++ b/app/models/groq_client.py @@ -0,0 +1,53 @@ +import json + +import httpx + +from app.utils.logger import get_logger + +logger = get_logger(__name__) + + +class GroqClient: + def __init__( + self, + api_key: str | None = None, + model: str = "llama-3.3-70b-versatile", + base_url: str = "https://api.groq.com/openai/v1", + ): + self.api_key = api_key + self.model = model + self.base_url = base_url + + def complete(self, prompt: str, system: str | None = None) -> str: + if not self.api_key: + logger.info("Groq API key not configured; using deterministic local response.") + return prompt + + messages = [] + if system: + messages.append({"role": "system", "content": system}) + messages.append({"role": "user", "content": prompt}) + + payload = { + "model": self.model, + "messages": messages, + "temperature": 0.2, + } + if "json" in prompt.lower(): + payload["response_format"] = {"type": "json_object"} + + response = httpx.post( + f"{self.base_url}/chat/completions", + headers={ + "Authorization": f"Bearer {self.api_key}", + "Content-Type": "application/json", + }, + json=payload, + timeout=45, + ) + response.raise_for_status() + data = response.json() + return data["choices"][0]["message"]["content"] + + def complete_json(self, prompt: str, system: str | None = None) -> dict: + return json.loads(self.complete(prompt, system)) diff --git a/app/models/model_router.py b/app/models/model_router.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3dffcaddd48a52e268f7954f42e1c9379279e2 --- /dev/null +++ b/app/models/model_router.py @@ -0,0 +1,11 @@ +from app.models.gemini_client import GeminiClient +from app.models.groq_client import GroqClient +from app.utils.config import get_settings + + +class ModelRouter: + def __init__(self): + settings = get_settings() + self.intent_model = GroqClient(settings.groq_api_key, "llama-3.1-8b-instant") + self.reasoning_model = GroqClient(settings.groq_api_key, "llama-3.3-70b-versatile") + self.validation_model = GeminiClient(settings.gemini_api_key or settings.google_api_key, "gemini-1.5-flash") diff --git a/app/rag/__init__.py b/app/rag/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7484db69ad9cf0e294519ab9d42ae1d26f75dc77 --- /dev/null +++ b/app/rag/__init__.py @@ -0,0 +1 @@ +"""Retrieval package.""" diff --git a/app/rag/embeddings.py b/app/rag/embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..ad8f41d78e9da84680458d500beb0bb81bac867f --- /dev/null +++ b/app/rag/embeddings.py @@ -0,0 +1,46 @@ +from functools import lru_cache + +from chromadb import Documents, EmbeddingFunction, Embeddings +from sentence_transformers import CrossEncoder, SentenceTransformer + +from app.utils.config import get_settings + + +QUERY_PREFIX = "Represent this sentence for searching relevant passages: " + + +@lru_cache +def get_embedding_model() -> SentenceTransformer: + settings = get_settings() + return SentenceTransformer(settings.embedding_model_name) + + +@lru_cache +def get_reranker_model() -> CrossEncoder: + settings = get_settings() + return CrossEncoder(settings.reranker_model_name) + + +def embed_documents(texts: list[str]) -> list[list[float]]: + model = get_embedding_model() + vectors = model.encode(texts, normalize_embeddings=True, show_progress_bar=False) + return vectors.tolist() + + +def embed_queries(texts: list[str]) -> list[list[float]]: + prefixed = [QUERY_PREFIX + text for text in texts] + return embed_documents(prefixed) + + +class BGEEmbeddingFunction(EmbeddingFunction): + def __call__(self, input: Documents) -> Embeddings: + return embed_documents(list(input)) + + +def rerank(query: str, documents: list[str]) -> list[float]: + if not documents: + return [] + model = get_reranker_model() + pairs = [(query, document) for document in documents] + scores = model.predict(pairs, show_progress_bar=False) + return [float(score) for score in scores] diff --git a/app/rag/ingest.py b/app/rag/ingest.py new file mode 100644 index 0000000000000000000000000000000000000000..3b82e2b2569b9cb61c14a46da312b262ad9b41f7 --- /dev/null +++ b/app/rag/ingest.py @@ -0,0 +1,103 @@ +import hashlib +from pathlib import Path + +from langchain_text_splitters import RecursiveCharacterTextSplitter + +from app.utils.config import get_settings +from app.rag.vector_store import get_policy_collection, reset_vector_store + + +def load_policy_documents(policy_dir: Path | None = None) -> list[dict]: + directory = policy_dir or get_settings().policy_dir + documents: list[dict] = [] + for path in sorted(directory.glob("*.txt")): + content = path.read_text(encoding="utf-8").strip() + if content: + documents.append( + { + "source": path.name, + "path": str(path), + "document_type": infer_document_type(path.name), + "text": content, + } + ) + return documents + + +def infer_document_type(filename: str) -> str: + if filename.startswith("faq_"): + return "faq" + if filename.startswith("product_manual_"): + return "product_manual" + if "policy" in filename or "shipping" in filename: + return "policy" + return "knowledge_base" + + +def build_text_splitter() -> RecursiveCharacterTextSplitter: + settings = get_settings() + return RecursiveCharacterTextSplitter( + chunk_size=settings.rag_chunk_size, + chunk_overlap=settings.rag_chunk_overlap, + separators=["\n\n", "\n", ". ", " ", ""], + ) + + +def chunk_documents(documents: list[dict]) -> list[dict]: + splitter = build_text_splitter() + chunks: list[dict] = [] + for document in documents: + split_texts = splitter.split_text(document["text"]) + total_chunks = len(split_texts) + for index, text in enumerate(split_texts): + chunk_id = stable_chunk_id(document["source"], index, text) + chunks.append( + { + "id": chunk_id, + "text": text, + "metadata": { + "source": document["source"], + "path": document["path"], + "document_type": document["document_type"], + "chunk_index": index, + "chunk_count": total_chunks, + "char_count": len(text), + }, + } + ) + return chunks + + +def stable_chunk_id(source: str, index: int, text: str) -> str: + digest = hashlib.sha1(f"{source}:{index}:{text}".encode("utf-8")).hexdigest()[:16] + return f"{Path(source).stem}-{index}-{digest}" + + +def ingest_policies(reset: bool = True) -> dict: + if reset: + reset_vector_store() + + documents = load_policy_documents() + chunks = chunk_documents(documents) + collection = get_policy_collection() + + if chunks: + collection.upsert( + ids=[chunk["id"] for chunk in chunks], + documents=[chunk["text"] for chunk in chunks], + metadatas=[chunk["metadata"] for chunk in chunks], + ) + + return { + "documents": len(documents), + "chunks": len(chunks), + "collection_count": collection.count(), + } + + +if __name__ == "__main__": + result = ingest_policies(reset=True) + print( + "Ingested {documents} documents into {chunks} chunks. " + "Chroma collection now has {collection_count} records.".format(**result) + ) diff --git a/app/rag/retriever.py b/app/rag/retriever.py new file mode 100644 index 0000000000000000000000000000000000000000..81757a35a5a48898bf4a3a2ef347808c72ca503a --- /dev/null +++ b/app/rag/retriever.py @@ -0,0 +1,48 @@ +from app.rag.embeddings import embed_queries, rerank +from app.rag.ingest import ingest_policies +from app.rag.vector_store import get_policy_collection + + +def ensure_vector_store_ready() -> None: + collection = get_policy_collection() + if collection.count() == 0: + ingest_policies(reset=False) + + +def retrieve_policies(query: str, k: int = 4, fetch_k: int = 12, use_reranker: bool = True) -> list[dict]: + ensure_vector_store_ready() + collection = get_policy_collection() + query_embedding = embed_queries([query])[0] + results = collection.query( + query_embeddings=[query_embedding], + n_results=fetch_k, + include=["documents", "metadatas", "distances"], + ) + + documents = results.get("documents", [[]])[0] + metadatas = results.get("metadatas", [[]])[0] + distances = results.get("distances", [[]])[0] + ids = results.get("ids", [[]])[0] + + candidates = [] + for chunk_id, content, metadata, distance in zip(ids, documents, metadatas, distances): + candidates.append( + { + "id": chunk_id, + "source": metadata.get("source"), + "content": content, + "metadata": metadata, + "distance": round(float(distance), 4), + "score": round(1 / (1 + float(distance)), 4), + } + ) + + if use_reranker and candidates: + scores = rerank(query, [candidate["content"] for candidate in candidates]) + for candidate, score in zip(candidates, scores): + candidate["rerank_score"] = round(score, 4) + candidates.sort(key=lambda item: item["rerank_score"], reverse=True) + else: + candidates.sort(key=lambda item: item["score"], reverse=True) + + return candidates[:k] diff --git a/app/rag/vector_store.py b/app/rag/vector_store.py new file mode 100644 index 0000000000000000000000000000000000000000..9725e99b648eb1a30a899445e56421d96950fe6a --- /dev/null +++ b/app/rag/vector_store.py @@ -0,0 +1,34 @@ +import shutil +from pathlib import Path + +import chromadb + +from app.rag.embeddings import BGEEmbeddingFunction +from app.utils.config import get_settings + + +def get_chroma_client(persist_dir: Path | None = None) -> chromadb.PersistentClient: + settings = get_settings() + directory = persist_dir or settings.chroma_dir + directory.mkdir(parents=True, exist_ok=True) + return chromadb.PersistentClient(path=str(directory)) + + +def get_policy_collection(): + settings = get_settings() + client = get_chroma_client() + return client.get_or_create_collection( + name=settings.chroma_collection, + embedding_function=BGEEmbeddingFunction(), + metadata={"description": "Shopify customer support policy and manual chunks"}, + ) + + +def reset_vector_store() -> None: + settings = get_settings() + if settings.chroma_dir.exists(): + shutil.rmtree(settings.chroma_dir) + + +def collection_count() -> int: + return get_policy_collection().count() diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9bdba2a1e77644c3b7dfdb24767867290389161 --- /dev/null +++ b/app/services/__init__.py @@ -0,0 +1 @@ +"""Service package.""" diff --git a/app/services/escalation_service.py b/app/services/escalation_service.py new file mode 100644 index 0000000000000000000000000000000000000000..90a079ba91b96c11a57c254b7f11701419a2e6b3 --- /dev/null +++ b/app/services/escalation_service.py @@ -0,0 +1,13 @@ +from app.utils.config import get_settings + + +class EscalationService: + def should_escalate(self, confidence: float, validation: dict, order: dict | None) -> tuple[bool, str | None]: + threshold = get_settings().auto_reply_confidence_threshold + if not validation.get("valid"): + return True, "Validation failed or policy grounding was insufficient." + if confidence < threshold: + return True, f"Confidence {confidence:.2f} is below threshold {threshold:.2f}." + if order is None: + return True, "Order details could not be found." + return False, None diff --git a/app/services/shopify_service.py b/app/services/shopify_service.py new file mode 100644 index 0000000000000000000000000000000000000000..f85595a5db0b82e3eee7ad542c82f5410b1cc6b2 --- /dev/null +++ b/app/services/shopify_service.py @@ -0,0 +1,19 @@ +import json +from pathlib import Path + +from app.utils.config import get_settings + + +class ShopifyService: + def __init__(self, orders_path: Path | None = None): + self.orders_path = orders_path or get_settings().orders_path + + def get_order(self, order_id: str | None) -> dict | None: + if not order_id or not self.orders_path.exists(): + return None + data = json.loads(self.orders_path.read_text(encoding="utf-8")) + normalized = order_id.replace("#", "").upper() + for order in data.get("orders", []): + if str(order.get("order_id", "")).upper() == normalized: + return order + return None diff --git a/app/services/ticket_service.py b/app/services/ticket_service.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a80ca97c66c833c0a6f8281969b23835409460 --- /dev/null +++ b/app/services/ticket_service.py @@ -0,0 +1,21 @@ +import json +from datetime import datetime, timezone +from pathlib import Path +from uuid import uuid4 + +from app.utils.config import get_settings + + +class TicketService: + def __init__(self, tickets_dir: Path | None = None): + self.tickets_dir = tickets_dir or get_settings().tickets_dir + self.tickets_dir.mkdir(parents=True, exist_ok=True) + + def save(self, payload: dict) -> str: + ticket_id = f"ticket_{uuid4().hex[:10]}" + payload = {"ticket_id": ticket_id, "created_at": datetime.now(timezone.utc).isoformat(), **payload} + metadata_path = self.tickets_dir / f"{ticket_id}.json" + response_path = self.tickets_dir / f"{ticket_id}.txt" + metadata_path.write_text(json.dumps(payload, indent=2), encoding="utf-8") + response_path.write_text(payload.get("response", ""), encoding="utf-8") + return ticket_id diff --git a/app/utils/__init__.py b/app/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88c371e524d6714df76d03579e7454ef7cc04aa1 --- /dev/null +++ b/app/utils/__init__.py @@ -0,0 +1 @@ +"""Utility package.""" diff --git a/app/utils/config.py b/app/utils/config.py new file mode 100644 index 0000000000000000000000000000000000000000..26299d692a3bb2fc1e6c9e1349c1429865666675 --- /dev/null +++ b/app/utils/config.py @@ -0,0 +1,33 @@ +from functools import lru_cache +from pathlib import Path + +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + app_name: str = "Shopify Customer Support Intelligence" + environment: str = "development" + log_level: str = "INFO" + data_dir: Path = Path("data") + policy_dir: Path = Path("data/policies") + orders_path: Path = Path("data/orders/orders.json") + tickets_dir: Path = Path("data/tickets") + chroma_dir: Path = Path("data/embeddings/chroma") + chroma_collection: str = "shopify_support_policies" + embedding_model_name: str = "BAAI/bge-small-en-v1.5" + reranker_model_name: str = "BAAI/bge-reranker-base" + rag_chunk_size: int = 700 + rag_chunk_overlap: int = 120 + groq_api_key: str | None = None + gemini_api_key: str | None = None + google_api_key: str | None = None + shopify_store_url: str | None = None + shopify_access_token: str | None = None + auto_reply_confidence_threshold: float = 0.72 + + model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8") + + +@lru_cache +def get_settings() -> Settings: + return Settings() diff --git a/app/utils/helpers.py b/app/utils/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..fb9bdb9c37700ad54e51488d35ec84a2e439d4d1 --- /dev/null +++ b/app/utils/helpers.py @@ -0,0 +1,15 @@ +import re +from datetime import date + + +ORDER_PATTERN = re.compile(r"(?:order\s*)?#?\s*([A-Z0-9-]{4,})", re.IGNORECASE) + + +def extract_order_id(text: str) -> str | None: + match = ORDER_PATTERN.search(text) + return match.group(1).upper() if match else None + + +def days_between(start: str, end: str | None = None) -> int: + end_date = date.fromisoformat(end) if end else date.today() + return (end_date - date.fromisoformat(start)).days diff --git a/app/utils/logger.py b/app/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd319aefd87718f59676252565d966297e6fd63 --- /dev/null +++ b/app/utils/logger.py @@ -0,0 +1,12 @@ +import logging + +from app.utils.config import get_settings + + +def get_logger(name: str) -> logging.Logger: + settings = get_settings() + logging.basicConfig( + level=settings.log_level, + format="%(asctime)s %(levelname)s [%(name)s] %(message)s", + ) + return logging.getLogger(name) diff --git a/app/workflows/__init__.py b/app/workflows/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..35ffe2e7c035c308170545f0db6443c3a2db83cf --- /dev/null +++ b/app/workflows/__init__.py @@ -0,0 +1 @@ +"""Workflow package.""" diff --git a/app/workflows/langgraph_workflow.py b/app/workflows/langgraph_workflow.py new file mode 100644 index 0000000000000000000000000000000000000000..af1f83dcb7267d4e8ff12fd2414a5c37bebc3b02 --- /dev/null +++ b/app/workflows/langgraph_workflow.py @@ -0,0 +1,63 @@ +from app.agents.intent_agent import IntentAgent +from app.agents.order_agent import OrderAgent +from app.agents.policy_agent import PolicyAgent +from app.agents.reasoning_agent import ReasoningAgent +from app.agents.supervisor_agent import SupervisorAgent +from app.agents.validation_agent import ValidationAgent +from app.services.escalation_service import EscalationService +from app.services.ticket_service import TicketService + + +class CustomerSupportWorkflow: + def __init__(self): + self.supervisor = SupervisorAgent() + self.intent_agent = IntentAgent() + self.order_agent = OrderAgent() + self.policy_agent = PolicyAgent() + self.reasoning_agent = ReasoningAgent() + self.validation_agent = ValidationAgent() + self.escalation_service = EscalationService() + self.ticket_service = TicketService() + + def run(self, customer_id: str, message: str, order_id: str | None = None) -> dict: + supervisor = self.supervisor.plan(message, order_id) + intent = self.intent_agent.classify(message) + order = self.order_agent.fetch(message, order_id) if supervisor["run_order_agent"] else None + policies = self.policy_agent.retrieve(message, intent["intent"]) if supervisor["run_policy_agent"] else [] + reasoning = self.reasoning_agent.respond(message, intent, order, policies) + validation = self.validation_agent.validate(reasoning["response"], policies) + escalated, escalation_reason = self.escalation_service.should_escalate( + reasoning["confidence"], validation, order + ) + ticket_id = self.ticket_service.save( + { + "customer_id": customer_id, + "message": message, + "order_id": order_id, + "response": reasoning["response"], + "escalated": escalated, + "trace": { + "supervisor": supervisor, + "intent": intent, + "order": order, + "policies": policies, + "reasoning": reasoning, + "validation": validation, + }, + } + ) + return { + "ticket_id": ticket_id, + "response": reasoning["response"], + "confidence": reasoning["confidence"], + "escalated": escalated, + "escalation_reason": escalation_reason, + "trace": { + "supervisor": supervisor, + "intent": intent, + "order": order, + "policies": policies, + "reasoning": reasoning, + "validation": validation, + }, + } diff --git a/data/orders/orders.json b/data/orders/orders.json new file mode 100644 index 0000000000000000000000000000000000000000..4eff9c85c23608a4f15a5fea4ec50795925eb4c9 --- /dev/null +++ b/data/orders/orders.json @@ -0,0 +1,526 @@ +{ + "orders": [ + { + "order_id": "1234", + "customer_id": "cust_001", + "customer_email": "maya@example.com", + "status": "delayed", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1234IN", + "carrier": "BlueDart", + "ordered_at": "2026-06-14", + "expected_delivery": "2026-06-25", + "promised_delivery": "2026-06-22", + "total": 129.99, + "currency": "USD", + "shipping_country": "IN", + "items": ["Smart Travel Backpack"] + }, + { + "order_id": "5678", + "customer_id": "cust_002", + "customer_email": "noah@example.com", + "status": "delivered", + "fulfillment_status": "fulfilled", + "payment_status": "paid", + "tracking_number": "TRK5678US", + "carrier": "UPS", + "ordered_at": "2026-06-10", + "expected_delivery": "2026-06-16", + "promised_delivery": "2026-06-17", + "delivered_at": "2026-06-16", + "total": 79.5, + "currency": "USD", + "shipping_country": "US", + "items": ["Wireless Desk Lamp"] + }, + { + "order_id": "9012", + "customer_id": "cust_003", + "customer_email": "aisha@example.com", + "status": "processing", + "fulfillment_status": "unfulfilled", + "payment_status": "paid", + "tracking_number": null, + "carrier": null, + "ordered_at": "2026-06-22", + "expected_delivery": "2026-06-29", + "promised_delivery": "2026-06-30", + "total": 34.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle"] + }, + { + "order_id": "1001", + "customer_id": "cust_004", + "customer_email": "liam@example.com", + "status": "in_transit", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1001US", + "carrier": "FedEx", + "ordered_at": "2026-06-18", + "expected_delivery": "2026-06-24", + "promised_delivery": "2026-06-25", + "total": 58.25, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle", "Replacement Lid"] + }, + { + "order_id": "1002", + "customer_id": "cust_005", + "customer_email": "emma@example.com", + "status": "delivered", + "fulfillment_status": "fulfilled", + "payment_status": "paid", + "tracking_number": "TRK1002CA", + "carrier": "DHL", + "ordered_at": "2026-06-05", + "expected_delivery": "2026-06-15", + "promised_delivery": "2026-06-16", + "delivered_at": "2026-06-15", + "total": 149.99, + "currency": "USD", + "shipping_country": "CA", + "items": ["Smart Travel Backpack"] + }, + { + "order_id": "1003", + "customer_id": "cust_006", + "customer_email": "olivia@example.com", + "status": "cancelled", + "fulfillment_status": "cancelled", + "payment_status": "refunded", + "tracking_number": null, + "carrier": null, + "ordered_at": "2026-06-19", + "cancelled_at": "2026-06-19", + "expected_delivery": null, + "promised_delivery": null, + "total": 44.99, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle"] + }, + { + "order_id": "1004", + "customer_id": "cust_007", + "customer_email": "arjun@example.com", + "status": "payment_failed", + "fulfillment_status": "unfulfilled", + "payment_status": "failed", + "tracking_number": null, + "carrier": null, + "ordered_at": "2026-06-23", + "expected_delivery": null, + "promised_delivery": null, + "total": 219.0, + "currency": "USD", + "shipping_country": "IN", + "items": ["Wireless Desk Lamp", "Smart Travel Backpack"] + }, + { + "order_id": "1005", + "customer_id": "cust_008", + "customer_email": "sophia@example.com", + "status": "out_for_delivery", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1005US", + "carrier": "USPS", + "ordered_at": "2026-06-20", + "expected_delivery": "2026-06-23", + "promised_delivery": "2026-06-24", + "total": 39.5, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle"] + }, + { + "order_id": "1006", + "customer_id": "cust_009", + "customer_email": "ethan@example.com", + "status": "lost_package_review", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1006US", + "carrier": "UPS", + "ordered_at": "2026-06-07", + "expected_delivery": "2026-06-14", + "promised_delivery": "2026-06-14", + "total": 89.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Wireless Desk Lamp"] + }, + { + "order_id": "1007", + "customer_id": "cust_010", + "customer_email": "mia@example.com", + "status": "return_requested", + "fulfillment_status": "fulfilled", + "payment_status": "paid", + "tracking_number": "TRK1007US", + "carrier": "FedEx", + "ordered_at": "2026-06-01", + "expected_delivery": "2026-06-07", + "promised_delivery": "2026-06-08", + "delivered_at": "2026-06-07", + "total": 129.99, + "currency": "USD", + "shipping_country": "US", + "items": ["Smart Travel Backpack"] + }, + { + "order_id": "1008", + "customer_id": "cust_011", + "customer_email": "lucas@example.com", + "status": "exchange_requested", + "fulfillment_status": "fulfilled", + "payment_status": "paid", + "tracking_number": "TRK1008US", + "carrier": "UPS", + "ordered_at": "2026-06-03", + "expected_delivery": "2026-06-09", + "promised_delivery": "2026-06-10", + "delivered_at": "2026-06-09", + "total": 34.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle"] + }, + { + "order_id": "1009", + "customer_id": "cust_012", + "customer_email": "ava@example.com", + "status": "damaged_on_arrival", + "fulfillment_status": "fulfilled", + "payment_status": "paid", + "tracking_number": "TRK1009US", + "carrier": "USPS", + "ordered_at": "2026-06-12", + "expected_delivery": "2026-06-18", + "promised_delivery": "2026-06-18", + "delivered_at": "2026-06-18", + "total": 79.5, + "currency": "USD", + "shipping_country": "US", + "items": ["Wireless Desk Lamp"] + }, + { + "order_id": "1010", + "customer_id": "cust_013", + "customer_email": "isabella@example.com", + "status": "partially_fulfilled", + "fulfillment_status": "partial", + "payment_status": "paid", + "tracking_number": "TRK1010US-A", + "carrier": "FedEx", + "ordered_at": "2026-06-17", + "expected_delivery": "2026-06-26", + "promised_delivery": "2026-06-27", + "total": 208.99, + "currency": "USD", + "shipping_country": "US", + "items": ["Smart Travel Backpack", "Wireless Desk Lamp"] + }, + { + "order_id": "1011", + "customer_id": "cust_014", + "customer_email": "logan@example.com", + "status": "international_customs", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1011GB", + "carrier": "DHL", + "ordered_at": "2026-06-08", + "expected_delivery": "2026-06-28", + "promised_delivery": "2026-06-26", + "total": 164.99, + "currency": "USD", + "shipping_country": "GB", + "items": ["Smart Travel Backpack"] + }, + { + "order_id": "1012", + "customer_id": "cust_015", + "customer_email": "amelia@example.com", + "status": "delivered", + "fulfillment_status": "fulfilled", + "payment_status": "paid", + "tracking_number": "TRK1012AU", + "carrier": "DHL", + "ordered_at": "2026-05-30", + "expected_delivery": "2026-06-20", + "promised_delivery": "2026-06-21", + "delivered_at": "2026-06-19", + "total": 114.0, + "currency": "USD", + "shipping_country": "AU", + "items": ["Wireless Desk Lamp", "Fitness Water Bottle"] + }, + { + "order_id": "1013", + "customer_id": "cust_016", + "customer_email": "ben@example.com", + "status": "awaiting_pickup", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1013US", + "carrier": "USPS", + "ordered_at": "2026-06-16", + "expected_delivery": "2026-06-23", + "promised_delivery": "2026-06-24", + "total": 44.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle"] + }, + { + "order_id": "1014", + "customer_id": "cust_017", + "customer_email": "zoe@example.com", + "status": "refund_approved", + "fulfillment_status": "fulfilled", + "payment_status": "refund_pending", + "tracking_number": "TRK1014US", + "carrier": "UPS", + "ordered_at": "2026-05-25", + "expected_delivery": "2026-06-01", + "promised_delivery": "2026-06-01", + "delivered_at": "2026-06-01", + "total": 79.5, + "currency": "USD", + "shipping_country": "US", + "items": ["Wireless Desk Lamp"] + }, + { + "order_id": "1015", + "customer_id": "cust_018", + "customer_email": "daniel@example.com", + "status": "fraud_review", + "fulfillment_status": "on_hold", + "payment_status": "authorized", + "tracking_number": null, + "carrier": null, + "ordered_at": "2026-06-23", + "expected_delivery": null, + "promised_delivery": null, + "total": 389.98, + "currency": "USD", + "shipping_country": "US", + "items": ["Smart Travel Backpack", "Smart Travel Backpack", "Wireless Desk Lamp"] + }, + { + "order_id": "1016", + "customer_id": "cust_019", + "customer_email": "nora@example.com", + "status": "preparing_shipment", + "fulfillment_status": "processing", + "payment_status": "paid", + "tracking_number": null, + "carrier": null, + "ordered_at": "2026-06-21", + "expected_delivery": "2026-06-28", + "promised_delivery": "2026-06-29", + "total": 129.99, + "currency": "USD", + "shipping_country": "US", + "items": ["Smart Travel Backpack"] + }, + { + "order_id": "1017", + "customer_id": "cust_020", + "customer_email": "sam@example.com", + "status": "delivered", + "fulfillment_status": "fulfilled", + "payment_status": "paid", + "tracking_number": "TRK1017US", + "carrier": "FedEx", + "ordered_at": "2026-06-11", + "expected_delivery": "2026-06-17", + "promised_delivery": "2026-06-18", + "delivered_at": "2026-06-17", + "total": 34.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle"] + }, + { + "order_id": "1018", + "customer_id": "cust_021", + "customer_email": "harper@example.com", + "status": "carrier_exception", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1018US", + "carrier": "UPS", + "ordered_at": "2026-06-13", + "expected_delivery": "2026-06-19", + "promised_delivery": "2026-06-20", + "total": 79.5, + "currency": "USD", + "shipping_country": "US", + "items": ["Wireless Desk Lamp"] + }, + { + "order_id": "1019", + "customer_id": "cust_022", + "customer_email": "vivaan@example.com", + "status": "international_in_transit", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1019SG", + "carrier": "DHL", + "ordered_at": "2026-06-12", + "expected_delivery": "2026-07-02", + "promised_delivery": "2026-07-01", + "total": 173.99, + "currency": "USD", + "shipping_country": "SG", + "items": ["Smart Travel Backpack", "Fitness Water Bottle"] + }, + { + "order_id": "1020", + "customer_id": "cust_023", + "customer_email": "ella@example.com", + "status": "gift_card_issued", + "fulfillment_status": "digital_delivered", + "payment_status": "paid", + "tracking_number": null, + "carrier": "email", + "ordered_at": "2026-06-22", + "expected_delivery": "2026-06-22", + "promised_delivery": "2026-06-22", + "delivered_at": "2026-06-22", + "total": 50.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Digital Gift Card"] + }, + { + "order_id": "1021", + "customer_id": "cust_024", + "customer_email": "jack@example.com", + "status": "address_hold", + "fulfillment_status": "on_hold", + "payment_status": "paid", + "tracking_number": null, + "carrier": null, + "ordered_at": "2026-06-23", + "expected_delivery": "2026-06-30", + "promised_delivery": "2026-06-30", + "total": 129.99, + "currency": "USD", + "shipping_country": "US", + "items": ["Smart Travel Backpack"] + }, + { + "order_id": "1022", + "customer_id": "cust_025", + "customer_email": "grace@example.com", + "status": "replacement_sent", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1022US", + "carrier": "FedEx", + "ordered_at": "2026-06-02", + "expected_delivery": "2026-06-24", + "promised_delivery": "2026-06-25", + "total": 0.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Wireless Desk Lamp Replacement"] + }, + { + "order_id": "1023", + "customer_id": "cust_026", + "customer_email": "leo@example.com", + "status": "return_in_transit", + "fulfillment_status": "fulfilled", + "payment_status": "paid", + "tracking_number": "RET1023US", + "carrier": "USPS", + "ordered_at": "2026-05-28", + "expected_delivery": "2026-06-04", + "promised_delivery": "2026-06-05", + "delivered_at": "2026-06-04", + "total": 34.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle"] + }, + { + "order_id": "1024", + "customer_id": "cust_027", + "customer_email": "chloe@example.com", + "status": "subscription_order_created", + "fulfillment_status": "processing", + "payment_status": "paid", + "tracking_number": null, + "carrier": null, + "ordered_at": "2026-06-23", + "expected_delivery": "2026-06-30", + "promised_delivery": "2026-06-30", + "total": 34.0, + "currency": "USD", + "shipping_country": "US", + "items": ["Fitness Water Bottle"] + }, + { + "order_id": "1025", + "customer_id": "cust_028", + "customer_email": "omar@example.com", + "status": "delayed", + "fulfillment_status": "shipped", + "payment_status": "paid", + "tracking_number": "TRK1025DE", + "carrier": "DHL", + "ordered_at": "2026-06-04", + "expected_delivery": "2026-06-27", + "promised_delivery": "2026-06-20", + "total": 129.99, + "currency": "USD", + "shipping_country": "DE", + "items": ["Smart Travel Backpack"] + }, + { + "order_id": "1026", + "customer_id": "cust_029", + "customer_email": "lily@example.com", + "status": "delivered", + "fulfillment_status": "fulfilled", + "payment_status": "partially_refunded", + "tracking_number": "TRK1026US", + "carrier": "UPS", + "ordered_at": "2026-06-06", + "expected_delivery": "2026-06-12", + "promised_delivery": "2026-06-13", + "delivered_at": "2026-06-12", + "total": 208.99, + "currency": "USD", + "shipping_country": "US", + "items": ["Smart Travel Backpack", "Wireless Desk Lamp"] + }, + { + "order_id": "1027", + "customer_id": "cust_030", + "customer_email": "mateo@example.com", + "status": "manual_review", + "fulfillment_status": "on_hold", + "payment_status": "paid", + "tracking_number": null, + "carrier": null, + "ordered_at": "2026-06-23", + "expected_delivery": "2026-07-01", + "promised_delivery": "2026-07-01", + "total": 499.0, + "currency": "USD", + "shipping_country": "MX", + "items": ["Smart Travel Backpack", "Wireless Desk Lamp", "Fitness Water Bottle"] + } + ] +} diff --git a/data/policies/cancellation_policy.txt b/data/policies/cancellation_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..e10ae9801e6af380515684d77521a28fc5c2b826 --- /dev/null +++ b/data/policies/cancellation_policy.txt @@ -0,0 +1,13 @@ +Cancellation Policy + +Orders can be cancelled before fulfillment begins. Support should check the fulfillment status before confirming cancellation. If the order is still unfulfilled, cancellation can usually be processed and the customer should receive confirmation by email. + +After fulfillment starts, cancellation is not guaranteed. If the warehouse has picked, packed, or handed the shipment to the carrier, support should explain that the order may need to be delivered first and then returned under the return policy. + +Cancellation requests for digital products, gift cards, personalized items, or made-to-order products require human review because these items may be created or delivered immediately after purchase. + +If a customer entered an incorrect address, support should try an address change before cancellation when the order is not fulfilled. If the order has shipped, support should direct the customer to the carrier or escalate the case. + +Subscription cancellations apply only to future billing cycles. A customer who wants to cancel an order already generated by a subscription must follow the normal order cancellation window. + +Urgent cancellation messages should be prioritized when the order is less than 2 hours old, but support must not guarantee cancellation until fulfillment status is verified. diff --git a/data/policies/exchange_policy.txt b/data/policies/exchange_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a5e85486dd3388aedd48ae71298b88485b5ab7f --- /dev/null +++ b/data/policies/exchange_policy.txt @@ -0,0 +1,13 @@ +Exchange Policy + +Exchanges are available within 30 days of delivery for eligible unused items. The exchange window begins on the carrier delivery date. Support should confirm the product, original variant, requested replacement variant, and reason for exchange. + +Size, color, and style exchanges depend on current inventory. If the requested replacement is in stock, support may reserve or create the replacement order according to store procedures. If inventory is low, support should avoid promising availability until the exchange is approved. + +The original item must be returned unused, clean, and in original packaging. Customers should include all accessories, labels, manuals, and protective inserts. Items that are damaged, used, or missing components may not qualify for exchange. + +If the requested replacement is unavailable, the customer may choose a return, store credit, or waitlist notification. Price differences may apply when the requested item has a different price than the original item. + +Exchanges for damaged, defective, or incorrect items should be treated as store-responsibility cases. Support should request photos and may provide a prepaid return label. + +International exchanges require human review because return shipping, customs duties, and replacement shipping costs vary by destination. diff --git a/data/policies/faq_1.txt b/data/policies/faq_1.txt new file mode 100644 index 0000000000000000000000000000000000000000..f7927c9a6df348b9eb3ad72c279fe4338391ed37 --- /dev/null +++ b/data/policies/faq_1.txt @@ -0,0 +1,7 @@ +FAQ: Where is my order? + +Use the tracking number from the shipping confirmation email. Tracking can take up to 24 hours to appear after the carrier receives the package. If tracking says "label created", the package may still be waiting for the first carrier scan. + +If the promised delivery date has not passed, provide the expected delivery date and carrier name. If the promised delivery date has passed, check whether the package is still moving. Domestic packages with no movement for more than 5 business days should be escalated. International packages with no movement for more than 14 days should be escalated. + +If tracking says delivered but the customer cannot find the package, ask them to check around the delivery location, mail room, reception desk, household members, and neighbors. Then escalate if the package is still missing. diff --git a/data/policies/faq_2.txt b/data/policies/faq_2.txt new file mode 100644 index 0000000000000000000000000000000000000000..e21182ed43f7a69075a620ad2038d4ab3ff0c4df --- /dev/null +++ b/data/policies/faq_2.txt @@ -0,0 +1,7 @@ +FAQ: Can I change my shipping address? + +Shipping addresses can be changed only before fulfillment begins. Support should check the order fulfillment status before promising any change. If the order is unfulfilled, collect the corrected full address and confirm it back to the customer. + +If the order has already shipped, address changes are not guaranteed. The customer may need to contact the carrier or local postal service. Some carriers allow delivery management, package hold, or pickup point changes. + +If the address error could cause package loss, escalate the case. Do not cancel or refund a shipped order only because of an address error unless a support lead approves it. diff --git a/data/policies/faq_3.txt b/data/policies/faq_3.txt new file mode 100644 index 0000000000000000000000000000000000000000..60b284ba428570bc9202429d470ec10f305fff29 --- /dev/null +++ b/data/policies/faq_3.txt @@ -0,0 +1,7 @@ +FAQ: What should I do if my item arrived damaged? + +Send photos of the damaged item, exterior packaging, interior packaging, and shipping label within 7 days of delivery. Include the order number and a short description of the damage. + +Support should determine whether the damage appears to be carrier damage, manufacturing defect, missing component, or wrong item. For safety issues such as overheating electronics, broken glass, sharp parts, smoke, or exposed wires, advise the customer to stop using the product and escalate immediately. + +Possible resolutions include replacement, replacement part, refund, store credit, or warranty review. Do not require the customer to return a dangerous item without human review. diff --git a/data/policies/faq_4.txt b/data/policies/faq_4.txt new file mode 100644 index 0000000000000000000000000000000000000000..9ce8c8619e0b05c053f7b8ab9e69dda576c3d7d1 --- /dev/null +++ b/data/policies/faq_4.txt @@ -0,0 +1,7 @@ +FAQ: Why did my payment fail? + +Payments can fail because of incorrect card details, insufficient funds, bank authentication, expired card, payment provider outage, address mismatch, browser issue, or network interruption. Customers should retry once after checking card details and billing address. + +If the payment still fails, suggest another accepted payment method such as a different card, Shop Pay, PayPal, or gift card where available. Customers should not repeatedly retry many times because banks may temporarily block further attempts. + +A failed payment may appear as a pending authorization in the customer's bank account. Failed authorizations are not captured by the store and usually disappear automatically based on the bank timeline. diff --git a/data/policies/gift_card_policy.txt b/data/policies/gift_card_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..23bd67b9f2068931b28e357597a7f50927dcaa8d --- /dev/null +++ b/data/policies/gift_card_policy.txt @@ -0,0 +1,13 @@ +Gift Card Policy + +Gift cards are delivered by email and can be used at checkout for eligible products. Delivery may take several minutes after purchase. Customers should check spam, promotions, and alternate email inboxes before reporting a missing gift card. + +Gift cards do not expire unless required by local law. They cannot be replaced with cash unless required by law and cannot be used to buy another gift card. + +Lost gift cards can be reissued only after the original purchaser verifies the purchase. Verification may include order number, purchaser email, billing name, and partial payment details that do not expose sensitive card information. + +If a gift card code was sent to the wrong email address, support may resend it to the correct address only after confirming that the balance has not been used. If any balance has been redeemed, the case must be escalated. + +Gift card balances can be combined with another payment method when the gift card balance is less than the order total. Refunds for purchases made with a gift card are normally returned to the gift card first. + +Suspected stolen, resold, or fraudulently obtained gift cards must be escalated before any balance information is disclosed. diff --git a/data/policies/international_shipping.txt b/data/policies/international_shipping.txt new file mode 100644 index 0000000000000000000000000000000000000000..6bed2f66795cc7422ee1aaf309ec1a1f8f9855cb --- /dev/null +++ b/data/policies/international_shipping.txt @@ -0,0 +1,13 @@ +International Shipping Policy + +International shipping times vary by destination, carrier network, customs processing, local holidays, weather, and import inspection. Delivery estimates shown at checkout are estimates and may change after the shipment enters the destination country. + +Customers are responsible for duties, taxes, brokerage fees, and import fees unless checkout clearly states that these charges are prepaid. Support should not quote exact customs charges because they are determined by the destination country. + +Tracking may show limited updates while a package is between countries or waiting for customs clearance. If tracking has no update for fewer than 14 days, support should explain that international tracking gaps can happen. If tracking has no update for more than 14 days, escalate for carrier investigation. + +International address changes after shipment are rarely possible. If the order has not shipped, support may request an address correction. If the order has shipped, the customer may need to contact the carrier or local postal service. + +Refused international packages may be returned to sender, abandoned, or destroyed depending on the carrier and customs rules. Refunds for refused packages exclude non-refundable shipping costs, duties, taxes, and return fees unless the refusal was caused by store error. + +International returns and exchanges require human review because return labels, customs declarations, tax recovery, and replacement shipping costs vary by destination. diff --git a/data/policies/membership_policy.txt b/data/policies/membership_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..cdd835b02aaba2b2b80ee511251b0426102efdca --- /dev/null +++ b/data/policies/membership_policy.txt @@ -0,0 +1,13 @@ +Membership Policy + +Members receive early access to selected promotions, saved preferences, order history features, loyalty rewards, birthday offers, and limited product launches where available. Benefits may vary by country, account status, and campaign. + +Membership benefits cannot be exchanged for cash. Discounts, points, or rewards cannot be transferred between accounts unless support approves an account merge for verified duplicate accounts. + +Reward points may take up to 48 hours to appear after purchase. Points may be reversed if an order is cancelled, refunded, returned, marked fraudulent, or adjusted after purchase. + +Members are responsible for keeping their account email current. If a customer checks out as a guest, points may not be applied automatically. Support may help attach an eligible order to a member account after verification. + +Promotional rewards may have expiration dates, product exclusions, minimum order values, and stacking limitations. Support should check the campaign terms before promising reward reinstatement. + +Suspected abuse, repeated account creation, referral fraud, or reward manipulation must be escalated before credits are issued. diff --git a/data/policies/payment_policy.txt b/data/policies/payment_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..23ae8a8a09f97d78c8f11eadbe08b365c7f638bd --- /dev/null +++ b/data/policies/payment_policy.txt @@ -0,0 +1,13 @@ +Payment Policy + +The store accepts major credit cards, debit cards, Shop Pay, PayPal, and gift cards where available. Available payment methods may vary by country, currency, device, and checkout configuration. + +Failed payments are not captured by the store. A failed payment may still appear as a temporary bank authorization, but it should fall off automatically based on the customer's bank timeline. Support should explain that failed authorization holds are controlled by the bank and are not settled charges. + +If a customer reports a duplicate charge, support must request the order number, amount, payment method, transaction timestamp, and a screenshot that hides full card details. Duplicate charge reports should be escalated to human support for payment verification before any refund promise is made. + +Gift cards can be combined with another payment method when the gift card balance is lower than the order total. Gift cards cannot usually be converted to cash unless required by law. + +Currency conversion, foreign transaction fees, and bank fees are controlled by the payment provider or card issuer. The store cannot refund bank fees unless a support lead approves an exception. + +Orders with high-risk fraud indicators, mismatched billing details, repeated failed payment attempts, or chargeback threats must be escalated before fulfillment or refund action. diff --git a/data/policies/product_manual_1.txt b/data/policies/product_manual_1.txt new file mode 100644 index 0000000000000000000000000000000000000000..e7bd4dad6ee43c8d11a796182c178a86232c0ea2 --- /dev/null +++ b/data/policies/product_manual_1.txt @@ -0,0 +1,11 @@ +Product Manual 1: Smart Travel Backpack + +The Smart Travel Backpack includes padded laptop storage, weather-resistant exterior fabric, hidden security pocket, luggage pass-through strap, and USB charging pass-through. The USB port does not include a battery. Customers must connect their own power bank inside the backpack. + +Clean with a damp cloth and mild soap. Do not machine wash, bleach, tumble dry, iron, or dry clean. Let the backpack air dry fully before storing electronics inside. + +Do not overload the backpack beyond normal travel use. Heavy overload may strain zippers, seams, shoulder straps, and laptop compartments. Damage from overload or misuse is not covered by warranty. + +Warranty covers zipper failure, stitching defects, strap defects, and manufacturing issues for 1 year from delivery. Cosmetic dirt, scuffs, stains, accidental tears, water damage from submersion, and airline handling damage are not covered. + +If the USB pass-through does not work, ask the customer to test with another cable and power bank before opening a warranty claim. diff --git a/data/policies/product_manual_2.txt b/data/policies/product_manual_2.txt new file mode 100644 index 0000000000000000000000000000000000000000..1dcf5ccc557e89b26cedfe8f9914900d409c139f --- /dev/null +++ b/data/policies/product_manual_2.txt @@ -0,0 +1,11 @@ +Product Manual 2: Wireless Desk Lamp + +The Wireless Desk Lamp includes adjustable brightness, touch power control, rechargeable battery, USB-C charging, and warm-neutral light modes. Charge fully before first use. + +Use only a 5V USB-C adapter and the included cable or a certified equivalent. High-voltage fast chargers may cause overheating or battery damage. Do not use the lamp while it is wet or near water. + +Tap the power button to turn the lamp on or off. Long press the power button to adjust brightness. Some models cycle light temperature by double tapping the control area. + +If battery life is shorter than expected, fully charge the lamp, unplug it, and test on medium brightness. Very high brightness drains the battery faster. If the lamp does not charge, test another cable and adapter. + +Stop use and contact support if the battery overheats, swells, smells unusual, smokes, sparks, or leaks. Safety-related cases must be escalated immediately. diff --git a/data/policies/product_manual_3.txt b/data/policies/product_manual_3.txt new file mode 100644 index 0000000000000000000000000000000000000000..886929f0ac1233fcca6a7068a601c85e1370a26b --- /dev/null +++ b/data/policies/product_manual_3.txt @@ -0,0 +1,11 @@ +Product Manual 3: Fitness Water Bottle + +The Fitness Water Bottle includes a leak-resistant lid, carry loop, measurement marks, and removable silicone seal. Wash all parts before first use. + +The lid is top-rack dishwasher safe, but the bottle body should be hand washed to preserve exterior finish and measurement markings. Use mild soap and warm water. Do not use bleach, abrasive scrubbers, or harsh chemicals. + +Do not microwave, freeze while full, boil, or use with carbonated beverages unless the product page specifically allows it. Pressure buildup can cause leaks or lid release. + +If the bottle leaks, remove and reseat the silicone seal, check for cracks, and confirm the lid is fully tightened. Replacement lids or seals may be requested if the seal fails under warranty. + +Warranty covers manufacturing defects such as cracked lid on arrival, defective seal, or faulty carry loop. Damage from drops, impacts, misuse, odor from poor cleaning, or normal scratches is not covered. diff --git a/data/policies/refund_policy.txt b/data/policies/refund_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..02c598ed5388b26e1d0312ab764f3bb53aa9addf --- /dev/null +++ b/data/policies/refund_policy.txt @@ -0,0 +1,13 @@ +Refund Policy + +Customers may request a refund when an order is cancelled before fulfillment, when an eligible delivered item is returned in acceptable condition, or when a shipment is delayed by more than 7 calendar days beyond the promised delivery date. A refund request must include the order number, customer email, and a short explanation of the issue. + +For delayed shipments, support should first check the carrier tracking status, the promised delivery date, and whether the package is still moving through the carrier network. If the order is delayed by 7 days or less, the customer is not automatically eligible for a refund. In that case, provide the latest delivery estimate, apologize for the inconvenience, and keep the ticket open for follow-up. + +For delivered orders, refunds are approved only after the returned item is received and inspected. Items must be unused, complete, and in original packaging unless the refund is related to damage, defect, or store error. If an item is missing accessories or shows signs of use, support may offer a partial refund or escalate the case for human review. + +Refunds are issued to the original payment method within 5 to 10 business days after approval. Bank processing times may vary. Store credit may be offered when the customer requests it or when the original payment method is no longer available. + +Shipping fees are refundable only when the delay, incorrect shipment, or delivery failure was caused by the store or carrier. Shipping fees are not refunded when the customer entered an incorrect address, missed carrier delivery attempts, or refused delivery without prior approval. + +High-value orders, suspected fraud, duplicate refund requests, chargeback threats, or abusive customer messages must be escalated to a human support lead before any refund promise is made. diff --git a/data/policies/return_policy.txt b/data/policies/return_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0c03fe76e331748bef710e6b593c83444510a2f --- /dev/null +++ b/data/policies/return_policy.txt @@ -0,0 +1,13 @@ +Return Policy + +Customers may request a return within 30 days of delivery. The return window begins on the carrier delivery date, not the order date. Support should verify the order number, delivery date, product category, and reason for return before authorizing the request. + +Eligible items must be unused, clean, in original packaging, and include all manuals, accessories, tags, chargers, cables, and protective inserts. The customer should pack the item securely to prevent damage in transit. If the returned item is damaged because of poor return packaging, the refund may be reduced. + +Final sale, personalized, custom-made, opened hygiene-sensitive items, and downloadable products are not eligible for return unless they arrived damaged, defective, or incorrect. If the customer claims a defect, support should request clear photos or video showing the issue. + +Return labels may be provided for store errors, damaged items, incorrect items, or warranty-related returns. For preference-based returns such as wrong size, changed mind, or unwanted gift, the customer may be responsible for return shipping unless a promotion states otherwise. + +Once the returned item is received, inspection normally takes 2 to 4 business days. Approved refunds are sent to the original payment method. If an item fails inspection, support should explain the reason and escalate the ticket if the customer disputes the decision. + +International returns require human review because customs forms, duties, taxes, and return shipping cost vary by destination. diff --git a/data/policies/shipping_policy.txt b/data/policies/shipping_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..41271e809056abf9bc6d8d1aee453c191e9dcc25 --- /dev/null +++ b/data/policies/shipping_policy.txt @@ -0,0 +1,13 @@ +Shipping Policy + +Standard domestic shipping usually arrives within 3 to 7 business days after fulfillment. Expedited shipping usually arrives within 1 to 3 business days after fulfillment. Delivery estimates are calculated from the fulfillment date, not the order placement date. + +Orders are normally processed within 1 to 2 business days. During major sales, holidays, severe weather, or carrier disruptions, processing and transit may take longer. Support should avoid promising a guaranteed delivery date unless the carrier service explicitly includes one. + +Tracking updates may take up to 24 hours after the carrier receives the package. If tracking shows "label created" for less than 48 hours, ask the customer to allow additional carrier scan time. If tracking has no movement for more than 5 business days domestically, escalate the case for carrier investigation. + +Customers should verify the shipping address before checkout. If an order has not entered fulfillment, support may request an address update. Once an order has shipped, address changes are not guaranteed and may need to be handled directly with the carrier. + +Lost package claims require the order number, tracking number, delivery address, and any carrier delivery photo or proof of delivery. If tracking says delivered but the customer cannot find the package, ask them to check nearby entrances, mail rooms, household members, and building staff before escalating. + +Split shipments may arrive on different days. Support should check whether the order contains multiple tracking numbers before telling the customer an item is missing. diff --git a/data/policies/warranty_policy.txt b/data/policies/warranty_policy.txt new file mode 100644 index 0000000000000000000000000000000000000000..6735e9ad74e8579df82fc6863182eb31e3b29c45 --- /dev/null +++ b/data/policies/warranty_policy.txt @@ -0,0 +1,13 @@ +Warranty Policy + +Products include a 1 year limited warranty for manufacturing defects beginning on the delivery date. Warranty coverage applies to defects in materials, workmanship, electronics, stitching, seams, closures, charging ports, and other covered components described in the product manual. + +Warranty claims require proof of purchase, the order number, photos or video of the defect, and a description of how the issue occurred. Support should ask when the issue began and whether the product was used according to the product manual. + +Damage from misuse, accidents, improper cleaning, unauthorized repairs, modification, normal wear, cosmetic scratches, water exposure beyond stated product limits, or lost parts is not covered. + +Approved warranty resolutions may include troubleshooting, replacement parts, replacement product, store credit, repair instructions, or refund when replacement is not practical. Support should not promise a specific resolution until the claim is reviewed. + +Products purchased from unauthorized resellers may not qualify for warranty support. The customer may be asked for proof that the purchase came from an approved channel. + +Safety issues such as overheating batteries, smoke, exposed wires, broken glass, or sharp broken parts must be escalated immediately and the customer should be advised to stop using the product. diff --git a/data/tickets/ticket_0f53631577.txt b/data/tickets/ticket_0f53631577.txt new file mode 100644 index 0000000000000000000000000000000000000000..d6741c1df12c33b78c52ec205da4b899c41824d1 --- /dev/null +++ b/data/tickets/ticket_0f53631577.txt @@ -0,0 +1,3 @@ +{ + "response": "I've checked on the status of your order #9012. The order is still being processed and has not shipped yet. Since the delay is currently within our expected timeframe, I'd like to provide you with an update on the latest delivery estimate. Unfortunately, I don't have a new estimated delivery date at this time. I apologize for the inconvenience this has caused and I'll keep your ticket open for follow-up. If the delay exceeds 7 days beyond the promised delivery date of 2026-06-30, you may be eligible for a refund. I'll be happy to assist you further at that time." +} \ No newline at end of file diff --git a/data/tickets/ticket_87dcf4f9c5.txt b/data/tickets/ticket_87dcf4f9c5.txt new file mode 100644 index 0000000000000000000000000000000000000000..50354cc27de72773c111f0891c0d5cc8cccf744c --- /dev/null +++ b/data/tickets/ticket_87dcf4f9c5.txt @@ -0,0 +1,3 @@ +{ + "response": "I've checked on the status of your order #9012 and see that it's still being processed. The expected delivery date was June 29, 2026, and the promised delivery date is June 30, 2026. Since the delay is currently within our expected timeframe, I'd like to provide you with an update instead of a refund at this time. I apologize for the inconvenience this has caused and appreciate your patience. I'll keep your ticket open to follow up on the status of your order." +} \ No newline at end of file diff --git a/data/tickets/ticket_ad837d455c.txt b/data/tickets/ticket_ad837d455c.txt new file mode 100644 index 0000000000000000000000000000000000000000..27908c7661005aa3fbe8d2f4880b4b6624d6a32e --- /dev/null +++ b/data/tickets/ticket_ad837d455c.txt @@ -0,0 +1,3 @@ +{ + "response": "I've checked on your order #1004 and see that the payment failed. The bank charge you're seeing is likely a temporary authorization hold, which should fall off automatically based on your bank's timeline. This isn't a settled charge, and you won't be charged by our store. If you'd like to retry the payment, please ensure your card details and billing address are correct. If the issue persists, you can try an alternative payment method like a different card, Shop Pay, or PayPal. Please let me know if there's anything else I can help you with." +} \ No newline at end of file diff --git a/deployment/Dockerfile b/deployment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7d16566ce16f7ec009060f4b8bd697a64b3b6652 --- /dev/null +++ b/deployment/Dockerfile @@ -0,0 +1,20 @@ +FROM python:3.11-slim + +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 +ENV PIP_NO_CACHE_DIR=1 + +WORKDIR /app + +RUN apt-get update \ + && apt-get install -y --no-install-recommends build-essential curl \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . +RUN pip install --upgrade pip \ + && pip install -r requirements.txt + +COPY . . + +EXPOSE 8000 +CMD ["python", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/deployment/Dockerfile.frontend b/deployment/Dockerfile.frontend new file mode 100644 index 0000000000000000000000000000000000000000..c90e74e0ef412b775db78cd6f50783233b9a55ab --- /dev/null +++ b/deployment/Dockerfile.frontend @@ -0,0 +1,19 @@ +FROM python:3.11-slim + +ENV PYTHONDONTWRITEBYTECODE=1 +ENV PYTHONUNBUFFERED=1 +ENV PIP_NO_CACHE_DIR=1 +ENV STREAMLIT_SERVER_HEADLESS=true +ENV STREAMLIT_BROWSER_GATHER_USAGE_STATS=false + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --upgrade pip \ + && pip install -r requirements.txt + +COPY app ./app + +EXPOSE 8501 + +CMD ["python", "-m", "streamlit", "run", "app/frontend.py", "--server.address", "0.0.0.0", "--server.port", "8501"] diff --git a/deployment/docker-compose.yml b/deployment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..60be7aabb53de47a35ecc947f397a9fa90491ed0 --- /dev/null +++ b/deployment/docker-compose.yml @@ -0,0 +1,26 @@ +services: + api: + build: + context: .. + dockerfile: deployment/Dockerfile + env_file: + - ../.env + ports: + - "8000:8000" + volumes: + - ../data:/app/data + - ../logs:/app/logs + command: > + sh -c "python -m app.rag.ingest && + python -m uvicorn app.main:app --host 0.0.0.0 --port 8000" + + frontend: + build: + context: .. + dockerfile: deployment/Dockerfile.frontend + environment: + API_BASE_URL: http://api:8000 + ports: + - "8501:8501" + depends_on: + - api diff --git a/deployment/github_actions.yml b/deployment/github_actions.yml new file mode 100644 index 0000000000000000000000000000000000000000..13f02fd170bc7fb700985298f1e28858e719c38d --- /dev/null +++ b/deployment/github_actions.yml @@ -0,0 +1,20 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Install dependencies + run: pip install -r requirements.txt + - name: Run tests + run: pytest diff --git a/deployment/nginx.conf b/deployment/nginx.conf new file mode 100644 index 0000000000000000000000000000000000000000..b3aaa5762f1ba1f17481427a93a381ff3bc7f483 --- /dev/null +++ b/deployment/nginx.conf @@ -0,0 +1,19 @@ +events {} + +http { + upstream shopify_support_api { + server api:8000; + } + + server { + listen 80; + + location / { + proxy_pass http://shopify_support_api; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + } +} diff --git a/deployment/start-hf.sh b/deployment/start-hf.sh new file mode 100644 index 0000000000000000000000000000000000000000..e90a4d2483f49c2ecc6d7ed83ad05f8e332ecae8 --- /dev/null +++ b/deployment/start-hf.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -e + +python -m app.rag.ingest || echo "RAG ingest failed at startup; app will try lazy ingest on first retrieval." + +python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 & + +python -m streamlit run app/frontend.py \ + --server.address 0.0.0.0 \ + --server.port "${PORT:-7860}" \ + --server.headless true diff --git a/docs/report.md b/docs/report.md new file mode 100644 index 0000000000000000000000000000000000000000..285a7a338ae299c5b2bafd5b3c958ba8450204be --- /dev/null +++ b/docs/report.md @@ -0,0 +1,28 @@ +# Project Report + +## Objective + +Build an AI-powered business workflow automation prototype for Shopify customer support. + +## Architecture + +The platform exposes a FastAPI endpoint that receives customer tickets and runs a multi-agent workflow. The current implementation uses local deterministic fallbacks so the project works without paid API keys, while the `models` package contains clear extension points for Groq and Gemini clients. + +## Workflow + +1. Customer submits a ticket through `POST /api/tickets`. +2. Supervisor decides which agents should run. +3. Intent agent classifies the support intent and priority. +4. Order agent loads matching Shopify-style order data. +5. Policy agent retrieves relevant policy documents. +6. Reasoning agent creates a grounded customer response. +7. Validation agent checks whether policy context was used. +8. Escalation service routes low-confidence or unverifiable cases to a human. + +## Data + +Policy documents live in `data/policies`. Sample orders live in `data/orders/orders.json`. + +## Production Path + +Replace local model fallbacks with real Groq and Gemini SDK calls, replace sample order JSON with Shopify Admin API calls, persist tickets in a database, and deploy the FastAPI service behind Nginx using the Docker files in `deployment`. diff --git a/requirements.txt b/requirements.txt index c87f98eaa85f9f401536f866fd77d54d709f85f7..f910b2c136703c3feab3ed099985a7128559e422 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ - fastapi==0.115.14 uvicorn[standard]==0.35.0 pydantic==2.11.7 @@ -19,4 +18,3 @@ tokenizers==0.21.2 safetensors==0.5.3 scikit-learn==1.7.0 numpy==2.2.6 - diff --git a/tests/test_agents.py b/tests/test_agents.py new file mode 100644 index 0000000000000000000000000000000000000000..afc5e419a69daf80f5818c0daf5ee2b3d80ace10 --- /dev/null +++ b/tests/test_agents.py @@ -0,0 +1,14 @@ +from app.agents.intent_agent import IntentAgent +from app.agents.order_agent import OrderAgent + + +def test_intent_agent_detects_refund(): + result = IntentAgent().classify("My order #1234 is late and I want a refund") + assert result["intent"] == "refund_request" + assert result["priority"] == "high" + + +def test_order_agent_loads_sample_order(): + order = OrderAgent().fetch("Where is order #1234?") + assert order["order_id"] == "1234" + assert order["status"] == "delayed" diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..6f3efffcc2ac09971deb4639d30f6319b6bafa94 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,15 @@ +from fastapi.testclient import TestClient + +from app.main import app + + +def test_ticket_endpoint_returns_response(): + client = TestClient(app) + response = client.post( + "/api/tickets", + json={"customer_id": "cust_001", "message": "My order #1234 is delayed. Can I get a refund?"}, + ) + assert response.status_code == 200 + payload = response.json() + assert payload["ticket_id"].startswith("ticket_") + assert "response" in payload diff --git a/tests/test_rag.py b/tests/test_rag.py new file mode 100644 index 0000000000000000000000000000000000000000..b93abcb82d9f1a97492e80aa380fc9491ab4e947 --- /dev/null +++ b/tests/test_rag.py @@ -0,0 +1,7 @@ +from app.rag.retriever import retrieve_policies + + +def test_policy_retriever_finds_refund_policy(): + results = retrieve_policies("refund delayed shipment") + assert results + assert any("refund" in item["source"] for item in results)