File size: 22,134 Bytes
c9f5049
 
 
 
 
 
 
 
 
570280a
c9f5049
570280a
 
 
 
c9f5049
 
 
 
 
 
 
 
 
 
 
 
570280a
c9f5049
570280a
c9f5049
 
 
 
 
 
 
 
570280a
 
c9f5049
 
 
570280a
c9f5049
570280a
 
 
 
 
 
 
 
 
c9f5049
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570280a
c9f5049
 
 
 
 
 
 
 
 
570280a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f5049
 
 
 
 
 
 
 
 
 
 
 
 
570280a
c9f5049
 
 
 
 
 
 
 
 
 
 
 
570280a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f5049
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570280a
 
c9f5049
570280a
 
 
 
 
 
 
c9f5049
570280a
c9f5049
570280a
c9f5049
570280a
c9f5049
 
570280a
 
 
c9f5049
570280a
 
 
 
 
c9f5049
570280a
 
c9f5049
 
570280a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f5049
 
 
 
 
570280a
 
c9f5049
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570280a
c9f5049
 
 
570280a
 
 
 
c9f5049
 
 
570280a
c9f5049
570280a
 
c9f5049
f8a2f75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23611e1
 
f8a2f75
23611e1
 
 
f8a2f75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23611e1
f8a2f75
 
 
 
23611e1
 
f8a2f75
 
 
 
 
23611e1
 
c9f5049
 
 
 
 
 
23611e1
 
 
c9f5049
 
 
 
570280a
c9f5049
 
 
570280a
 
 
c9f5049
 
23611e1
 
 
570280a
23611e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570280a
23611e1
570280a
23611e1
570280a
2ddc4bc
570280a
 
 
 
2ddc4bc
 
 
 
 
23611e1
 
 
 
 
570280a
2ddc4bc
570280a
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# Developer Guide โ€” trip-bot

## Table of Contents

1. [Project Overview](#1-project-overview)
2. [Directory Structure](#2-directory-structure)
3. [Architecture](#3-architecture)
4. [App Flow โ€” Request Lifecycle](#4-app-flow--request-lifecycle)
5. [Module Responsibilities](#5-module-responsibilities)
6. [LLM System (Phase 3)](#6-llm-system-phase-3)
7. [Data Schema โ€” tokyo-matsumoto.json](#7-data-schema--tokyo-matsumotojson)
8. [Stateless Design](#8-stateless-design)
9. [Phase 2 Reference (ML NER)](#9-phase-2-reference-ml-ner)
10. [Environment Variables](#10-environment-variables)
11. [Learning & Upgrade Roadmap](#11-learning--upgrade-roadmap)

---

## 1. Project Overview

A **stateless** Thai-language itinerary chatbot for the LINE Messaging API.
Users ask questions in Thai; the bot answers based on a fixed travel itinerary (Tokyoโ€“Matsumoto).

| Property | Value |
|---|---|
| Language | Python 3.10+ |
| Framework | FastAPI |
| LLM | Typhoon API (`typhoon-v2.5-30b-a3b-instruct`) via OpenAI-compatible SDK |
| Integration | LINE Messaging API v3 Webhook |
| State | **None** โ€” fully stateless |

---

## 2. Directory Structure

```
trip-bot/
โ”œโ”€โ”€ main.py                         # FastAPI app entry point & router registration
โ”œโ”€โ”€ requirements.txt                # pip dependencies
โ”œโ”€โ”€ .env                            # Secrets โ€” credentials (never commit)
โ”œโ”€โ”€ .env.example                    # Template for .env
โ”‚
โ”œโ”€โ”€ data/
โ”‚   โ””โ”€โ”€ tokyo-matsumoto.json        # Itinerary โ€” single source of truth
โ”‚
โ”œโ”€โ”€ app/
โ”‚   โ”œโ”€โ”€ routes/
โ”‚   โ”‚   โ””โ”€โ”€ webhook.py              # POST /webhook โ€” LINE event receiver
โ”‚   โ””โ”€โ”€ utils/
โ”‚       โ””โ”€โ”€ llm_client.py           # Typhoon API client + system prompt
โ”‚
โ””โ”€โ”€ dev_tools/
    โ”œโ”€โ”€ learning_roadmap.md         # NLP โ†’ LLM learning path
    โ””โ”€โ”€ test_thainerwangchan.py     # Phase 2 NER experiments (WangchanBERTa)
```

---

## 3. Architecture

```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                          LINE Platform                                  โ”‚
โ”‚                    (sends webhook POST request)                          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚  POST /webhook
                                โ”‚  Header: X-Line-Signature (HMAC-SHA256)
                                โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  main.py  โ€”  FastAPI Application                                        โ”‚
โ”‚  โ€ข load_dotenv() โ€” must run before any os.getenv()                     โ”‚
โ”‚  โ€ข Registers /webhook router                                            โ”‚
โ”‚  โ€ข Exposes GET /health                                                  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚
                                โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  app/routes/webhook.py                                                  โ”‚
โ”‚  1. Verify HMAC-SHA256 signature  โ†’  400 if invalid                    โ”‚
โ”‚  2. Parse LINE event (MessageEvent + TextMessageContent)                โ”‚
โ”‚  3. Pass raw user_text to llm_client.ask()                             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚  user_text (raw Thai string)
                                โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  app/utils/llm_client.py                                                โ”‚
โ”‚  โ€ข Itinerary JSON loaded once at startup โ†’ injected into system prompt โ”‚
โ”‚  โ€ข OpenAI SDK with base_url = https://api.opentyphoon.ai/v1            โ”‚
โ”‚  โ€ข Model: typhoon-v2.5-30b-a3b-instruct                                โ”‚
โ”‚  โ€ข Returns Thai reply string                                            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚  POST /v1/chat/completions
                                โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  Typhoon API (cloud)                                                    โ”‚
โ”‚  โ€ข Receives: system prompt (itinerary JSON) + user message             โ”‚
โ”‚  โ€ข Generates: Thai reply grounded in itinerary data                    โ”‚
โ”‚  โ€ข Returns: choices[0].message.content                                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                โ”‚  reply_text
                                โ–ผ
                  LINE Reply API โ€” sends reply to user

             โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
             โ”‚  data/tokyo-matsumoto.json  (read-only at startup)       โ”‚
             โ”‚  Loaded once into memory โ€” no DB, no file I/O per req   โ”‚
             โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```

---

## 4. App Flow โ€” Request Lifecycle

Below is the step-by-step flow for a single user message.

**Example:** User types `"เธงเธฑเธ™เธ—เธตเนˆ 29 เธ—เธณเธญเธฐเน„เธฃเธšเน‰เธฒเธ‡"`

```
Step 1  โ”€โ”€ LINE Platform
           User sends message โ†’ LINE generates webhook POST

Step 2  โ”€โ”€ app/routes/webhook.py : async def webhook()
           โ€ข Reads raw request body
           โ€ข Verifies X-Line-Signature (HMAC-SHA256 with CHANNEL_SECRET)
           โ€ข Calls handler.handle(body, signature)
           โ€ข Returns {"status": "ok"} to LINE immediately

Step 3  โ”€โ”€ app/routes/webhook.py : handle_text_message(event)
           โ€ข user_text = "เธงเธฑเธ™เธ—เธตเนˆ 29 เธ—เธณเธญเธฐเน„เธฃเธšเน‰เธฒเธ‡"
           โ€ข Calls ask(user_text)

Step 4  โ”€โ”€ app/utils/llm_client.py : ask(user_text)
           โ€ข Builds messages:
             - system: _SYSTEM_PROMPT  (Thai assistant rules + full itinerary JSON)
             - user:   "เธงเธฑเธ™เธ—เธตเนˆ 29 เธ—เธณเธญเธฐเน„เธฃเธšเน‰เธฒเธ‡"
           โ€ข POST https://api.opentyphoon.ai/v1/chat/completions
             model: typhoon-v2.5-30b-a3b-instruct
             temperature: 0.6 / top_p: 0.6 / max_completion_tokens: 4096

Step 5  โ”€โ”€ Typhoon API
           Reads full itinerary in context โ†’ identifies "เธงเธฑเธ™เธ—เธตเนˆ 29" = 2026-05-29
           Generates grounded Thai reply from itinerary data

Step 6  โ”€โ”€ reply_text =
           "เธงเธฑเธ™เธ—เธตเนˆ 29 เธžเธคเธฉเธ เธฒเธ„เธก เธเธดเธˆเธเธฃเธฃเธกเธกเธตเธ”เธฑเธ‡เธ™เธตเน‰:
            โ€ข 06:00 เธ™. เธ•เธทเนˆเธ™เธ™เธญเธ™ เน€เธ•เธฃเธตเธขเธกเธ•เธฑเธง
            โ€ข ..."

Step 7  โ”€โ”€ LINE Reply API
           MessagingApi.reply_message_with_http_info(reply_token, TextMessage)
           User receives the reply in LINE chat
```

---

## 5. Module Responsibilities

### `main.py`
- Creates the FastAPI application instance
- Calls `load_dotenv()` **before** any other import reads `os.getenv()`
- Registers the webhook router
- Exposes `GET /health` for deployment liveness probes

### `app/routes/webhook.py`
- Owns the `POST /webhook` HTTP endpoint
- Verifies LINE's HMAC-SHA256 signature โ€” rejects invalid requests with HTTP 400
- Extracts `user_text` from the event
- Calls `ask(user_text)` from `llm_client` and sends reply via LINE Reply API

### `app/utils/llm_client.py`
- Loads `data/tokyo-matsumoto.json` **once at startup** and serializes to string
- Builds the system prompt: Thai assistant persona + itinerary rules + full JSON
- Creates an `OpenAI` client pointed at `https://api.opentyphoon.ai/v1`
- `ask(user_text)` โ€” sends system + user message, returns `choices[0].message.content`
- API key read from `TYPHOON_API_KEY` env var
- Model: `typhoon-v2.5-30b-a3b-instruct`

---

## 6. LLM System (Phase 3)

### System Prompt Structure

```python
_SYSTEM_PROMPT = f"""เธ„เธธเธ“เน€เธ›เน‡เธ™เธœเธนเน‰เธŠเนˆเธงเธขเธ—เนˆเธญเธ‡เน€เธ—เธตเนˆเธขเธงเธ เธฒเธฉเธฒเน„เธ—เธข เธŠเธทเนˆเธญ "เธ—เธฃเธดเธ›เธšเธญเธ—"

เธ—เธฃเธดเธ›เธ™เธตเน‰เธญเธขเธนเนˆเนƒเธ™เธŠเนˆเธงเธ‡เธงเธฑเธ™เธ—เธตเนˆ 29 เธžเธคเธฉเธ เธฒเธ„เธก โ€“ 8 เธกเธดเธ–เธธเธ™เธฒเธขเธ™ 2569 (เธ„.เธจ. 2026)

เธเธŽ:
- เธ•เธญเธšเธ•เธฒเธกเธ‚เน‰เธญเธกเธนเธฅเธเธณเธซเธ™เธ”เธเธฒเธฃเธ”เน‰เธฒเธ™เธฅเนˆเธฒเธ‡เน€เธ—เนˆเธฒเธ™เธฑเน‰เธ™
- เธซเน‰เธฒเธกเนเธ•เนˆเธ‡เธซเธฃเธทเธญเน€เธžเธดเนˆเธกเธ‚เน‰เธญเธกเธนเธฅเธ—เธตเนˆเน„เธกเนˆเธกเธตเนƒเธ™เธเธณเธซเธ™เธ”เธเธฒเธฃ
- เธ•เธญเธšเน€เธ›เน‡เธ™เธ เธฒเธฉเธฒเน„เธ—เธข เธเธฃเธฐเธŠเธฑเธšเนเธฅเธฐเธŠเธฑเธ”เน€เธˆเธ™
- เธ–เน‰เธฒเน„เธกเนˆเธกเธตเธ‚เน‰เธญเธกเธนเธฅเธ—เธตเนˆเธ–เธฒเธกเนƒเธซเน‰เธšเธญเธเธ•เธฃเธ‡เน† เธงเนˆเธฒเน„เธกเนˆเธกเธตเธ‚เน‰เธญเธกเธนเธฅ

เธเธณเธซเธ™เธ”เธเธฒเธฃเธ—เธฃเธดเธ›:
{_ITINERARY_TEXT}"""   # โ† full JSON injected here (~2600 tokens)
```

The LLM handles everything the old Phase 1 code did manually:

| Phase 1 needed | LLM does automatically |
|---|---|
| Regex for date extraction | Reads "เธงเธฑเธ™เธ—เธตเนˆ 29" in context โ†’ understands it |
| Gazetteer for place names | Matches places from the injected JSON |
| Intent classification | Infers what the user wants from phrasing |
| Typo handling | Predicts most likely meaning from context |

### Why Full Context Injection (not RAG)

The itinerary JSON is ~2600 tokens โ€” well within the 128K context window.
No vector search or retrieval needed โ€” the LLM reads all data every request.

RAG would only be needed if data grew beyond the context limit (100+ trips, external guides, etc.).

### Model Parameters

| Parameter | Value | Reason |
|---|---|---|
| `temperature` | 0.6 | Focused but not rigid |
| `top_p` | 0.6 | Reduces unlikely token sampling |
| `max_completion_tokens` | 4096 | Total budget: ~2635 prompt + ~1461 reply |

> Note: Typhoon's `max_completion_tokens` is the **total** limit (prompt + output), not output-only.

---

## 7. Data Schema โ€” tokyo-matsumoto.json

> To change the bot's knowledge: edit this file and restart the server. No code changes needed.

```jsonc
{
  "YYYY-MM-DD": [           // JST date key โ€” must match _date_from_timestamp() output
    {
      "time": "HH:MM",      // 24-hour local time (JST) โ€” used for wakeup/departure intents
      "origin": "...",      // Departure location โ€” used by Ask_Departure_Time & Phase 2 NER
      "destination": "...", // Arrival location   โ€” used by Ask_Next_Destination & Phase 2 NER
      "activity": "...",    // Thai description   โ€” used by Ask_Activity, Ask_Wakeup_Time
      "travel_mode": "..."  // "train" | "bus" | "flight" | "walk" | "hike" | "none" | combinations
    }
  ]
}
```

**Date range:** `2026-05-29` through `2026-06-08` (JST)

To add a new trip day, append a new date key with its events array.
No code changes are needed โ€” `response_builder.py` picks it up automatically.

---

## 8. Stateless Design

The bot holds **zero session state**. Every request is self-contained:

- No database, no session store, no cache
- The full itinerary JSON is re-injected into the system prompt on every call
- Date/time context is determined by the LLM reading the user's message
- Two users asking the same question at the same time get the same answer

---

## 9. Phase 2 Reference (ML NER)

> Phase 2 was a learning exercise โ€” the production bot uses LLM (Phase 3).
> NER experiments are in `dev_tools/test_thainerwangchan.py`.

### Entity Extraction Strategy โ€” Which Tool for What

Testing `Porameht/wangchanberta-thainer-corpus-v2-2` on itinerary queries revealed that
different entity types need different extraction tools:

| Entity | Example | Best Tool | Reason |
|---|---|---|---|
| Date with month | `"29 เธž.เธ„."`, `"29 เธžเธคเธฉเธ เธฒเธ„เธก"` | **Regex** | Fixed pattern; NER returns `''` artifact |
| Date without month | `"เธงเธฑเธ™เธ—เธตเนˆ 29"` | **Regex** | `\d+` pattern is simpler and reliable |
| Time | `"15:00"`, `"เธšเนˆเธฒเธขเธชเธฒเธก"` | **Regex** | NER produces `''` and `'.'` subword artifacts |
| Known place names | `"เธกเธฑเธ•เธชเธถเน‚เธกเน‚เธ•"`, `"เธฎเธฒเธ„เธธเธšเธฐ"` | **Gazetteer** | Itinerary is fixed; NER gives partial match at low score |
| Unknown place names | Any arbitrary city | **NER** | Can't enumerate; NER handles open vocabulary |

**Decision rule:**
```
Is the set of possible values finite and known in advance?
    YES โ†’ Gazetteer (exact match) or Regex (pattern match)
    NO  โ†’ NER (open vocabulary, but needs fine-tuning for domain-specific names)
```

**Recommended hybrid pipeline:**
```python
# 1. Date โ†’ Regex (existing response_builder.py logic โ€” keep as-is)
date = _extract_date_from_text(user_text)

# 2. Known places โ†’ Gazetteer
KNOWN_PLACES = ["เธกเธฑเธ•เธชเธถเน‚เธกเน‚เธ•", "เธ„เธฒเธกเธดเน‚เธ„เธˆเธด", "เธฎเธฒเธ„เธธเธšเธฐ", "เน‚เธ•เน€เธเธตเธขเธง"]
location = next((p for p in KNOWN_PLACES if p in user_text), None)

# 3. Unknown places โ†’ NER (after fine-tuning, with artifact filtering)
if not location:
    location = extract_location_via_ner(user_text)  # filter empty/punctuation results
```

**NER artifact filtering** (always apply in production):
```python
for ent in ner_results:
    word = ent["word"].strip()
    if not word or word in {".", ",", ":", "-"}:
        continue  # skip empty string and punctuation artifacts
    if ent["score"] < 0.7:
        continue  # skip low-confidence predictions
```

NER's real value for this bot arrives **after fine-tuning** โ€” when trips expand beyond the hard-coded place list.

### NER Output Artifacts โ€” Are They Normal?

**Yes โ€” `''` and `'.'` artifacts are a known post-processing issue, not a model defect.**

Root cause: `aggregation_strategy="simple"` reconstructs words by stripping the `โ–` (SentencePiece word-start prefix). Two edge cases produce garbage:

| Artifact | Why it happens |
|---|---|
| `''` (empty string) | Token was only `โ–` (a space piece with no word characters); stripping `โ–` leaves nothing |
| `'.'` (punctuation) | Abbreviation like `เธ™.` gets split into `เธ™` + `.`; the `.` piece survives aggregation as a standalone entity |

The NER model itself classified correctly โ€” the artifact is in the text reconstruction step only.

**Every production NER system applies post-processing filters.** Raw NER output is never used directly:

```
NER raw output  โ†’  filter empty/punctuation  โ†’  filter low score  โ†’  merge with gazetteer  โ†’  bot logic
```

**Is NER unsuitable for chatbots because of this?**

No. NER is widely used in production chatbots โ€” but always as one layer in a pipeline:

| Problem observed | Root cause | Fix |
|---|---|---|
| `''` artifact | Subword space piece | Filter empty strings |
| `'.'` artifact | Punctuation in abbreviation | Filter punctuation tokens |
| Partial place name (`'เธกเธฑเธ•เธชเธถ'`) | Japanese names rare in training data | Fine-tune or use gazetteer |
| Date `"29"` not extracted | Model expects richer date context | Use regex instead |

The NER artifacts are predictable and filterable. The bigger limitation for this bot is the **domain mismatch** (Japanese place names in Thai training data) โ€” which is solved by fine-tuning or a gazetteer.

### Pre-trained Model Cache (local)

All HuggingFace models are downloaded on first use and cached at:

```
C:\Users\WindowS 10\.cache\huggingface\hub\
```

> **Note:** This is a hidden folder. Enable "Show hidden items" in File Explorer to see it.

Models downloaded so far:

```
C:\Users\WindowS 10\.cache\huggingface\hub\
โ”‚
โ”œโ”€โ”€ models--airesearch--wangchanberta-base-att-spm-uncased\
โ”‚   โ””โ”€โ”€ snapshots\
โ”‚       โ””โ”€โ”€ b81d38df6b4755dbedec0bfea863c9956cbb963e\
โ”‚           โ”œโ”€โ”€ config.json
โ”‚           โ”œโ”€โ”€ sentencepiece.bpe.model
โ”‚           โ””โ”€โ”€ tokenizer_config.json
โ”‚
โ””โ”€โ”€ models--Porameht--wangchanberta-thainer-corpus-v2-2\
    โ””โ”€โ”€ snapshots\
        โ””โ”€โ”€ <snapshot-hash>\
            โ”œโ”€โ”€ config.json          โ† includes id2label (32 NER labels)
            โ”œโ”€โ”€ pytorch_model.bin    โ† fine-tuned weights (~500 MB)
            โ””โ”€โ”€ tokenizer files
```

| Model | Purpose |
|---|---|
| `airesearch/wangchanberta-base-att-spm-uncased` | Base encoder โ€” tokenizer experiments, Step 1 learning |
| `Porameht/wangchanberta-thainer-corpus-v2-2` | Fine-tuned NER โ€” LOCATION, DATE, TIME, FACILITY extraction |

After the first download, `from_pretrained()` loads from cache โ€” no internet required.

### New dependencies (add to requirements.txt)

```
transformers>=4.40.0
torch>=2.2.0
sentencepiece>=0.1.99
protobuf>=4.0.0
tiktoken>=0.6.0
accelerate>=0.27.0   # fine-tuning only
```

---

## 10. Environment Variables

| Variable | Description | Where to get it |
|---|---|---|
| `LINE_CHANNEL_SECRET` | Verifies webhook signatures (HMAC-SHA256) | LINE Developers Console โ†’ Basic settings โ†’ Channel secret |
| `LINE_CHANNEL_ACCESS_TOKEN` | Calls the LINE Reply API | LINE Developers Console โ†’ Messaging API โ†’ Channel access token (long-lived) |
| `TYPHOON_API_KEY` | Authenticates requests to Typhoon LLM API | [playground.opentyphoon.ai](https://playground.opentyphoon.ai) โ†’ Settings โ†’ API Keys |

Store these in `.env` (never commit this file). See `.env.example` for the template.

---

## 11. Learning & Upgrade Roadmap

This section documents the planned learning path from the current rule-based Phase 1 bot through ML-based NER (Phase 2) to a production LLM-powered chatbot (Phase 3).

---

### Phase 2 โ€” ML-based NLP & Named Entity Recognition

The goal is to understand how transformers process Thai text and to fine-tune WangchanBERTa for NER.

| Step | Topic | What you learn |
|---|---|---|
| 1 | **Text preprocessing** | Why subword tokenization (SentencePiece/BPE) outperforms word-level tokenization for Thai; vocabulary size trade-offs |
| 2 | **Transformer architecture** | Attention mechanism, encoder-only vs. decoder-only models, how BERT/RoBERTa produce contextual embeddings |
| 3 | **NER & BIO tagging** | BIO scheme (B-LOC, I-LOC, O), token-classification head, how the model labels each subword |
| 4 | **Fine-tuning WangchanBERTa** | Load `airesearch/wangchanberta-base-att-spm-uncased`, attach a classification head, train on LST20 NER dataset |
| 5 | **Bot integration** | Implement `extract_entities()` in `app/models/ner_placeholder.py`; uncomment the Phase 2 block in `webhook.py` |

**Why WangchanBERTa instead of PyThaiNLP for Phase 2?**

PyThaiNLP uses dictionary-based word tokenization โ€” fast but produces fixed vocabulary tokens.
WangchanBERTa uses SentencePiece subword tokenization trained on 78 GB of Thai text,
producing contextual embeddings that capture word meaning from surrounding context.
This is required for NER: the same word (e.g., "เธกเธฑเธ•เธชเธถเน‚เธกเน‚เธ•") can be a location or a person name depending on context.

**Recommended study order:**

```
1. Read the WangchanBERTa paper (arxiv.org/abs/2101.09635)
2. Work through HuggingFace "Token Classification" tutorial
3. Explore the LST20 dataset structure to understand BIO labels
4. Run the fine-tuning notebook locally (requires accelerate โ€” see requirements.txt)
5. Swap the stub in ner_placeholder.py with the trained pipeline
```

---

### Phase 3 โ€” LLM-powered Chatbot (Current โ€” Done)

The bot now uses full context injection: the entire itinerary JSON is pasted into the system prompt on every request. The LLM handles date parsing, place matching, intent inference, and Thai generation in one step.

See [Section 6](#6-llm-system-phase-3) for prompt structure and model parameters.

**Current stack:**
- Model: `typhoon-v2.5-30b-a3b-instruct` (Typhoon API, free tier)
- SDK: `openai` Python SDK with `base_url="https://api.opentyphoon.ai/v1"`
- No RAG, no NER, no entity extraction โ€” LLM reads everything directly

**When RAG becomes necessary:**
- 10+ trips where full JSON no longer fits in context window
- Answering questions across external documents (hotel reviews, transport guides)
- For the current single-trip bot: **not needed**

---

### Architecture Evolution Summary

| Phase | Entity Extraction | Response Generation | Status |
|---|---|---|---|
| **1** | Keyword set intersection | Hardcoded templates | Replaced |
| **2** | WangchanBERTa NER | Hardcoded templates | Learning only (dev_tools) |
| **3** | LLM reads full JSON | Typhoon API (cloud) | **Current** |