Prerna43 commited on
Commit
80ef840
·
1 Parent(s): 70cc086

shopify_ai

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +14 -0
  2. .gitignore +11 -0
  3. Dockerfile +0 -1
  4. README.md +245 -19
  5. app/__init__.py +1 -0
  6. app/agents/__init__.py +1 -0
  7. app/agents/intent_agent.py +54 -0
  8. app/agents/order_agent.py +11 -0
  9. app/agents/policy_agent.py +7 -0
  10. app/agents/reasoning_agent.py +88 -0
  11. app/agents/supervisor_agent.py +15 -0
  12. app/agents/validation_agent.py +17 -0
  13. app/api/__init__.py +1 -0
  14. app/api/routes.py +44 -0
  15. app/api/schemas.py +27 -0
  16. app/frontend.py +51 -0
  17. app/main.py +18 -0
  18. app/models/__init__.py +1 -0
  19. app/models/gemini_client.py +50 -0
  20. app/models/groq_client.py +53 -0
  21. app/models/model_router.py +11 -0
  22. app/rag/__init__.py +1 -0
  23. app/rag/embeddings.py +46 -0
  24. app/rag/ingest.py +103 -0
  25. app/rag/retriever.py +48 -0
  26. app/rag/vector_store.py +34 -0
  27. app/services/__init__.py +1 -0
  28. app/services/escalation_service.py +13 -0
  29. app/services/shopify_service.py +19 -0
  30. app/services/ticket_service.py +21 -0
  31. app/utils/__init__.py +1 -0
  32. app/utils/config.py +33 -0
  33. app/utils/helpers.py +15 -0
  34. app/utils/logger.py +12 -0
  35. app/workflows/__init__.py +1 -0
  36. app/workflows/langgraph_workflow.py +63 -0
  37. data/orders/orders.json +526 -0
  38. data/policies/cancellation_policy.txt +13 -0
  39. data/policies/exchange_policy.txt +13 -0
  40. data/policies/faq_1.txt +7 -0
  41. data/policies/faq_2.txt +7 -0
  42. data/policies/faq_3.txt +7 -0
  43. data/policies/faq_4.txt +7 -0
  44. data/policies/gift_card_policy.txt +13 -0
  45. data/policies/international_shipping.txt +13 -0
  46. data/policies/membership_policy.txt +13 -0
  47. data/policies/payment_policy.txt +13 -0
  48. data/policies/product_manual_1.txt +11 -0
  49. data/policies/product_manual_2.txt +11 -0
  50. data/policies/product_manual_3.txt +11 -0
.dockerignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .agents
3
+ .codex
4
+ __pycache__/
5
+ *.py[cod]
6
+ .pytest_cache/
7
+ .ruff_cache/
8
+ .mypy_cache/
9
+ venv/
10
+ env/
11
+ logs/
12
+ data/tickets/
13
+ data/embeddings/
14
+ .env
.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ .mypy_cache/
7
+ env/
8
+ venv/
9
+ logs/*.log
10
+ data/tickets/*.json
11
+ data/embeddings/
Dockerfile CHANGED
@@ -1,4 +1,3 @@
1
-
2
  FROM python:3.11-slim
3
 
4
  ENV PYTHONDONTWRITEBYTECODE=1
 
 
1
  FROM python:3.11-slim
2
 
3
  ENV PYTHONDONTWRITEBYTECODE=1
README.md CHANGED
@@ -1,19 +1,245 @@
1
- ---
2
- title: Shopify AI
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: Streamlit template space
12
- ---
13
-
14
- # Welcome to Streamlit!
15
-
16
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
17
-
18
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
19
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shopify Customer Support Intelligence Agent
2
+
3
+
4
+ **Overview:**
5
+ - **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.
6
+
7
+ **Key Features:**
8
+ - **Multi-agent architecture:** intent, order, policy, reasoning, validation, supervisor agents.
9
+ - **RAG support:** embeddings, retriever, and vector store for knowledge search.
10
+ - **Pluggable models:** adapters for Gemini, Groq, or other LLMs.
11
+ - **Services integration:** Shopify API, ticketing, escalation logic.
12
+
13
+ **Architecture Flow**
14
+
15
+ ```mermaid
16
+ flowchart TD
17
+ User[Customer / Support Agent] -->|UI / Ticket| Frontend[Frontend / Streamlit or Web UI]
18
+ Frontend --> API[API (FastAPI)]
19
+ API --> Orchestrator[Supervisor Agent / Orchestrator]
20
+ Orchestrator --> Intent[Intent Agent]
21
+ Orchestrator --> Order[Order Agent]
22
+ Orchestrator --> Policy[Policy Agent]
23
+ Orchestrator --> Reasoning[Reasoning Agent]
24
+ Orchestrator --> Validation[Validation Agent]
25
+ Policy --> RAG[RAG Retriever]
26
+ RAG --> VectorStore[Vector Store / Embeddings]
27
+ Orchestrator --> Models[Model Router -> LLM Clients]
28
+ Models --> Gemini[Gemini Client]
29
+ Models --> Groq[Groq Client]
30
+ Orchestrator --> Services[Services Layer]
31
+ Services --> Shopify[Shopify Service]
32
+ Services --> TicketService[Ticket Service & Escalation]
33
+ TicketService -->|Create/Update| Data[Data / Logs]
34
+ classDef infra fill:#f9f,stroke:#333,stroke-width:1px;
35
+ VectorStore,Data,Shopify class infra
36
+ ```
37
+
38
+ Quick links:
39
+ - Project entry: `app/main.py`
40
+ - Frontend: `app/frontend.py`
41
+ - Agents: `app/agents/`
42
+ - RAG: `rag/`
43
+ - Models: `models/`
44
+
45
+ **Quickstart (Development)**
46
+
47
+ Prerequisites:
48
+ - Python 3.10+ (use virtualenv)
49
+ - pip
50
+
51
+ Install dependencies:
52
+
53
+ ```bash
54
+ python -m venv .venv
55
+ source .venv/bin/activate # macOS / Linux
56
+ .venv\Scripts\Activate # Windows PowerShell
57
+ pip install -r requirements.txt
58
+ ```
59
+
60
+ Run the API locally (example):
61
+
62
+ ```bash
63
+ python -m app.main
64
+ # or if using uvicorn/fastapi:
65
+ # uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
66
+ ```
67
+
68
+ Run tests:
69
+
70
+ ```bash
71
+ pytest -q
72
+ ```
73
+
74
+ **Docker**
75
+
76
+ Use this minimal `Dockerfile` as a template:
77
+
78
+ ```dockerfile
79
+ FROM python:3.11-slim
80
+ WORKDIR /app
81
+ COPY requirements.txt ./
82
+ RUN pip install --no-cache-dir -r requirements.txt
83
+ COPY . /app
84
+ ENV PYTHONUNBUFFERED=1
85
+ EXPOSE 8000
86
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
87
+ ```
88
+
89
+ Build and run locally:
90
+
91
+ ```bash
92
+ docker build -t shopify_ai:latest .
93
+ docker run --rm -p 8000:8000 \
94
+ -e OPENAI_API_KEY="your_key" \
95
+ -v $(pwd)/data:/app/data \
96
+ shopify_ai:latest
97
+ ```
98
+
99
+ docker-compose (example) `docker-compose.yml` snippet:
100
+
101
+ ```yaml
102
+ version: '3.8'
103
+ services:
104
+ web:
105
+ build: .
106
+ ports:
107
+ - "8000:8000"
108
+ environment:
109
+ - OPENAI_API_KEY=${OPENAI_API_KEY}
110
+ volumes:
111
+ - ./:/app
112
+ ```
113
+
114
+ **Streamlit (optional UI)**
115
+
116
+ If you want a quick interactive UI using Streamlit, create a simple `streamlit_app.py` (example):
117
+
118
+ ```python
119
+ import streamlit as st
120
+ st.title('Shopify AI — Support Assistant')
121
+ question = st.text_input('Customer question')
122
+ if st.button('Ask'):
123
+ st.write('Sending to API...')
124
+ # call your API endpoint here, e.g. requests.post('http://localhost:8000/route', json={...})
125
+
126
+ # Run: `streamlit run streamlit_app.py`
127
+ ```
128
+
129
+ Run Streamlit:
130
+
131
+ ```bash
132
+ pip install streamlit
133
+ streamlit run streamlit_app.py
134
+ ```
135
+
136
+ **Git / GitHub: commit & push commands**
137
+
138
+ Set up and push to GitHub (replace `USERNAME/REPO`):
139
+
140
+ ```bash
141
+ git init
142
+ git add .
143
+ git commit -m "chore: initial project import"
144
+ git branch -M main
145
+ git remote add origin git@github.com:USERNAME/REPO.git
146
+ git push -u origin main
147
+ ```
148
+
149
+ If you prefer HTTPS remote:
150
+
151
+ ```bash
152
+ git remote add origin https://github.com/USERNAME/REPO.git
153
+ git push -u origin main
154
+ ```
155
+
156
+ **Repository layout**
157
+
158
+ - `app/` — application entrypoints and agents (`app/main.py`, `app/frontend.py`, `app/agents/`)
159
+ - `api/` — route definitions and request/response schemas
160
+ - `models/` — model clients and router
161
+ - `rag/` — embeddings, retriever, vector store
162
+ - `services/` — shopify, ticketing, escalation
163
+ - `data/` — embeddings, policies, tickets, orders
164
+ - `tests/` — unit/integration tests
165
+
166
+ **Environment & Secrets**
167
+ - Store secrets in environment variables. Example: `OPENAI_API_KEY`, `SHOPIFY_API_KEY`, `SHOPIFY_SECRET`.
168
+ - Consider using `.env` and `python-dotenv` in development.
169
+
170
+ **Contributing**
171
+ - Please open issues and PRs. Follow the repo's coding style and testing.
172
+
173
+ **License**
174
+ - Add a license file (e.g., MIT) if you plan to open-source this repository.
175
+
176
+ ----
177
+
178
+ If you'd like, I can also create the `Dockerfile` and a `streamlit_app.py` in the repo now — tell me to proceed.
179
+
180
+ This prototype automates Shopify-style customer support tickets with a multi-agent workflow:
181
+
182
+ - Supervisor agent decides which steps to run.
183
+ - Intent agent classifies the ticket.
184
+ - Order agent retrieves sample Shopify order data from `data/orders/orders.json`.
185
+ - Policy agent retrieves relevant policy text from `data/policies`.
186
+ - Reasoning agent generates a grounded customer response.
187
+ - Validation agent checks policy grounding.
188
+ - Escalation service sends low-confidence or unsafe cases to human support.
189
+
190
+
191
+ ## Run Locally
192
+
193
+
194
+ ```bash
195
+ pip install -r requirements.txt
196
+ python -m app.rag.ingest
197
+ uvicorn app.main:app --reload
198
+ ```
199
+
200
+ Open `http://127.0.0.1:8000/docs` for the API docs.
201
+
202
+ Run the Streamlit frontend in a second terminal:
203
+
204
+ ```bash
205
+ streamlit run app/frontend.py
206
+ ```
207
+
208
+ ## Example Request
209
+
210
+ ```bash
211
+ curl -X POST http://127.0.0.1:8000/api/tickets \
212
+ -H "Content-Type: application/json" \
213
+ -d '{"customer_id":"cust_001","message":"My order #1234 is delayed. Can I get a refund?"}'
214
+ ```
215
+
216
+ The project runs with deterministic local fallbacks by default. Add API keys in `.env` when wiring real Groq, Gemini, and Shopify integrations.
217
+
218
+ ## RAG Pipeline
219
+
220
+ The policy RAG flow uses:
221
+
222
+ - `RecursiveCharacterTextSplitter` for chunking policy, FAQ, and product manual files.
223
+ - `BAAI/bge-small-en-v1.5` from Hugging Face through `sentence-transformers`.
224
+ - Persistent Chroma DB stored at `data/embeddings/chroma`.
225
+ - Metadata per chunk, including source file, document type, chunk index, path, and character count.
226
+ - `BAAI/bge-reranker-base` as a cross-encoder reranker after vector retrieval.
227
+
228
+ Build or rebuild the vector DB:
229
+
230
+ ```bash
231
+ python -m app.rag.ingest
232
+ ```
233
+
234
+ Check the vector DB from the API:
235
+
236
+ ```bash
237
+ curl http://127.0.0.1:8000/api/rag/status
238
+ ```
239
+
240
+ Rebuild from the API:
241
+
242
+ ```bash
243
+ curl -X POST http://127.0.0.1:8000/api/rag/ingest
244
+ ```
245
+ >>>>>>> 4c7223c (shopify_ai)
app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Shopify customer support intelligence platform."""
app/agents/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Agent implementations."""
app/agents/intent_agent.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.models.model_router import ModelRouter
2
+
3
+
4
+ class IntentAgent:
5
+ INTENT_KEYWORDS = {
6
+ "refund_request": ["refund", "money back", "reimburse"],
7
+ "return_request": ["return", "send back"],
8
+ "shipping_status": ["where", "shipping", "shipment", "tracking", "arrived", "delivery", "delayed"],
9
+ "payment_issue": ["payment", "card", "charged", "failed"],
10
+ "cancellation_request": ["cancel", "cancellation"],
11
+ "exchange_request": ["exchange", "replace", "size"],
12
+ "warranty_claim": ["warranty", "repair", "defective", "broken"],
13
+ }
14
+
15
+ def __init__(self, router: ModelRouter | None = None):
16
+ self.router = router or ModelRouter()
17
+
18
+ def classify(self, message: str) -> dict:
19
+ if self.router.intent_model.api_key:
20
+ try:
21
+ return self._classify_with_groq(message)
22
+ except Exception:
23
+ pass
24
+ return self._classify_locally(message)
25
+
26
+ def _classify_with_groq(self, message: str) -> dict:
27
+ prompt = f"""
28
+ Classify this Shopify customer support ticket.
29
+ Return only JSON with keys: intent, priority, confidence.
30
+ Allowed intents: refund_request, return_request, shipping_status, payment_issue,
31
+ cancellation_request, exchange_request, warranty_claim, general_support.
32
+ Allowed priority values: low, normal, high.
33
+
34
+ Message: {message}
35
+ """
36
+ result = self.router.intent_model.complete_json(
37
+ prompt,
38
+ system="You are an intent classification agent for ecommerce customer support.",
39
+ )
40
+ return {
41
+ "intent": result.get("intent", "general_support"),
42
+ "priority": result.get("priority", "normal"),
43
+ "confidence": float(result.get("confidence", 0.7)),
44
+ }
45
+
46
+ def _classify_locally(self, message: str) -> dict:
47
+ lowered = message.lower()
48
+ intent = "general_support"
49
+ for candidate, keywords in self.INTENT_KEYWORDS.items():
50
+ if any(keyword in lowered for keyword in keywords):
51
+ intent = candidate
52
+ break
53
+ priority = "high" if any(word in lowered for word in ["urgent", "angry", "refund", "failed", "broken"]) else "normal"
54
+ return {"intent": intent, "priority": priority, "confidence": 0.86 if intent != "general_support" else 0.62}
app/agents/order_agent.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.services.shopify_service import ShopifyService
2
+ from app.utils.helpers import extract_order_id
3
+
4
+
5
+ class OrderAgent:
6
+ def __init__(self, service: ShopifyService | None = None):
7
+ self.service = service or ShopifyService()
8
+
9
+ def fetch(self, message: str, order_id: str | None = None) -> dict | None:
10
+ resolved_order_id = order_id or extract_order_id(message)
11
+ return self.service.get_order(resolved_order_id)
app/agents/policy_agent.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from app.rag.retriever import retrieve_policies
2
+
3
+
4
+ class PolicyAgent:
5
+ def retrieve(self, message: str, intent: str | None = None) -> list[dict]:
6
+ query = f"{intent or ''} {message}".strip()
7
+ return retrieve_policies(query, k=4)
app/agents/reasoning_agent.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.models.model_router import ModelRouter
2
+
3
+
4
+ class ReasoningAgent:
5
+ def __init__(self, router: ModelRouter | None = None):
6
+ self.router = router or ModelRouter()
7
+
8
+ def respond(self, message: str, intent: dict, order: dict | None, policies: list[dict]) -> dict:
9
+ if self.router.reasoning_model.api_key:
10
+ try:
11
+ return self._respond_with_groq(message, intent, order, policies)
12
+ except Exception:
13
+ pass
14
+ return self._respond_locally(message, intent, order, policies)
15
+
16
+ def _respond_with_groq(self, message: str, intent: dict, order: dict | None, policies: list[dict]) -> dict:
17
+ policy_context = "\n\n".join(
18
+ f"Source: {policy['source']}\n{policy['content']}" for policy in policies
19
+ )
20
+ prompt = f"""
21
+ Generate a Shopify customer support response using the order and policy context.
22
+ Return only the final customer-facing reply as normal plain text.
23
+ Do not return JSON, markdown tables, internal analysis, confidence values, or policy metadata.
24
+ Do not promise refunds, replacements, cancellations, or payment actions unless the policy clearly allows it.
25
+
26
+ Customer message:
27
+ {message}
28
+
29
+ Intent:
30
+ {intent}
31
+
32
+ Order:
33
+ {order}
34
+
35
+ Policy context:
36
+ {policy_context}
37
+ """
38
+ response = self.router.reasoning_model.complete(
39
+ prompt,
40
+ system="You are a careful ecommerce support reasoning agent.",
41
+ ).strip()
42
+ confidence = min(0.95, intent.get("confidence", 0.7) + (0.08 if order else -0.08) + (0.06 if policies else -0.06))
43
+ return {
44
+ "analysis": self._analysis_summary(intent, order, policies, "groq"),
45
+ "response": response,
46
+ "confidence": round(confidence, 2),
47
+ }
48
+
49
+ def _respond_locally(self, message: str, intent: dict, order: dict | None, policies: list[dict]) -> dict:
50
+ intent_name = intent.get("intent", "general_support")
51
+ policy_hint = policies[0]["content"].splitlines()[0] if policies else "Use store support policy."
52
+ order_text = self._order_summary(order)
53
+ response = self._compose_response(intent_name, order, policy_hint)
54
+ confidence = min(0.95, intent.get("confidence", 0.6) + (0.08 if order else -0.08) + (0.06 if policies else -0.06))
55
+ return {
56
+ "analysis": self._analysis_summary(intent, order, policies, "local"),
57
+ "response": response,
58
+ "confidence": round(confidence, 2),
59
+ }
60
+
61
+ def _analysis_summary(self, intent: dict, order: dict | None, policies: list[dict], mode: str) -> str:
62
+ intent_name = intent.get("intent", "general_support")
63
+ order_text = self._order_summary(order)
64
+ policy_sources = ", ".join(policy["source"] for policy in policies) if policies else "none"
65
+ return f"mode={mode}; intent={intent_name}; {order_text}; policy_sources={policy_sources}"
66
+
67
+ def _order_summary(self, order: dict | None) -> str:
68
+ if not order:
69
+ return "No matching order was found."
70
+ return f"Order {order['order_id']} is {order['status']} with delivery estimate {order.get('expected_delivery')}."
71
+
72
+ def _compose_response(self, intent_name: str, order: dict | None, policy_hint: str) -> str:
73
+ greeting = "Thanks for reaching out. "
74
+ if not order:
75
+ 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."
76
+ if intent_name == "refund_request":
77
+ return (
78
+ greeting
79
+ + f"I checked order #{order['order_id']}. Its current status is {order['status']} and the expected delivery date is "
80
+ + 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."
81
+ )
82
+ if intent_name == "shipping_status":
83
+ return (
84
+ greeting
85
+ + f"Order #{order['order_id']} is currently {order['status']}. Tracking: {order.get('tracking_number')}. "
86
+ + f"Expected delivery is {order.get('expected_delivery')}."
87
+ )
88
+ 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."
app/agents/supervisor_agent.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class SupervisorAgent:
2
+ def plan(self, message: str, order_id: str | None = None) -> dict:
3
+ lowered = message.lower()
4
+ needs_order = bool(order_id) or any(word in lowered for word in ["order", "shipment", "tracking", "delivery"])
5
+ needs_policy = any(
6
+ word in lowered
7
+ for word in ["refund", "return", "shipping", "payment", "cancel", "exchange", "warranty", "gift"]
8
+ )
9
+ return {
10
+ "run_intent_agent": True,
11
+ "run_order_agent": needs_order,
12
+ "run_policy_agent": needs_policy or True,
13
+ "run_reasoning_agent": True,
14
+ "run_validation_agent": True,
15
+ }
app/agents/validation_agent.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.models.model_router import ModelRouter
2
+
3
+
4
+ class ValidationAgent:
5
+ def __init__(self, router: ModelRouter | None = None):
6
+ self.router = router or ModelRouter()
7
+
8
+ def validate(self, response: str, policies: list[dict]) -> dict:
9
+ context = "\n\n".join(policy["content"] for policy in policies)
10
+ try:
11
+ result = self.router.validation_model.validate(response, context)
12
+ except Exception as exc:
13
+ result = {
14
+ "valid": bool(context.strip()) and len(response.strip()) > 20,
15
+ "issues": [f"Gemini validation unavailable; used local fallback. {type(exc).__name__}"],
16
+ }
17
+ return {"valid": bool(result.get("valid")), "issues": result.get("issues", [])}
app/api/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """API package."""
app/api/routes.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter
2
+ from fastapi.responses import PlainTextResponse
3
+
4
+ from app.api.schemas import TicketRequest, TicketResponse
5
+ from app.rag.ingest import ingest_policies
6
+ from app.rag.vector_store import collection_count
7
+ from app.workflows.langgraph_workflow import CustomerSupportWorkflow
8
+
9
+ router = APIRouter(prefix="/api", tags=["support"])
10
+ workflow = CustomerSupportWorkflow()
11
+
12
+
13
+ @router.get("/health")
14
+ def health() -> dict:
15
+ return {"status": "ok"}
16
+
17
+
18
+ @router.get("/rag/status")
19
+ def rag_status() -> dict:
20
+ return {"collection_count": collection_count()}
21
+
22
+
23
+ @router.post("/rag/ingest")
24
+ def ingest_rag() -> dict:
25
+ return ingest_policies(reset=True)
26
+
27
+
28
+ @router.post("/tickets", response_model=TicketResponse)
29
+ def submit_ticket(request: TicketRequest) -> dict:
30
+ return workflow.run(
31
+ customer_id=request.customer_id,
32
+ message=request.message,
33
+ order_id=request.order_id,
34
+ )
35
+
36
+
37
+ @router.post("/tickets/text", response_class=PlainTextResponse)
38
+ def submit_ticket_text(request: TicketRequest) -> str:
39
+ result = workflow.run(
40
+ customer_id=request.customer_id,
41
+ message=request.message,
42
+ order_id=request.order_id,
43
+ )
44
+ return result["response"]
app/api/schemas.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class TicketRequest(BaseModel):
7
+ customer_id: str = Field(..., examples=["cust_001"])
8
+ message: str = Field(..., examples=["My order #1234 has not arrived. Can I get a refund?"])
9
+ order_id: str | None = Field(default=None, examples=["1234"])
10
+
11
+
12
+ class AgentTrace(BaseModel):
13
+ supervisor: dict[str, Any]
14
+ intent: dict[str, Any]
15
+ order: dict[str, Any] | None
16
+ policies: list[dict[str, Any]]
17
+ reasoning: dict[str, Any]
18
+ validation: dict[str, Any]
19
+
20
+
21
+ class TicketResponse(BaseModel):
22
+ ticket_id: str
23
+ response: str
24
+ confidence: float
25
+ escalated: bool
26
+ escalation_reason: str | None = None
27
+ trace: AgentTrace
app/frontend.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import httpx
4
+ import streamlit as st
5
+
6
+
7
+ API_BASE_URL = os.getenv("API_BASE_URL", "http://127.0.0.1:8000")
8
+
9
+
10
+ st.set_page_config(page_title="Shopify Support AI", page_icon="AI", layout="centered")
11
+
12
+ st.title("Shopify Support AI")
13
+
14
+ customer_id = st.text_input("Customer ID", value="cust_001")
15
+ order_id = st.text_input("Order ID", value="1234")
16
+ message = st.text_area(
17
+ "Customer message",
18
+ value="My order #1234 is delayed. Can I get a refund?",
19
+ height=140,
20
+ )
21
+ show_debug = st.checkbox("Show agent debug details", value=False)
22
+
23
+ if st.button("Submit ticket", type="primary"):
24
+ payload = {
25
+ "customer_id": customer_id,
26
+ "message": message,
27
+ "order_id": order_id or None,
28
+ }
29
+
30
+ try:
31
+ with httpx.Client(timeout=30) as client:
32
+ response = client.post(f"{API_BASE_URL}/api/tickets", json=payload)
33
+ response.raise_for_status()
34
+ data = response.json()
35
+ except httpx.HTTPError as exc:
36
+ st.error(f"Backend request failed: {exc}")
37
+ else:
38
+ st.subheader("AI Response")
39
+ st.write(data["response"])
40
+
41
+ if show_debug:
42
+ col1, col2, col3 = st.columns(3)
43
+ col1.metric("Ticket", data["ticket_id"])
44
+ col2.metric("Confidence", data["confidence"])
45
+ col3.metric("Escalated", "Yes" if data["escalated"] else "No")
46
+
47
+ if data.get("escalation_reason"):
48
+ st.warning(data["escalation_reason"])
49
+
50
+ with st.expander("Agent trace"):
51
+ st.json(data["trace"])
app/main.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+
3
+ from app.api.routes import router
4
+ from app.utils.config import get_settings
5
+
6
+
7
+ def create_app() -> FastAPI:
8
+ settings = get_settings()
9
+ app = FastAPI(
10
+ title=settings.app_name,
11
+ version="0.1.0",
12
+ description="Agentic Shopify customer support prototype with policy RAG and escalation.",
13
+ )
14
+ app.include_router(router)
15
+ return app
16
+
17
+
18
+ app = create_app()
app/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Model client package."""
app/models/gemini_client.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+
4
+ import httpx
5
+
6
+ from app.utils.logger import get_logger
7
+
8
+ logger = get_logger(__name__)
9
+
10
+
11
+ class GeminiClient:
12
+ def __init__(self, api_key: str | None = None, model: str = "gemini-1.5-flash"):
13
+ self.api_key = api_key
14
+ self.model = model
15
+
16
+ def validate(self, response: str, context: str) -> dict:
17
+ if not self.api_key:
18
+ logger.info("Gemini API key not configured; using local validation.")
19
+ has_policy_context = bool(context.strip())
20
+ return {
21
+ "valid": has_policy_context and len(response.strip()) > 20,
22
+ "issues": [] if has_policy_context else ["No policy context was supplied."],
23
+ }
24
+
25
+ prompt = f"""
26
+ Validate this customer support response against the policy context.
27
+ Return only JSON with keys: valid (boolean), issues (array of strings).
28
+
29
+ Policy context:
30
+ {context}
31
+
32
+ Customer response:
33
+ {response}
34
+ """
35
+ api_response = httpx.post(
36
+ f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent",
37
+ params={"key": self.api_key},
38
+ json={"contents": [{"parts": [{"text": prompt}]}]},
39
+ timeout=45,
40
+ )
41
+ api_response.raise_for_status()
42
+ text = api_response.json()["candidates"][0]["content"]["parts"][0]["text"]
43
+ return self._parse_json(text)
44
+
45
+ def _parse_json(self, text: str) -> dict:
46
+ cleaned = text.strip()
47
+ fenced = re.search(r"```(?:json)?\s*(.*?)```", cleaned, flags=re.DOTALL)
48
+ if fenced:
49
+ cleaned = fenced.group(1).strip()
50
+ return json.loads(cleaned)
app/models/groq_client.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+
3
+ import httpx
4
+
5
+ from app.utils.logger import get_logger
6
+
7
+ logger = get_logger(__name__)
8
+
9
+
10
+ class GroqClient:
11
+ def __init__(
12
+ self,
13
+ api_key: str | None = None,
14
+ model: str = "llama-3.3-70b-versatile",
15
+ base_url: str = "https://api.groq.com/openai/v1",
16
+ ):
17
+ self.api_key = api_key
18
+ self.model = model
19
+ self.base_url = base_url
20
+
21
+ def complete(self, prompt: str, system: str | None = None) -> str:
22
+ if not self.api_key:
23
+ logger.info("Groq API key not configured; using deterministic local response.")
24
+ return prompt
25
+
26
+ messages = []
27
+ if system:
28
+ messages.append({"role": "system", "content": system})
29
+ messages.append({"role": "user", "content": prompt})
30
+
31
+ payload = {
32
+ "model": self.model,
33
+ "messages": messages,
34
+ "temperature": 0.2,
35
+ }
36
+ if "json" in prompt.lower():
37
+ payload["response_format"] = {"type": "json_object"}
38
+
39
+ response = httpx.post(
40
+ f"{self.base_url}/chat/completions",
41
+ headers={
42
+ "Authorization": f"Bearer {self.api_key}",
43
+ "Content-Type": "application/json",
44
+ },
45
+ json=payload,
46
+ timeout=45,
47
+ )
48
+ response.raise_for_status()
49
+ data = response.json()
50
+ return data["choices"][0]["message"]["content"]
51
+
52
+ def complete_json(self, prompt: str, system: str | None = None) -> dict:
53
+ return json.loads(self.complete(prompt, system))
app/models/model_router.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.models.gemini_client import GeminiClient
2
+ from app.models.groq_client import GroqClient
3
+ from app.utils.config import get_settings
4
+
5
+
6
+ class ModelRouter:
7
+ def __init__(self):
8
+ settings = get_settings()
9
+ self.intent_model = GroqClient(settings.groq_api_key, "llama-3.1-8b-instant")
10
+ self.reasoning_model = GroqClient(settings.groq_api_key, "llama-3.3-70b-versatile")
11
+ self.validation_model = GeminiClient(settings.gemini_api_key or settings.google_api_key, "gemini-1.5-flash")
app/rag/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Retrieval package."""
app/rag/embeddings.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+
3
+ from chromadb import Documents, EmbeddingFunction, Embeddings
4
+ from sentence_transformers import CrossEncoder, SentenceTransformer
5
+
6
+ from app.utils.config import get_settings
7
+
8
+
9
+ QUERY_PREFIX = "Represent this sentence for searching relevant passages: "
10
+
11
+
12
+ @lru_cache
13
+ def get_embedding_model() -> SentenceTransformer:
14
+ settings = get_settings()
15
+ return SentenceTransformer(settings.embedding_model_name)
16
+
17
+
18
+ @lru_cache
19
+ def get_reranker_model() -> CrossEncoder:
20
+ settings = get_settings()
21
+ return CrossEncoder(settings.reranker_model_name)
22
+
23
+
24
+ def embed_documents(texts: list[str]) -> list[list[float]]:
25
+ model = get_embedding_model()
26
+ vectors = model.encode(texts, normalize_embeddings=True, show_progress_bar=False)
27
+ return vectors.tolist()
28
+
29
+
30
+ def embed_queries(texts: list[str]) -> list[list[float]]:
31
+ prefixed = [QUERY_PREFIX + text for text in texts]
32
+ return embed_documents(prefixed)
33
+
34
+
35
+ class BGEEmbeddingFunction(EmbeddingFunction):
36
+ def __call__(self, input: Documents) -> Embeddings:
37
+ return embed_documents(list(input))
38
+
39
+
40
+ def rerank(query: str, documents: list[str]) -> list[float]:
41
+ if not documents:
42
+ return []
43
+ model = get_reranker_model()
44
+ pairs = [(query, document) for document in documents]
45
+ scores = model.predict(pairs, show_progress_bar=False)
46
+ return [float(score) for score in scores]
app/rag/ingest.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ from pathlib import Path
3
+
4
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
5
+
6
+ from app.utils.config import get_settings
7
+ from app.rag.vector_store import get_policy_collection, reset_vector_store
8
+
9
+
10
+ def load_policy_documents(policy_dir: Path | None = None) -> list[dict]:
11
+ directory = policy_dir or get_settings().policy_dir
12
+ documents: list[dict] = []
13
+ for path in sorted(directory.glob("*.txt")):
14
+ content = path.read_text(encoding="utf-8").strip()
15
+ if content:
16
+ documents.append(
17
+ {
18
+ "source": path.name,
19
+ "path": str(path),
20
+ "document_type": infer_document_type(path.name),
21
+ "text": content,
22
+ }
23
+ )
24
+ return documents
25
+
26
+
27
+ def infer_document_type(filename: str) -> str:
28
+ if filename.startswith("faq_"):
29
+ return "faq"
30
+ if filename.startswith("product_manual_"):
31
+ return "product_manual"
32
+ if "policy" in filename or "shipping" in filename:
33
+ return "policy"
34
+ return "knowledge_base"
35
+
36
+
37
+ def build_text_splitter() -> RecursiveCharacterTextSplitter:
38
+ settings = get_settings()
39
+ return RecursiveCharacterTextSplitter(
40
+ chunk_size=settings.rag_chunk_size,
41
+ chunk_overlap=settings.rag_chunk_overlap,
42
+ separators=["\n\n", "\n", ". ", " ", ""],
43
+ )
44
+
45
+
46
+ def chunk_documents(documents: list[dict]) -> list[dict]:
47
+ splitter = build_text_splitter()
48
+ chunks: list[dict] = []
49
+ for document in documents:
50
+ split_texts = splitter.split_text(document["text"])
51
+ total_chunks = len(split_texts)
52
+ for index, text in enumerate(split_texts):
53
+ chunk_id = stable_chunk_id(document["source"], index, text)
54
+ chunks.append(
55
+ {
56
+ "id": chunk_id,
57
+ "text": text,
58
+ "metadata": {
59
+ "source": document["source"],
60
+ "path": document["path"],
61
+ "document_type": document["document_type"],
62
+ "chunk_index": index,
63
+ "chunk_count": total_chunks,
64
+ "char_count": len(text),
65
+ },
66
+ }
67
+ )
68
+ return chunks
69
+
70
+
71
+ def stable_chunk_id(source: str, index: int, text: str) -> str:
72
+ digest = hashlib.sha1(f"{source}:{index}:{text}".encode("utf-8")).hexdigest()[:16]
73
+ return f"{Path(source).stem}-{index}-{digest}"
74
+
75
+
76
+ def ingest_policies(reset: bool = True) -> dict:
77
+ if reset:
78
+ reset_vector_store()
79
+
80
+ documents = load_policy_documents()
81
+ chunks = chunk_documents(documents)
82
+ collection = get_policy_collection()
83
+
84
+ if chunks:
85
+ collection.upsert(
86
+ ids=[chunk["id"] for chunk in chunks],
87
+ documents=[chunk["text"] for chunk in chunks],
88
+ metadatas=[chunk["metadata"] for chunk in chunks],
89
+ )
90
+
91
+ return {
92
+ "documents": len(documents),
93
+ "chunks": len(chunks),
94
+ "collection_count": collection.count(),
95
+ }
96
+
97
+
98
+ if __name__ == "__main__":
99
+ result = ingest_policies(reset=True)
100
+ print(
101
+ "Ingested {documents} documents into {chunks} chunks. "
102
+ "Chroma collection now has {collection_count} records.".format(**result)
103
+ )
app/rag/retriever.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.rag.embeddings import embed_queries, rerank
2
+ from app.rag.ingest import ingest_policies
3
+ from app.rag.vector_store import get_policy_collection
4
+
5
+
6
+ def ensure_vector_store_ready() -> None:
7
+ collection = get_policy_collection()
8
+ if collection.count() == 0:
9
+ ingest_policies(reset=False)
10
+
11
+
12
+ def retrieve_policies(query: str, k: int = 4, fetch_k: int = 12, use_reranker: bool = True) -> list[dict]:
13
+ ensure_vector_store_ready()
14
+ collection = get_policy_collection()
15
+ query_embedding = embed_queries([query])[0]
16
+ results = collection.query(
17
+ query_embeddings=[query_embedding],
18
+ n_results=fetch_k,
19
+ include=["documents", "metadatas", "distances"],
20
+ )
21
+
22
+ documents = results.get("documents", [[]])[0]
23
+ metadatas = results.get("metadatas", [[]])[0]
24
+ distances = results.get("distances", [[]])[0]
25
+ ids = results.get("ids", [[]])[0]
26
+
27
+ candidates = []
28
+ for chunk_id, content, metadata, distance in zip(ids, documents, metadatas, distances):
29
+ candidates.append(
30
+ {
31
+ "id": chunk_id,
32
+ "source": metadata.get("source"),
33
+ "content": content,
34
+ "metadata": metadata,
35
+ "distance": round(float(distance), 4),
36
+ "score": round(1 / (1 + float(distance)), 4),
37
+ }
38
+ )
39
+
40
+ if use_reranker and candidates:
41
+ scores = rerank(query, [candidate["content"] for candidate in candidates])
42
+ for candidate, score in zip(candidates, scores):
43
+ candidate["rerank_score"] = round(score, 4)
44
+ candidates.sort(key=lambda item: item["rerank_score"], reverse=True)
45
+ else:
46
+ candidates.sort(key=lambda item: item["score"], reverse=True)
47
+
48
+ return candidates[:k]
app/rag/vector_store.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ from pathlib import Path
3
+
4
+ import chromadb
5
+
6
+ from app.rag.embeddings import BGEEmbeddingFunction
7
+ from app.utils.config import get_settings
8
+
9
+
10
+ def get_chroma_client(persist_dir: Path | None = None) -> chromadb.PersistentClient:
11
+ settings = get_settings()
12
+ directory = persist_dir or settings.chroma_dir
13
+ directory.mkdir(parents=True, exist_ok=True)
14
+ return chromadb.PersistentClient(path=str(directory))
15
+
16
+
17
+ def get_policy_collection():
18
+ settings = get_settings()
19
+ client = get_chroma_client()
20
+ return client.get_or_create_collection(
21
+ name=settings.chroma_collection,
22
+ embedding_function=BGEEmbeddingFunction(),
23
+ metadata={"description": "Shopify customer support policy and manual chunks"},
24
+ )
25
+
26
+
27
+ def reset_vector_store() -> None:
28
+ settings = get_settings()
29
+ if settings.chroma_dir.exists():
30
+ shutil.rmtree(settings.chroma_dir)
31
+
32
+
33
+ def collection_count() -> int:
34
+ return get_policy_collection().count()
app/services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Service package."""
app/services/escalation_service.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.utils.config import get_settings
2
+
3
+
4
+ class EscalationService:
5
+ def should_escalate(self, confidence: float, validation: dict, order: dict | None) -> tuple[bool, str | None]:
6
+ threshold = get_settings().auto_reply_confidence_threshold
7
+ if not validation.get("valid"):
8
+ return True, "Validation failed or policy grounding was insufficient."
9
+ if confidence < threshold:
10
+ return True, f"Confidence {confidence:.2f} is below threshold {threshold:.2f}."
11
+ if order is None:
12
+ return True, "Order details could not be found."
13
+ return False, None
app/services/shopify_service.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+
4
+ from app.utils.config import get_settings
5
+
6
+
7
+ class ShopifyService:
8
+ def __init__(self, orders_path: Path | None = None):
9
+ self.orders_path = orders_path or get_settings().orders_path
10
+
11
+ def get_order(self, order_id: str | None) -> dict | None:
12
+ if not order_id or not self.orders_path.exists():
13
+ return None
14
+ data = json.loads(self.orders_path.read_text(encoding="utf-8"))
15
+ normalized = order_id.replace("#", "").upper()
16
+ for order in data.get("orders", []):
17
+ if str(order.get("order_id", "")).upper() == normalized:
18
+ return order
19
+ return None
app/services/ticket_service.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from datetime import datetime, timezone
3
+ from pathlib import Path
4
+ from uuid import uuid4
5
+
6
+ from app.utils.config import get_settings
7
+
8
+
9
+ class TicketService:
10
+ def __init__(self, tickets_dir: Path | None = None):
11
+ self.tickets_dir = tickets_dir or get_settings().tickets_dir
12
+ self.tickets_dir.mkdir(parents=True, exist_ok=True)
13
+
14
+ def save(self, payload: dict) -> str:
15
+ ticket_id = f"ticket_{uuid4().hex[:10]}"
16
+ payload = {"ticket_id": ticket_id, "created_at": datetime.now(timezone.utc).isoformat(), **payload}
17
+ metadata_path = self.tickets_dir / f"{ticket_id}.json"
18
+ response_path = self.tickets_dir / f"{ticket_id}.txt"
19
+ metadata_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
20
+ response_path.write_text(payload.get("response", ""), encoding="utf-8")
21
+ return ticket_id
app/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Utility package."""
app/utils/config.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ from pathlib import Path
3
+
4
+ from pydantic_settings import BaseSettings, SettingsConfigDict
5
+
6
+
7
+ class Settings(BaseSettings):
8
+ app_name: str = "Shopify Customer Support Intelligence"
9
+ environment: str = "development"
10
+ log_level: str = "INFO"
11
+ data_dir: Path = Path("data")
12
+ policy_dir: Path = Path("data/policies")
13
+ orders_path: Path = Path("data/orders/orders.json")
14
+ tickets_dir: Path = Path("data/tickets")
15
+ chroma_dir: Path = Path("data/embeddings/chroma")
16
+ chroma_collection: str = "shopify_support_policies"
17
+ embedding_model_name: str = "BAAI/bge-small-en-v1.5"
18
+ reranker_model_name: str = "BAAI/bge-reranker-base"
19
+ rag_chunk_size: int = 700
20
+ rag_chunk_overlap: int = 120
21
+ groq_api_key: str | None = None
22
+ gemini_api_key: str | None = None
23
+ google_api_key: str | None = None
24
+ shopify_store_url: str | None = None
25
+ shopify_access_token: str | None = None
26
+ auto_reply_confidence_threshold: float = 0.72
27
+
28
+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
29
+
30
+
31
+ @lru_cache
32
+ def get_settings() -> Settings:
33
+ return Settings()
app/utils/helpers.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from datetime import date
3
+
4
+
5
+ ORDER_PATTERN = re.compile(r"(?:order\s*)?#?\s*([A-Z0-9-]{4,})", re.IGNORECASE)
6
+
7
+
8
+ def extract_order_id(text: str) -> str | None:
9
+ match = ORDER_PATTERN.search(text)
10
+ return match.group(1).upper() if match else None
11
+
12
+
13
+ def days_between(start: str, end: str | None = None) -> int:
14
+ end_date = date.fromisoformat(end) if end else date.today()
15
+ return (end_date - date.fromisoformat(start)).days
app/utils/logger.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from app.utils.config import get_settings
4
+
5
+
6
+ def get_logger(name: str) -> logging.Logger:
7
+ settings = get_settings()
8
+ logging.basicConfig(
9
+ level=settings.log_level,
10
+ format="%(asctime)s %(levelname)s [%(name)s] %(message)s",
11
+ )
12
+ return logging.getLogger(name)
app/workflows/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Workflow package."""
app/workflows/langgraph_workflow.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from app.agents.intent_agent import IntentAgent
2
+ from app.agents.order_agent import OrderAgent
3
+ from app.agents.policy_agent import PolicyAgent
4
+ from app.agents.reasoning_agent import ReasoningAgent
5
+ from app.agents.supervisor_agent import SupervisorAgent
6
+ from app.agents.validation_agent import ValidationAgent
7
+ from app.services.escalation_service import EscalationService
8
+ from app.services.ticket_service import TicketService
9
+
10
+
11
+ class CustomerSupportWorkflow:
12
+ def __init__(self):
13
+ self.supervisor = SupervisorAgent()
14
+ self.intent_agent = IntentAgent()
15
+ self.order_agent = OrderAgent()
16
+ self.policy_agent = PolicyAgent()
17
+ self.reasoning_agent = ReasoningAgent()
18
+ self.validation_agent = ValidationAgent()
19
+ self.escalation_service = EscalationService()
20
+ self.ticket_service = TicketService()
21
+
22
+ def run(self, customer_id: str, message: str, order_id: str | None = None) -> dict:
23
+ supervisor = self.supervisor.plan(message, order_id)
24
+ intent = self.intent_agent.classify(message)
25
+ order = self.order_agent.fetch(message, order_id) if supervisor["run_order_agent"] else None
26
+ policies = self.policy_agent.retrieve(message, intent["intent"]) if supervisor["run_policy_agent"] else []
27
+ reasoning = self.reasoning_agent.respond(message, intent, order, policies)
28
+ validation = self.validation_agent.validate(reasoning["response"], policies)
29
+ escalated, escalation_reason = self.escalation_service.should_escalate(
30
+ reasoning["confidence"], validation, order
31
+ )
32
+ ticket_id = self.ticket_service.save(
33
+ {
34
+ "customer_id": customer_id,
35
+ "message": message,
36
+ "order_id": order_id,
37
+ "response": reasoning["response"],
38
+ "escalated": escalated,
39
+ "trace": {
40
+ "supervisor": supervisor,
41
+ "intent": intent,
42
+ "order": order,
43
+ "policies": policies,
44
+ "reasoning": reasoning,
45
+ "validation": validation,
46
+ },
47
+ }
48
+ )
49
+ return {
50
+ "ticket_id": ticket_id,
51
+ "response": reasoning["response"],
52
+ "confidence": reasoning["confidence"],
53
+ "escalated": escalated,
54
+ "escalation_reason": escalation_reason,
55
+ "trace": {
56
+ "supervisor": supervisor,
57
+ "intent": intent,
58
+ "order": order,
59
+ "policies": policies,
60
+ "reasoning": reasoning,
61
+ "validation": validation,
62
+ },
63
+ }
data/orders/orders.json ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "orders": [
3
+ {
4
+ "order_id": "1234",
5
+ "customer_id": "cust_001",
6
+ "customer_email": "maya@example.com",
7
+ "status": "delayed",
8
+ "fulfillment_status": "shipped",
9
+ "payment_status": "paid",
10
+ "tracking_number": "TRK1234IN",
11
+ "carrier": "BlueDart",
12
+ "ordered_at": "2026-06-14",
13
+ "expected_delivery": "2026-06-25",
14
+ "promised_delivery": "2026-06-22",
15
+ "total": 129.99,
16
+ "currency": "USD",
17
+ "shipping_country": "IN",
18
+ "items": ["Smart Travel Backpack"]
19
+ },
20
+ {
21
+ "order_id": "5678",
22
+ "customer_id": "cust_002",
23
+ "customer_email": "noah@example.com",
24
+ "status": "delivered",
25
+ "fulfillment_status": "fulfilled",
26
+ "payment_status": "paid",
27
+ "tracking_number": "TRK5678US",
28
+ "carrier": "UPS",
29
+ "ordered_at": "2026-06-10",
30
+ "expected_delivery": "2026-06-16",
31
+ "promised_delivery": "2026-06-17",
32
+ "delivered_at": "2026-06-16",
33
+ "total": 79.5,
34
+ "currency": "USD",
35
+ "shipping_country": "US",
36
+ "items": ["Wireless Desk Lamp"]
37
+ },
38
+ {
39
+ "order_id": "9012",
40
+ "customer_id": "cust_003",
41
+ "customer_email": "aisha@example.com",
42
+ "status": "processing",
43
+ "fulfillment_status": "unfulfilled",
44
+ "payment_status": "paid",
45
+ "tracking_number": null,
46
+ "carrier": null,
47
+ "ordered_at": "2026-06-22",
48
+ "expected_delivery": "2026-06-29",
49
+ "promised_delivery": "2026-06-30",
50
+ "total": 34.0,
51
+ "currency": "USD",
52
+ "shipping_country": "US",
53
+ "items": ["Fitness Water Bottle"]
54
+ },
55
+ {
56
+ "order_id": "1001",
57
+ "customer_id": "cust_004",
58
+ "customer_email": "liam@example.com",
59
+ "status": "in_transit",
60
+ "fulfillment_status": "shipped",
61
+ "payment_status": "paid",
62
+ "tracking_number": "TRK1001US",
63
+ "carrier": "FedEx",
64
+ "ordered_at": "2026-06-18",
65
+ "expected_delivery": "2026-06-24",
66
+ "promised_delivery": "2026-06-25",
67
+ "total": 58.25,
68
+ "currency": "USD",
69
+ "shipping_country": "US",
70
+ "items": ["Fitness Water Bottle", "Replacement Lid"]
71
+ },
72
+ {
73
+ "order_id": "1002",
74
+ "customer_id": "cust_005",
75
+ "customer_email": "emma@example.com",
76
+ "status": "delivered",
77
+ "fulfillment_status": "fulfilled",
78
+ "payment_status": "paid",
79
+ "tracking_number": "TRK1002CA",
80
+ "carrier": "DHL",
81
+ "ordered_at": "2026-06-05",
82
+ "expected_delivery": "2026-06-15",
83
+ "promised_delivery": "2026-06-16",
84
+ "delivered_at": "2026-06-15",
85
+ "total": 149.99,
86
+ "currency": "USD",
87
+ "shipping_country": "CA",
88
+ "items": ["Smart Travel Backpack"]
89
+ },
90
+ {
91
+ "order_id": "1003",
92
+ "customer_id": "cust_006",
93
+ "customer_email": "olivia@example.com",
94
+ "status": "cancelled",
95
+ "fulfillment_status": "cancelled",
96
+ "payment_status": "refunded",
97
+ "tracking_number": null,
98
+ "carrier": null,
99
+ "ordered_at": "2026-06-19",
100
+ "cancelled_at": "2026-06-19",
101
+ "expected_delivery": null,
102
+ "promised_delivery": null,
103
+ "total": 44.99,
104
+ "currency": "USD",
105
+ "shipping_country": "US",
106
+ "items": ["Fitness Water Bottle"]
107
+ },
108
+ {
109
+ "order_id": "1004",
110
+ "customer_id": "cust_007",
111
+ "customer_email": "arjun@example.com",
112
+ "status": "payment_failed",
113
+ "fulfillment_status": "unfulfilled",
114
+ "payment_status": "failed",
115
+ "tracking_number": null,
116
+ "carrier": null,
117
+ "ordered_at": "2026-06-23",
118
+ "expected_delivery": null,
119
+ "promised_delivery": null,
120
+ "total": 219.0,
121
+ "currency": "USD",
122
+ "shipping_country": "IN",
123
+ "items": ["Wireless Desk Lamp", "Smart Travel Backpack"]
124
+ },
125
+ {
126
+ "order_id": "1005",
127
+ "customer_id": "cust_008",
128
+ "customer_email": "sophia@example.com",
129
+ "status": "out_for_delivery",
130
+ "fulfillment_status": "shipped",
131
+ "payment_status": "paid",
132
+ "tracking_number": "TRK1005US",
133
+ "carrier": "USPS",
134
+ "ordered_at": "2026-06-20",
135
+ "expected_delivery": "2026-06-23",
136
+ "promised_delivery": "2026-06-24",
137
+ "total": 39.5,
138
+ "currency": "USD",
139
+ "shipping_country": "US",
140
+ "items": ["Fitness Water Bottle"]
141
+ },
142
+ {
143
+ "order_id": "1006",
144
+ "customer_id": "cust_009",
145
+ "customer_email": "ethan@example.com",
146
+ "status": "lost_package_review",
147
+ "fulfillment_status": "shipped",
148
+ "payment_status": "paid",
149
+ "tracking_number": "TRK1006US",
150
+ "carrier": "UPS",
151
+ "ordered_at": "2026-06-07",
152
+ "expected_delivery": "2026-06-14",
153
+ "promised_delivery": "2026-06-14",
154
+ "total": 89.0,
155
+ "currency": "USD",
156
+ "shipping_country": "US",
157
+ "items": ["Wireless Desk Lamp"]
158
+ },
159
+ {
160
+ "order_id": "1007",
161
+ "customer_id": "cust_010",
162
+ "customer_email": "mia@example.com",
163
+ "status": "return_requested",
164
+ "fulfillment_status": "fulfilled",
165
+ "payment_status": "paid",
166
+ "tracking_number": "TRK1007US",
167
+ "carrier": "FedEx",
168
+ "ordered_at": "2026-06-01",
169
+ "expected_delivery": "2026-06-07",
170
+ "promised_delivery": "2026-06-08",
171
+ "delivered_at": "2026-06-07",
172
+ "total": 129.99,
173
+ "currency": "USD",
174
+ "shipping_country": "US",
175
+ "items": ["Smart Travel Backpack"]
176
+ },
177
+ {
178
+ "order_id": "1008",
179
+ "customer_id": "cust_011",
180
+ "customer_email": "lucas@example.com",
181
+ "status": "exchange_requested",
182
+ "fulfillment_status": "fulfilled",
183
+ "payment_status": "paid",
184
+ "tracking_number": "TRK1008US",
185
+ "carrier": "UPS",
186
+ "ordered_at": "2026-06-03",
187
+ "expected_delivery": "2026-06-09",
188
+ "promised_delivery": "2026-06-10",
189
+ "delivered_at": "2026-06-09",
190
+ "total": 34.0,
191
+ "currency": "USD",
192
+ "shipping_country": "US",
193
+ "items": ["Fitness Water Bottle"]
194
+ },
195
+ {
196
+ "order_id": "1009",
197
+ "customer_id": "cust_012",
198
+ "customer_email": "ava@example.com",
199
+ "status": "damaged_on_arrival",
200
+ "fulfillment_status": "fulfilled",
201
+ "payment_status": "paid",
202
+ "tracking_number": "TRK1009US",
203
+ "carrier": "USPS",
204
+ "ordered_at": "2026-06-12",
205
+ "expected_delivery": "2026-06-18",
206
+ "promised_delivery": "2026-06-18",
207
+ "delivered_at": "2026-06-18",
208
+ "total": 79.5,
209
+ "currency": "USD",
210
+ "shipping_country": "US",
211
+ "items": ["Wireless Desk Lamp"]
212
+ },
213
+ {
214
+ "order_id": "1010",
215
+ "customer_id": "cust_013",
216
+ "customer_email": "isabella@example.com",
217
+ "status": "partially_fulfilled",
218
+ "fulfillment_status": "partial",
219
+ "payment_status": "paid",
220
+ "tracking_number": "TRK1010US-A",
221
+ "carrier": "FedEx",
222
+ "ordered_at": "2026-06-17",
223
+ "expected_delivery": "2026-06-26",
224
+ "promised_delivery": "2026-06-27",
225
+ "total": 208.99,
226
+ "currency": "USD",
227
+ "shipping_country": "US",
228
+ "items": ["Smart Travel Backpack", "Wireless Desk Lamp"]
229
+ },
230
+ {
231
+ "order_id": "1011",
232
+ "customer_id": "cust_014",
233
+ "customer_email": "logan@example.com",
234
+ "status": "international_customs",
235
+ "fulfillment_status": "shipped",
236
+ "payment_status": "paid",
237
+ "tracking_number": "TRK1011GB",
238
+ "carrier": "DHL",
239
+ "ordered_at": "2026-06-08",
240
+ "expected_delivery": "2026-06-28",
241
+ "promised_delivery": "2026-06-26",
242
+ "total": 164.99,
243
+ "currency": "USD",
244
+ "shipping_country": "GB",
245
+ "items": ["Smart Travel Backpack"]
246
+ },
247
+ {
248
+ "order_id": "1012",
249
+ "customer_id": "cust_015",
250
+ "customer_email": "amelia@example.com",
251
+ "status": "delivered",
252
+ "fulfillment_status": "fulfilled",
253
+ "payment_status": "paid",
254
+ "tracking_number": "TRK1012AU",
255
+ "carrier": "DHL",
256
+ "ordered_at": "2026-05-30",
257
+ "expected_delivery": "2026-06-20",
258
+ "promised_delivery": "2026-06-21",
259
+ "delivered_at": "2026-06-19",
260
+ "total": 114.0,
261
+ "currency": "USD",
262
+ "shipping_country": "AU",
263
+ "items": ["Wireless Desk Lamp", "Fitness Water Bottle"]
264
+ },
265
+ {
266
+ "order_id": "1013",
267
+ "customer_id": "cust_016",
268
+ "customer_email": "ben@example.com",
269
+ "status": "awaiting_pickup",
270
+ "fulfillment_status": "shipped",
271
+ "payment_status": "paid",
272
+ "tracking_number": "TRK1013US",
273
+ "carrier": "USPS",
274
+ "ordered_at": "2026-06-16",
275
+ "expected_delivery": "2026-06-23",
276
+ "promised_delivery": "2026-06-24",
277
+ "total": 44.0,
278
+ "currency": "USD",
279
+ "shipping_country": "US",
280
+ "items": ["Fitness Water Bottle"]
281
+ },
282
+ {
283
+ "order_id": "1014",
284
+ "customer_id": "cust_017",
285
+ "customer_email": "zoe@example.com",
286
+ "status": "refund_approved",
287
+ "fulfillment_status": "fulfilled",
288
+ "payment_status": "refund_pending",
289
+ "tracking_number": "TRK1014US",
290
+ "carrier": "UPS",
291
+ "ordered_at": "2026-05-25",
292
+ "expected_delivery": "2026-06-01",
293
+ "promised_delivery": "2026-06-01",
294
+ "delivered_at": "2026-06-01",
295
+ "total": 79.5,
296
+ "currency": "USD",
297
+ "shipping_country": "US",
298
+ "items": ["Wireless Desk Lamp"]
299
+ },
300
+ {
301
+ "order_id": "1015",
302
+ "customer_id": "cust_018",
303
+ "customer_email": "daniel@example.com",
304
+ "status": "fraud_review",
305
+ "fulfillment_status": "on_hold",
306
+ "payment_status": "authorized",
307
+ "tracking_number": null,
308
+ "carrier": null,
309
+ "ordered_at": "2026-06-23",
310
+ "expected_delivery": null,
311
+ "promised_delivery": null,
312
+ "total": 389.98,
313
+ "currency": "USD",
314
+ "shipping_country": "US",
315
+ "items": ["Smart Travel Backpack", "Smart Travel Backpack", "Wireless Desk Lamp"]
316
+ },
317
+ {
318
+ "order_id": "1016",
319
+ "customer_id": "cust_019",
320
+ "customer_email": "nora@example.com",
321
+ "status": "preparing_shipment",
322
+ "fulfillment_status": "processing",
323
+ "payment_status": "paid",
324
+ "tracking_number": null,
325
+ "carrier": null,
326
+ "ordered_at": "2026-06-21",
327
+ "expected_delivery": "2026-06-28",
328
+ "promised_delivery": "2026-06-29",
329
+ "total": 129.99,
330
+ "currency": "USD",
331
+ "shipping_country": "US",
332
+ "items": ["Smart Travel Backpack"]
333
+ },
334
+ {
335
+ "order_id": "1017",
336
+ "customer_id": "cust_020",
337
+ "customer_email": "sam@example.com",
338
+ "status": "delivered",
339
+ "fulfillment_status": "fulfilled",
340
+ "payment_status": "paid",
341
+ "tracking_number": "TRK1017US",
342
+ "carrier": "FedEx",
343
+ "ordered_at": "2026-06-11",
344
+ "expected_delivery": "2026-06-17",
345
+ "promised_delivery": "2026-06-18",
346
+ "delivered_at": "2026-06-17",
347
+ "total": 34.0,
348
+ "currency": "USD",
349
+ "shipping_country": "US",
350
+ "items": ["Fitness Water Bottle"]
351
+ },
352
+ {
353
+ "order_id": "1018",
354
+ "customer_id": "cust_021",
355
+ "customer_email": "harper@example.com",
356
+ "status": "carrier_exception",
357
+ "fulfillment_status": "shipped",
358
+ "payment_status": "paid",
359
+ "tracking_number": "TRK1018US",
360
+ "carrier": "UPS",
361
+ "ordered_at": "2026-06-13",
362
+ "expected_delivery": "2026-06-19",
363
+ "promised_delivery": "2026-06-20",
364
+ "total": 79.5,
365
+ "currency": "USD",
366
+ "shipping_country": "US",
367
+ "items": ["Wireless Desk Lamp"]
368
+ },
369
+ {
370
+ "order_id": "1019",
371
+ "customer_id": "cust_022",
372
+ "customer_email": "vivaan@example.com",
373
+ "status": "international_in_transit",
374
+ "fulfillment_status": "shipped",
375
+ "payment_status": "paid",
376
+ "tracking_number": "TRK1019SG",
377
+ "carrier": "DHL",
378
+ "ordered_at": "2026-06-12",
379
+ "expected_delivery": "2026-07-02",
380
+ "promised_delivery": "2026-07-01",
381
+ "total": 173.99,
382
+ "currency": "USD",
383
+ "shipping_country": "SG",
384
+ "items": ["Smart Travel Backpack", "Fitness Water Bottle"]
385
+ },
386
+ {
387
+ "order_id": "1020",
388
+ "customer_id": "cust_023",
389
+ "customer_email": "ella@example.com",
390
+ "status": "gift_card_issued",
391
+ "fulfillment_status": "digital_delivered",
392
+ "payment_status": "paid",
393
+ "tracking_number": null,
394
+ "carrier": "email",
395
+ "ordered_at": "2026-06-22",
396
+ "expected_delivery": "2026-06-22",
397
+ "promised_delivery": "2026-06-22",
398
+ "delivered_at": "2026-06-22",
399
+ "total": 50.0,
400
+ "currency": "USD",
401
+ "shipping_country": "US",
402
+ "items": ["Digital Gift Card"]
403
+ },
404
+ {
405
+ "order_id": "1021",
406
+ "customer_id": "cust_024",
407
+ "customer_email": "jack@example.com",
408
+ "status": "address_hold",
409
+ "fulfillment_status": "on_hold",
410
+ "payment_status": "paid",
411
+ "tracking_number": null,
412
+ "carrier": null,
413
+ "ordered_at": "2026-06-23",
414
+ "expected_delivery": "2026-06-30",
415
+ "promised_delivery": "2026-06-30",
416
+ "total": 129.99,
417
+ "currency": "USD",
418
+ "shipping_country": "US",
419
+ "items": ["Smart Travel Backpack"]
420
+ },
421
+ {
422
+ "order_id": "1022",
423
+ "customer_id": "cust_025",
424
+ "customer_email": "grace@example.com",
425
+ "status": "replacement_sent",
426
+ "fulfillment_status": "shipped",
427
+ "payment_status": "paid",
428
+ "tracking_number": "TRK1022US",
429
+ "carrier": "FedEx",
430
+ "ordered_at": "2026-06-02",
431
+ "expected_delivery": "2026-06-24",
432
+ "promised_delivery": "2026-06-25",
433
+ "total": 0.0,
434
+ "currency": "USD",
435
+ "shipping_country": "US",
436
+ "items": ["Wireless Desk Lamp Replacement"]
437
+ },
438
+ {
439
+ "order_id": "1023",
440
+ "customer_id": "cust_026",
441
+ "customer_email": "leo@example.com",
442
+ "status": "return_in_transit",
443
+ "fulfillment_status": "fulfilled",
444
+ "payment_status": "paid",
445
+ "tracking_number": "RET1023US",
446
+ "carrier": "USPS",
447
+ "ordered_at": "2026-05-28",
448
+ "expected_delivery": "2026-06-04",
449
+ "promised_delivery": "2026-06-05",
450
+ "delivered_at": "2026-06-04",
451
+ "total": 34.0,
452
+ "currency": "USD",
453
+ "shipping_country": "US",
454
+ "items": ["Fitness Water Bottle"]
455
+ },
456
+ {
457
+ "order_id": "1024",
458
+ "customer_id": "cust_027",
459
+ "customer_email": "chloe@example.com",
460
+ "status": "subscription_order_created",
461
+ "fulfillment_status": "processing",
462
+ "payment_status": "paid",
463
+ "tracking_number": null,
464
+ "carrier": null,
465
+ "ordered_at": "2026-06-23",
466
+ "expected_delivery": "2026-06-30",
467
+ "promised_delivery": "2026-06-30",
468
+ "total": 34.0,
469
+ "currency": "USD",
470
+ "shipping_country": "US",
471
+ "items": ["Fitness Water Bottle"]
472
+ },
473
+ {
474
+ "order_id": "1025",
475
+ "customer_id": "cust_028",
476
+ "customer_email": "omar@example.com",
477
+ "status": "delayed",
478
+ "fulfillment_status": "shipped",
479
+ "payment_status": "paid",
480
+ "tracking_number": "TRK1025DE",
481
+ "carrier": "DHL",
482
+ "ordered_at": "2026-06-04",
483
+ "expected_delivery": "2026-06-27",
484
+ "promised_delivery": "2026-06-20",
485
+ "total": 129.99,
486
+ "currency": "USD",
487
+ "shipping_country": "DE",
488
+ "items": ["Smart Travel Backpack"]
489
+ },
490
+ {
491
+ "order_id": "1026",
492
+ "customer_id": "cust_029",
493
+ "customer_email": "lily@example.com",
494
+ "status": "delivered",
495
+ "fulfillment_status": "fulfilled",
496
+ "payment_status": "partially_refunded",
497
+ "tracking_number": "TRK1026US",
498
+ "carrier": "UPS",
499
+ "ordered_at": "2026-06-06",
500
+ "expected_delivery": "2026-06-12",
501
+ "promised_delivery": "2026-06-13",
502
+ "delivered_at": "2026-06-12",
503
+ "total": 208.99,
504
+ "currency": "USD",
505
+ "shipping_country": "US",
506
+ "items": ["Smart Travel Backpack", "Wireless Desk Lamp"]
507
+ },
508
+ {
509
+ "order_id": "1027",
510
+ "customer_id": "cust_030",
511
+ "customer_email": "mateo@example.com",
512
+ "status": "manual_review",
513
+ "fulfillment_status": "on_hold",
514
+ "payment_status": "paid",
515
+ "tracking_number": null,
516
+ "carrier": null,
517
+ "ordered_at": "2026-06-23",
518
+ "expected_delivery": "2026-07-01",
519
+ "promised_delivery": "2026-07-01",
520
+ "total": 499.0,
521
+ "currency": "USD",
522
+ "shipping_country": "MX",
523
+ "items": ["Smart Travel Backpack", "Wireless Desk Lamp", "Fitness Water Bottle"]
524
+ }
525
+ ]
526
+ }
data/policies/cancellation_policy.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Cancellation Policy
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ 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.
data/policies/exchange_policy.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Exchange Policy
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ International exchanges require human review because return shipping, customs duties, and replacement shipping costs vary by destination.
data/policies/faq_1.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FAQ: Where is my order?
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
data/policies/faq_2.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FAQ: Can I change my shipping address?
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
data/policies/faq_3.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FAQ: What should I do if my item arrived damaged?
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
data/policies/faq_4.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FAQ: Why did my payment fail?
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
data/policies/gift_card_policy.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Gift Card Policy
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ Suspected stolen, resold, or fraudulently obtained gift cards must be escalated before any balance information is disclosed.
data/policies/international_shipping.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ International Shipping Policy
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ International returns and exchanges require human review because return labels, customs declarations, tax recovery, and replacement shipping costs vary by destination.
data/policies/membership_policy.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Membership Policy
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ Promotional rewards may have expiration dates, product exclusions, minimum order values, and stacking limitations. Support should check the campaign terms before promising reward reinstatement.
12
+
13
+ Suspected abuse, repeated account creation, referral fraud, or reward manipulation must be escalated before credits are issued.
data/policies/payment_policy.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Payment Policy
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ Orders with high-risk fraud indicators, mismatched billing details, repeated failed payment attempts, or chargeback threats must be escalated before fulfillment or refund action.
data/policies/product_manual_1.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Product Manual 1: Smart Travel Backpack
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ If the USB pass-through does not work, ask the customer to test with another cable and power bank before opening a warranty claim.
data/policies/product_manual_2.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Product Manual 2: Wireless Desk Lamp
2
+
3
+ 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.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ Stop use and contact support if the battery overheats, swells, smells unusual, smokes, sparks, or leaks. Safety-related cases must be escalated immediately.
data/policies/product_manual_3.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Product Manual 3: Fitness Water Bottle
2
+
3
+ The Fitness Water Bottle includes a leak-resistant lid, carry loop, measurement marks, and removable silicone seal. Wash all parts before first use.
4
+
5
+ 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.
6
+
7
+ 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.
8
+
9
+ 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.
10
+
11
+ 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.