nkeer1 commited on
Commit
47372da
·
0 Parent(s):

Clean snapshot: remove PDF for HF main (including asyncio fix)

Browse files
-finalqq ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ SSUUMMMMAARRYY OOFF LLEESSSS CCOOMMMMAANNDDSS
3
+
4
+ Commands marked with * may be preceded by a number, _N.
5
+ Notes in parentheses indicate the behavior if _N is given.
6
+ A key preceded by a caret indicates the Ctrl key; thus ^K is ctrl-K.
7
+
8
+ h H Display this help.
9
+ q :q Q :Q ZZ Exit.
10
+ ---------------------------------------------------------------------------
11
+
12
+ MMOOVVIINNGG
13
+
14
+ e ^E j ^N CR * Forward one line (or _N lines).
15
+ y ^Y k ^K ^P * Backward one line (or _N lines).
16
+ ESC-j * Forward one file line (or _N file lines).
17
+ ESC-k * Backward one file line (or _N file lines).
18
+ f ^F ^V SPACE * Forward one window (or _N lines).
19
+ b ^B ESC-v * Backward one window (or _N lines).
20
+ z * Forward one window (and set window to _N).
21
+ w * Backward one window (and set window to _N).
22
+ ESC-SPACE * Forward one window, but don't stop at end-of-file.
23
+ ESC-b * Backward one window, but don't stop at beginning-of-file.
24
+ d ^D * Forward one half-window (and set half-window to _N).
25
+ u ^U * Backward one half-window (and set half-window to _N).
26
+ ESC-) RightArrow * Right one half screen width (or _N positions).
27
+ ESC-( LeftArrow * Left one half screen width (or _N positions).
28
+ ESC-} ^RightArrow Right to last column displayed.
29
+ ESC-{ ^LeftArrow Left to first column.
30
+ F Forward forever; like "tail -f".
31
+ ESC-F Like F but stop when search pattern is found.
32
+ ESC-f Like F but ring the bell when search pattern is found.
33
+ r ^R ^L Repaint screen.
34
+ R Repaint screen, discarding buffered input.
35
+ ---------------------------------------------------
36
+ Default "window" is the screen height.
37
+ Default "half-window" is half of the screen height.
38
+ ---------------------------------------------------------------------------
39
+
40
+ SSEEAARRCCHHIINNGG
41
+
42
+ /_p_a_t_t_e_r_n * Search forward for (_N-th) matching line.
43
+ ?_p_a_t_t_e_r_n * Search backward for (_N-th) matching line.
44
+ n * Repeat previous search (for _N-th occurrence).
45
+ N * Repeat previous search in reverse direction.
46
+ ESC-n * Repeat previous search, spanning files.
47
+ ESC-N * Repeat previous search, reverse dir. & spanning files.
48
+ ^O^N ^On * Search forward for (_N-th) OSC8 hyperlink.
49
+ ^O^P ^Op * Search backward for (_N-th) OSC8 hyperlink.
50
+ ^O^L ^Ol Jump to the currently selected OSC8 hyperlink.
51
+ ESC-u Undo (toggle) search highlighting.
52
+ ESC-U Clear search highlighting.
53
+ &_p_a_t_t_e_r_n * Display only matching lines.
54
+ ---------------------------------------------------
55
+ Search is case-sensitive unless changed with -i or -I.
56
+ A search pattern may begin with one or more of:
57
+ ^N or ! Search for NON-matching lines.
58
+ ^E or * Search multiple files (pass thru END OF FILE).
59
+ ^F or @ Start search at FIRST file (for /) or last file (for ?).
60
+ ^K Highlight matches, but don't move (KEEP position).
61
+ ^R Don't use REGULAR EXPRESSIONS.
62
+ ^S _n Search for match in _n-th parenthesized subpattern.
63
+ ^W WRAP search if no match found.
64
+ ^L Enter next character literally into pattern.
65
+ ---------------------------------------------------------------------------
66
+
67
+ JJUUMMPPIINNGG
68
+
69
+ g < ESC-< * Go to first line in file (or line _N).
70
+ G > ESC-> * Go to last line in file (or line _N).
71
+ p % * Go to beginning of file (or _N percent into file).
72
+ t * Go to the (_N-th) next tag.
73
+ T * Go to the (_N-th) previous tag.
74
+ { ( [ * Find close bracket } ) ].
75
+ } ) ] * Find open bracket { ( [.
76
+ ESC-^F _<_c_1_> _<_c_2_> * Find close bracket _<_c_2_>.
77
+ ESC-^B _<_c_1_> _<_c_2_> * Find open bracket _<_c_1_>.
78
+ ---------------------------------------------------
79
+ Each "find close bracket" command goes forward to the close bracket
80
+ matching the (_N-th) open bracket in the top line.
81
+ Each "find open bracket" command goes backward to the open bracket
82
+ matching the (_N-th) close bracket in the bottom line.
83
+
84
+ m_<_l_e_t_t_e_r_> Mark the current top line with <letter>.
85
+ M_<_l_e_t_t_e_r_> Mark the current bottom line with <letter>.
86
+ '_<_l_e_t_t_e_r_> Go to a previously marked position.
87
+ '' Go to the previous position.
88
+ ^X^X Same as '.
89
+ ESC-m_<_l_e_t_t_e_r_> Clear a mark.
90
+ ---------------------------------------------------
91
+ A mark is any upper-case or lower-case letter.
92
+ Certain marks are predefined:
93
+ ^ means beginning of the file
94
+ $ means end of the file
95
+ ---------------------------------------------------------------------------
96
+
97
+ CCHHAANNGGIINNGG FFIILLEESS
98
+
99
+ :e [_f_i_l_e] Examine a new file.
100
+ ^X^V Same as :e.
101
+ :n * Examine the (_N-th) next file from the command line.
102
+ :p * Examine the (_N-th) previous file from the command line.
103
+ :x * Examine the first (or _N-th) file from the command line.
104
+ ^O^O Open the currently selected OSC8 hyperlink.
105
+ :d Delete the current file from the command line list.
106
+ = ^G :f Print current file name.
107
+ ---------------------------------------------------------------------------
108
+
109
+ MMIISSCCEELLLLAANNEEOOUUSS CCOOMMMMAANNDDSS
110
+
111
+ -_<_f_l_a_g_> Toggle a command line option [see OPTIONS below].
112
+ --_<_n_a_m_e_> Toggle a command line option, by name.
113
+ __<_f_l_a_g_> Display the setting of a command line option.
114
+ ___<_n_a_m_e_> Display the setting of an option, by name.
115
+ +_c_m_d Execute the less cmd each time a new file is examined.
116
+
117
+ !_c_o_m_m_a_n_d Execute the shell command with $SHELL.
118
+ #_c_o_m_m_a_n_d Execute the shell command, expanded like a prompt.
119
+ |XX_c_o_m_m_a_n_d Pipe file between current pos & mark XX to shell command.
120
+ s _f_i_l_e Save input to a file.
121
+ v Edit the current file with $VISUAL or $EDITOR.
122
+ V Print version number of "less".
123
+ ---------------------------------------------------------------------------
124
+
125
+ OOPPTTIIOONNSS
126
+
127
+ Most options may be changed either on the command line,
128
+ or from within less by using the - or -- command.
129
+ Options may be given in one of two forms: either a single
130
+ character preceded by a -, or a name preceded by --.
131
+
132
+ -? ........ --help
133
+ Display help (from command line).
134
+ -a ........ --search-skip-screen
135
+ Search skips current screen.
136
+ -A ........ --SEARCH-SKIP-SCREEN
137
+ Search starts just after target line.
138
+ -b [_N] .... --buffers=[_N]
139
+ Number of buffers.
140
+ -B ........ --auto-buffers
141
+ Don't automatically allocate buffers for pipes.
142
+ -c ........ --clear-screen
143
+ Repaint by clearing rather than scrolling.
144
+ -d ........ --dumb
145
+ Dumb terminal.
146
+ -D xx_c_o_l_o_r . --color=xx_c_o_l_o_r
147
+ Set screen colors.
148
+ -e -E .... --quit-at-eof --QUIT-AT-EOF
149
+ Quit at end of file.
150
+ -f ........ --force
151
+ Force open non-regular files.
152
+ -F ........ --quit-if-one-screen
153
+ Quit if entire file fits on first screen.
154
+ -g ........ --hilite-search
155
+ Highlight only last match for searches.
156
+ -G ........ --HILITE-SEARCH
157
+ Don't highlight any matches for searches.
158
+ -h [_N] .... --max-back-scroll=[_N]
159
+ Backward scroll limit.
160
+ -i ........ --ignore-case
161
+ Ignore case in searches that do not contain uppercase.
162
+ -I ........ --IGNORE-CASE
163
+ Ignore case in all searches.
164
+ -j [_N] .... --jump-target=[_N]
165
+ Screen position of target lines.
166
+ -J ........ --status-column
167
+ Display a status column at left edge of screen.
168
+ -k _f_i_l_e ... --lesskey-file=_f_i_l_e
169
+ Use a compiled lesskey file.
170
+ -K ........ --quit-on-intr
171
+ Exit less in response to ctrl-C.
172
+ -L ........ --no-lessopen
173
+ Ignore the LESSOPEN environment variable.
174
+ -m -M .... --long-prompt --LONG-PROMPT
175
+ Set prompt style.
176
+ -n ......... --line-numbers
177
+ Suppress line numbers in prompts and messages.
178
+ -N ......... --LINE-NUMBERS
179
+ Display line number at start of each line.
180
+ -o [_f_i_l_e] .. --log-file=[_f_i_l_e]
181
+ Copy to log file (standard input only).
182
+ -O [_f_i_l_e] .. --LOG-FILE=[_f_i_l_e]
183
+ Copy to log file (unconditionally overwrite).
184
+ -p _p_a_t_t_e_r_n . --pattern=[_p_a_t_t_e_r_n]
185
+ Start at pattern (from command line).
186
+ -P [_p_r_o_m_p_t] --prompt=[_p_r_o_m_p_t]
187
+ Define new prompt.
188
+ -q -Q .... --quiet --QUIET --silent --SILENT
189
+ Quiet the terminal bell.
190
+ -r -R .... --raw-control-chars --RAW-CONTROL-CHARS
191
+ Output "raw" control characters.
192
+ -s ........ --squeeze-blank-lines
193
+ Squeeze multiple blank lines.
194
+ -S ........ --chop-long-lines
195
+ Chop (truncate) long lines rather than wrapping.
196
+ -t _t_a_g .... --tag=[_t_a_g]
197
+ Find a tag.
198
+ -T [_t_a_g_s_f_i_l_e] --tag-file=[_t_a_g_s_f_i_l_e]
199
+ Use an alternate tags file.
200
+ -u -U .... --underline-special --UNDERLINE-SPECIAL
201
+ Change handling of backspaces, tabs and carriage returns.
202
+ -V ........ --version
203
+ Display the version number of "less".
204
+ -w ........ --hilite-unread
205
+ Highlight first new line after forward-screen.
206
+ -W ........ --HILITE-UNREAD
207
+ Highlight first new line after any forward movement.
208
+ -x [_N[,...]] --tabs=[_N[,...]]
209
+ Set tab stops.
210
+ -X ........ --no-init
211
+ Don't use termcap init/deinit strings.
212
+ -y [_N] .... --max-forw-scroll=[_N]
213
+ Forward scroll limit.
214
+ -z [_N] .... --window=[_N]
215
+ Set size of window.
216
+ -" [_c[_c]] . --quotes=[_c[_c]]
217
+ Set shell quote characters.
218
+ -~ ........ --tilde
219
+ Don't display tildes after end of file.
220
+ -# [_N] .... --shift=[_N]
221
+ Set horizontal scroll amount (0 = one half screen width).
222
+
223
+ --autosave=[_m_/_!_*]
224
+ Actions which cause the history file to be saved.
225
+ --exit-follow-on-close
226
+ Exit F command on a pipe when writer closes pipe.
227
+ --file-size
228
+ Automatically determine the size of the input file.
229
+ --follow-name
230
+ The F command changes files if the input file is renamed.
231
+ --form-feed
232
+ Stop scrolling when a form feed character is reached.
233
+ --header=[_L[,_C[,_N]]]
234
+ Use _L lines (starting at line _N) and _C columns as headers.
235
+ --incsearch
236
+ Search file as each pattern character is typed in.
237
+ --intr=[_C]
238
+ Use _C instead of ^X to interrupt a read.
239
+ --lesskey-context=_t_e_x_t
240
+ Use lesskey source file contents.
241
+ --lesskey-src=_f_i_l_e
242
+ Use a lesskey source file.
243
+ --line-num-width=[_N]
244
+ Set the width of the -N line number field to _N characters.
245
+ --match-shift=[_N]
246
+ Show at least _N characters to the left of a search match.
247
+ --modelines=[_N]
248
+ Read _N lines from the input file and look for vim modelines.
249
+ --mouse
250
+ Enable mouse input.
251
+ --no-edit-warn
252
+ Don't warn when using v command on a file opened via LESSOPEN.
253
+ --no-keypad
254
+ Don't send termcap keypad init/deinit strings.
255
+ --no-histdups
256
+ Remove duplicates from command history.
257
+ --no-number-headers
258
+ Don't give line numbers to header lines.
259
+ --no-paste
260
+ Ignore pasted input.
261
+ --no-search-header-lines
262
+ Searches do not include header lines.
263
+ --no-search-header-columns
264
+ Searches do not include header columns.
265
+ --no-search-headers
266
+ Searches do not include header lines or columns.
267
+ --no-vbell
268
+ Disable the terminal's visual bell.
269
+ --redraw-on-quit
270
+ Redraw final screen when quitting.
271
+ --rscroll=[_C]
272
+ Set the character used to mark truncated lines.
273
+ --save-marks
274
+ Retain marks across invocations of less.
275
+ --search-options=[EFKNRW-]
276
+ Set default options for every search.
277
+ --show-preproc-errors
278
+ Display a message if preprocessor exits with an error status.
279
+ --proc-backspace
280
+ Process backspaces for bold/underline.
281
+ --PROC-BACKSPACE
282
+ Treat backspaces as control characters.
283
+ --proc-return
284
+ Delete carriage returns before newline.
285
+ --PROC-RETURN
286
+ Treat carriage returns as control characters.
287
+ --proc-tab
288
+ Expand tabs to spaces.
289
+ --PROC-TAB
290
+ Treat tabs as control characters.
291
+ --status-col-width=[_N]
292
+ Set the width of the -J status column to _N characters.
293
+ --status-line
294
+ Highlight or color the entire line containing a mark.
295
+ --use-backslash
296
+ Subsequent options use backslash as escape char.
297
+ --use-color
298
+ Enables colored text.
299
+ --wheel-lines=[_N]
300
+ Each click of the mouse wheel moves _N lines.
301
+ --wordwrap
302
+ Wrap lines at spaces.
303
+
304
+
305
+ ---------------------------------------------------------------------------
306
+
307
+ LLIINNEE EEDDIITTIINNGG
308
+
309
+ These keys can be used to edit text being entered
310
+ on the "command line" at the bottom of the screen.
311
+
312
+ RightArrow ..................... ESC-l ... Move cursor right one character.
313
+ LeftArrow ...................... ESC-h ... Move cursor left one character.
314
+ ctrl-RightArrow ESC-RightArrow ESC-w ... Move cursor right one word.
315
+ ctrl-LeftArrow ESC-LeftArrow ESC-b ... Move cursor left one word.
316
+ HOME ........................... ESC-0 ... Move cursor to start of line.
317
+ END ............................ ESC-$ ... Move cursor to end of line.
318
+ BACKSPACE ................................ Delete char to left of cursor.
319
+ DELETE ......................... ESC-x ... Delete char under cursor.
320
+ ctrl-BACKSPACE ESC-BACKSPACE ........... Delete word to left of cursor.
321
+ ctrl-DELETE .... ESC-DELETE .... ESC-X ... Delete word under cursor.
322
+ ctrl-U ......... ESC (MS-DOS only) ....... Delete entire line.
323
+ UpArrow ........................ ESC-k ... Retrieve previous command line.
324
+ DownArrow ...................... ESC-j ... Retrieve next command line.
325
+ TAB ...................................... Complete filename & cycle.
326
+ SHIFT-TAB ...................... ESC-TAB Complete filename & reverse cycle.
327
+ ctrl-L ................................... Complete filename, list all.
.agents/skills/chat-sdk/SKILL.md ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: chat-sdk
3
+ description: Build multi-platform chat bots with Chat SDK (`chat` npm package). Use when developers want to build a Slack, Teams, Google Chat, Discord, Telegram, GitHub, Linear, or WhatsApp bot, handle mentions, direct messages, subscribed threads, reactions, slash commands, cards, modals, files, or AI streaming, set up webhook routes or multi-adapter bots, send rich cards or streamed AI responses to chat platforms, or build a custom adapter or state adapter.
4
+ ---
5
+
6
+ # Chat SDK
7
+
8
+ Unified TypeScript SDK for building chat bots across Slack, Teams, Google Chat, Discord, Telegram, GitHub, Linear, and WhatsApp. Write bot logic once, deploy everywhere.
9
+
10
+ ## Start with published sources
11
+
12
+ When Chat SDK is installed in a user project, inspect the published files that ship in `node_modules`:
13
+
14
+ ```
15
+ node_modules/chat/docs/ # bundled docs
16
+ node_modules/chat/dist/index.d.ts # core API types
17
+ node_modules/chat/dist/adapters/index.d.ts # static adapter catalog types
18
+ node_modules/chat/dist/jsx-runtime.d.ts # JSX runtime types
19
+ node_modules/chat/docs/contributing/ # adapter-authoring docs
20
+ node_modules/chat/resources/guides/ # framework/platform guides (markdown)
21
+ node_modules/chat/resources/templates.json # starter templates (title, description, href)
22
+ ```
23
+
24
+ If one of the paths below does not exist, that package is not installed in the project yet.
25
+
26
+ Read these before writing code:
27
+ - `node_modules/chat/docs/getting-started.mdx` — install and setup
28
+ - `node_modules/chat/docs/usage.mdx` — `Chat` config and lifecycle
29
+ - `node_modules/chat/docs/handling-events.mdx` — event routing and handlers
30
+ - `node_modules/chat/docs/threads-messages-channels.mdx` — thread/channel/message model
31
+ - `node_modules/chat/docs/posting-messages.mdx` — post, edit, delete, schedule
32
+ - `node_modules/chat/docs/streaming.mdx` — AI SDK integration and streaming semantics
33
+ - `node_modules/chat/docs/cards.mdx` — JSX cards
34
+ - `node_modules/chat/docs/actions.mdx` — button/select interactions
35
+ - `node_modules/chat/docs/modals.mdx` — modal submit/close flows
36
+ - `node_modules/chat/docs/slash-commands.mdx` — slash command routing
37
+ - `node_modules/chat/docs/direct-messages.mdx` — DM behavior and `openDM()`
38
+ - `node_modules/chat/docs/files.mdx` — attachments/uploads
39
+ - `node_modules/chat/docs/state-adapters.mdx` — persistence, locking, dedupe
40
+ - `node_modules/chat/docs/adapters.mdx` — cross-platform feature matrix
41
+ - `node_modules/chat/docs/api/chat.mdx` — exact `Chat` API
42
+ - `node_modules/chat/docs/api/thread.mdx` — exact `Thread` API
43
+ - `node_modules/chat/docs/api/message.mdx` — exact `Message` API
44
+ - `node_modules/chat/docs/api/modals.mdx` — modal element and event details
45
+
46
+ For the specific adapter or state package you are using, inspect that installed package's `dist/index.d.ts` export surface in `node_modules`.
47
+
48
+ ## Adapter catalog subpath
49
+
50
+ Chat SDK exposes a zero-dependency static catalog at `chat/adapters`. Agents can import `ADAPTERS`, `ADAPTER_NAMES`, `getAdapter`, `isAdapterSlug`, `listEnvVars`, `getSecretEnvVars`, and metadata types like `CatalogAdapter` and `AdapterSlug` from this subpath without importing any adapter implementation package.
51
+
52
+ Use it for:
53
+ - Listing official and vendor-official adapter slugs, names, npm packages, groups, and platform vs state types.
54
+ - Building setup or onboarding flows that need package names, peer dependencies, and install guidance before any adapter is installed.
55
+ - Discovering required, optional, and credential-mode environment variables for an adapter, including which variables are secrets.
56
+ - Keeping vendor-official adapter docs and metadata aligned with the catalog when adding or updating a listed adapter.
57
+
58
+ ## Available resources
59
+
60
+ <!-- RESOURCES:START -->
61
+
62
+ ### Guides
63
+
64
+ - `node_modules/chat/resources/guides/how-to-build-an-ai-agent-for-slack-with-chat-sdk-and-ai-sdk.md` — Build a Slack AI agent using Chat SDK, AI SDK's ToolLoopAgent, and Vercel AI Gateway. Covers project setup, tool definitions, streaming responses, deployment to Vercel, and scaling tool selection with toolpick.
65
+ - `node_modules/chat/resources/guides/human-in-the-loop-with-chat-sdk-and-workflow-sdk.md` — Pause durable workflows on Slack approval cards using Chat SDK and Workflow SDK. Uses createWebhook to suspend workflows until a button click, with patterns for multi-stage approvals, timeouts via durable sleep, and approver validation.
66
+ - `node_modules/chat/resources/guides/liveblocks-chat-sdk-ai-sdk.md` — Build an AI agent that replies to @-mentions in Liveblocks comment threads with streamed responses and tool calling. Uses Chat SDK, the Liveblocks adapter, AI SDK's ToolLoopAgent, and Redis for thread subscriptions and distributed locking.
67
+ - `node_modules/chat/resources/guides/slack-bot-vercel-blob.md` — Build a Slack bot that lists, reads, uploads, and deletes files in Vercel Blob through tool calls. Uses Chat SDK, AI SDK's ToolLoopAgent, and Files SDK's createFileTools factory with approval-gated write tools and a read-only mode.
68
+ - `node_modules/chat/resources/guides/run-and-track-deploys-from-slack.md` — Build a Slack deploy bot with Chat SDK and Vercel Workflow. Dispatch GitHub Actions from a slash command, gate production behind approval, poll for completion, and notify Linear and GitHub when the run finishes.
69
+ - `node_modules/chat/resources/guides/triage-form-submissions-with-chat-sdk.md` — Build a Slack bot that triages form submissions with interactive cards. Forward, edit, or mark as spam without leaving Slack. Built with Chat SDK, Hono, and Resend.
70
+ - `node_modules/chat/resources/guides/how-to-build-a-slack-bot-with-next-js-and-redis.md` — This guide walks through building a Slack bot with Next.js, covering project setup, Slack app configuration, event handling, interactive features, and deployment.
71
+ - `node_modules/chat/resources/guides/create-a-discord-support-bot-with-nuxt-and-redis.md` — This guide walks through building a Discord support bot with Nuxt, covering project setup, Discord app configuration, Gateway forwarding, AI-powered responses, and deployment.
72
+ - `node_modules/chat/resources/guides/ship-a-github-code-review-bot-with-hono-and-redis.md` — This guide walks through building a GitHub bot that reviews pull requests on demand. When a user @mentions the bot on a PR, Chat SDK picks up the mention, spins up a Vercel Sandbox with the repo cloned, and uses AI SDK to analyze the diff.
73
+
74
+ ### Templates
75
+
76
+ Listed in `node_modules/chat/resources/templates.json`:
77
+
78
+ - **Chat SDK Liveblocks Bot** — Build a bot that you can engage with inside Liveblocks. (https://vercel.com/templates/next.js/chat-sdk-liveblocks-bot)
79
+ - **Durable iMessage Agent** — Durable iMessage agent powered by the Sendblue adapter. (https://vercel.com/templates/nitro/durable-imessage-ai-agent)
80
+ - **Knowledge Agent** — Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base. (https://vercel.com/templates/nuxt/chat-sdk-knowledge-agent)
81
+ - **Community Agent** — Open source AI-powered Slack community management bot with a built-in Next.js admin panel. Uses Chat SDK, AI SDK, and Vercel Workflow. (https://vercel.com/templates/next.js/chat-sdk-community-agent)
82
+
83
+ <!-- RESOURCES:END -->
84
+
85
+ ## Quick start
86
+
87
+ ```typescript
88
+ import { Chat } from "chat";
89
+ import { createSlackAdapter } from "@chat-adapter/slack";
90
+ import { createRedisState } from "@chat-adapter/state-redis";
91
+
92
+ const bot = new Chat({
93
+ userName: "mybot",
94
+ adapters: {
95
+ slack: createSlackAdapter(),
96
+ },
97
+ state: createRedisState(),
98
+ dedupeTtlMs: 600_000,
99
+ });
100
+
101
+ bot.onNewMention(async (thread) => {
102
+ await thread.subscribe();
103
+ await thread.post("Hello! I'm listening to this thread.");
104
+ });
105
+
106
+ bot.onSubscribedMessage(async (thread, message) => {
107
+ await thread.post(`You said: ${message.text}`);
108
+ });
109
+ ```
110
+
111
+ ## Core concepts
112
+
113
+ - **Chat** — main entry point; coordinates adapters, routing, locks, and state
114
+ - **Adapters** — platform-specific integrations for Slack, Teams, Google Chat, Discord, Telegram, GitHub, Linear, and WhatsApp
115
+ - **State adapters** — persistence for subscriptions, locks, dedupe, and thread state
116
+ - **Thread** — conversation context with `post()`, `stream()`, `subscribe()`, `setState()`, `startTyping()`
117
+ - **Message** — normalized content with `text`, `formatted`, attachments, author info, and platform `raw`
118
+ - **Channel** — container for threads and top-level posts
119
+
120
+ ## Event handlers
121
+
122
+ | Handler | Trigger |
123
+ |---------|---------|
124
+ | `onNewMention` | Bot @-mentioned in an unsubscribed thread |
125
+ | `onDirectMessage` | New DM in an unsubscribed DM thread |
126
+ | `onSubscribedMessage` | Any message in a subscribed thread |
127
+ | `onNewMessage(regex)` | Regex match in an unsubscribed thread |
128
+ | `onReaction(emojis?)` | Emoji added or removed |
129
+ | `onAction(actionIds?)` | Button clicks and select/radio interactions |
130
+ | `onModalSubmit(callbackId?)` | Modal form submitted |
131
+ | `onModalClose(callbackId?)` | Modal dismissed/cancelled |
132
+ | `onSlashCommand(commands?)` | Slash command invocation |
133
+ | `onAssistantThreadStarted` | Slack assistant thread opened |
134
+ | `onAssistantContextChanged` | Slack assistant context changed |
135
+ | `onAppHomeOpened` | Slack App Home opened |
136
+ | `onMemberJoinedChannel` | Slack member joined channel event |
137
+
138
+ Read `node_modules/chat/docs/handling-events.mdx`, `node_modules/chat/docs/actions.mdx`, `node_modules/chat/docs/modals.mdx`, and `node_modules/chat/docs/slash-commands.mdx` before wiring handlers. `onDirectMessage` behavior is documented in `node_modules/chat/docs/direct-messages.mdx`.
139
+
140
+ ## Streaming
141
+
142
+ Pass any `AsyncIterable<string>` to `thread.post()`. For AI SDK, prefer `result.fullStream` over `result.textStream` when available so step boundaries are preserved.
143
+
144
+ ```typescript
145
+ import { ToolLoopAgent } from "ai";
146
+
147
+ const agent = new ToolLoopAgent({ model: "anthropic/claude-4.5-sonnet" });
148
+
149
+ bot.onNewMention(async (thread, message) => {
150
+ const result = await agent.stream({ prompt: message.text });
151
+ await thread.post(result.fullStream);
152
+ });
153
+ ```
154
+
155
+ Key details:
156
+ - `streamingUpdateIntervalMs` controls post+edit fallback cadence
157
+ - `fallbackStreamingPlaceholderText` defaults to `"..."`; set `null` to disable
158
+ - Structured `StreamChunk` support is Slack-only; other adapters ignore non-text chunks
159
+
160
+ ## Cards and modals (JSX)
161
+
162
+ Set `jsxImportSource: "chat"` in `tsconfig.json`.
163
+
164
+ Card components:
165
+ - `Card`, `CardText`, `Section`, `Fields`, `Field`, `Button`, `CardLink`, `LinkButton`, `Actions`, `Select`, `SelectOption`, `RadioSelect`, `Table`, `Image`, `Divider`
166
+
167
+ Modal components:
168
+ - `Modal`, `TextInput`, `Select`, `SelectOption`, `RadioSelect`
169
+
170
+ `Button` and `Modal` accept a `callbackUrl` prop — when triggered, the SDK POSTs the action payload to that URL in addition to firing any `onAction` / `onModalSubmit` handler. Use this for webhook-based workflow flows. See `node_modules/chat/docs/actions.mdx` and `node_modules/chat/docs/modals.mdx`.
171
+
172
+ ```tsx
173
+ await thread.post(
174
+ <Card title="Order #1234">
175
+ <CardText>Your order has been received.</CardText>
176
+ <Actions>
177
+ <Button id="approve" style="primary">Approve</Button>
178
+ <Button id="reject" style="danger">Reject</Button>
179
+ </Actions>
180
+ </Card>
181
+ );
182
+ ```
183
+
184
+ ## Adapter inventory
185
+
186
+ See [chat-sdk.dev/adapters](https://chat-sdk.dev/adapters) for the current list of official, vendor-official, and community adapters, including package names and authors. For the exact factory function and config types of an installed adapter, inspect its `dist/index.d.ts` in `node_modules`.
187
+
188
+ ## Building a custom adapter
189
+
190
+ Read these published docs first:
191
+ - `node_modules/chat/docs/contributing/building.mdx`
192
+ - `node_modules/chat/docs/contributing/testing.mdx`
193
+ - `node_modules/chat/docs/contributing/publishing.mdx`
194
+
195
+ Also inspect:
196
+ - `node_modules/chat/dist/index.d.ts` — `Adapter` and related interfaces
197
+ - `node_modules/@chat-adapter/shared/dist/index.d.ts` — shared errors and utilities
198
+ - Installed official adapter `dist/index.d.ts` files — reference implementations for config and APIs
199
+
200
+ A custom adapter needs request verification, webhook parsing, message/thread/channel operations, ID encoding/decoding, and a format converter. Use `BaseFormatConverter` from `chat` and shared utilities from `@chat-adapter/shared`.
201
+
202
+ ## Webhook setup
203
+
204
+ Each registered adapter exposes `bot.webhooks.<name>`. Wire those directly to your HTTP framework routes. See `node_modules/chat/resources/guides/how-to-build-a-slack-bot-with-next-js-and-redis.md` and `node_modules/chat/resources/guides/create-a-discord-support-bot-with-nuxt-and-redis.md` for framework-specific route patterns.
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
Binary file (404 Bytes). View file
 
README.md ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: InsureChat
3
+ emoji: "\U0001F6E1\uFE0F"
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ app_file: run_insurechat.py
8
+ pinned: false
9
+ tags:
10
+ - healthcare
11
+ - local-ai
12
+ - rag
13
+ - privacy
14
+ - multilingual
15
+ - track-local-ai
16
+ - track-healthcare
17
+ - badge-open-source
18
+ - badge-multilingual
19
+ - badge-privacy-first
20
+ short_description: 'A chatbot to ask anything or upload medical bills'
21
+ hf_oauth: true
22
+ hf_oauth_scopes:
23
+ - inference-api
24
+ ---
25
+
26
+ # InsureChat
27
+
28
+ InsureChat is a local Gradio assistant for U.S. medical insurance definitions, medical bills, EOBs, and claims. It combines a local knowledge base, OCR, FAISS retrieval, and optional GGUF language models through `llama-cpp-python`.
29
+
30
+ No OpenAI API or cloud inference service is used. After setup and model downloads, document processing and inference run locally.
31
+
32
+ ## Hackathon Submission
33
+
34
+ - **Social media post:** [Link will be added after publishing](SOCIAL_MEDIA_POST_URL)
35
+ - **Demo video:** [Link will be added after recording](DEMO_VIDEO_URL)
36
+
37
+ ### The Idea
38
+
39
+ Medical bills and U.S. insurance terms can be difficult to understand, especially for newcomers and people who prefer another language. InsureChat is a privacy-first assistant that explains common insurance concepts before a document is uploaded, then switches to answers grounded in the user's active bill, EOB, claim, image, or text file after it is processed.
40
+
41
+ ### How It Was Built
42
+
43
+ The app uses Gradio for the interface and a local retrieval-augmented generation pipeline for question answering. It extracts text from PDFs and text files, applies Tesseract OCR to images and scanned PDFs, retrieves relevant context with FAISS or a lexical fallback, and parses important bill fields such as billed amount, discount, plan payment, service date, and patient responsibility. Uploaded documents remain session-specific so an earlier bill cannot influence a new session.
44
+
45
+ ### Technology
46
+
47
+ - Python and Gradio
48
+ - `llama-cpp-python` with local GGUF models
49
+ - Aya Expanse 8B for multilingual translation
50
+ - Llama 3.1 8B for optional reasoning and structured extraction
51
+ - FAISS and Sentence Transformers for retrieval
52
+ - Tesseract, PyMuPDF, Pillow, and pypdf for OCR and document processing
53
+ - Local Markdown and text files for trusted insurance definitions
54
+
55
+ ## Features
56
+
57
+ - Answers insurance definitions from local Markdown, text, and PDF knowledge files.
58
+ - OCRs JPG, PNG, TIFF, and scanned PDF medical bills.
59
+ - Extracts billed amount, discounts, patient balance, service date, and related fields.
60
+ - Uses Aya Expanse 8B for local multilingual translation.
61
+ - Uses Llama 3.1 8B for optional reasoning and structured extraction.
62
+ - Keeps only one GGUF model loaded at a time to reduce peak RAM and VRAM use.
63
+ - Continues with deterministic RAG and regex fallbacks when optional GGUF models are missing.
64
+
65
+ ### Answer Routing
66
+
67
+ - Definitions and general insurance questions use the fast local glossary/RAG path without loading Llama.
68
+ - Misspelled or unknown terms receive a correction or close-term suggestion plus a trusted glossary link.
69
+ - Direct uploaded-bill fields such as discount, amount due, service date, and plan payment use deterministic parsed values.
70
+ - Llama is reserved for structured extraction and questions that require reasoning over the active PDF, image, or text upload.
71
+ - Aya is loaded only when a non-English answer must be translated.
72
+ - Question language and answer language are selected independently in the interface.
73
+ - Hindi questions may be entered in Devanagari or as Romanized Hindi by selecting the matching question-language option.
74
+
75
+ ## Requirements
76
+
77
+ - Python 3.10 or newer
78
+ - Approximately 6 GB of free space for Aya alone
79
+ - Approximately 12-14 GB for all three Q4 GGUF models
80
+ - Tesseract OCR for JPG, PNG, TIFF, and scanned PDF processing
81
+ - Enough system RAM to load the selected model; models are loaded by role and are not all required for every request
82
+
83
+ ### Install Tesseract
84
+
85
+ Windows:
86
+
87
+ 1. Install Tesseract from [UB Mannheim's Windows builds](https://github.com/UB-Mannheim/tesseract/wiki).
88
+ 2. Enable the option to add Tesseract to `PATH`, or install it in `C:\Program Files\Tesseract-OCR`.
89
+
90
+ macOS:
91
+
92
+ ```bash
93
+ brew install tesseract
94
+ ```
95
+
96
+ Ubuntu/Debian:
97
+
98
+ ```bash
99
+ sudo apt install tesseract-ocr
100
+ ```
101
+
102
+ ## Setup
103
+
104
+ Create and activate a virtual environment:
105
+
106
+ ```powershell
107
+ python -m venv venv
108
+ venv\Scripts\activate
109
+ ```
110
+
111
+ On macOS/Linux, activate it with:
112
+
113
+ ```bash
114
+ source venv/bin/activate
115
+ ```
116
+
117
+ Install the InsureChat dependencies:
118
+
119
+ ```powershell
120
+ python -m pip install --upgrade pip
121
+ python -m pip install -r insurechat/requirements.txt
122
+ ```
123
+
124
+ The requirements install Python packages only. They do not install Tesseract or download multi-gigabyte GGUF model files.
125
+
126
+ ## Download Models
127
+
128
+ Models are intentionally excluded from Git and are not downloaded automatically. Each user must download the models needed on their own computer.
129
+
130
+ Translation model:
131
+
132
+ ```powershell
133
+ python insurechat/download_models.py --model aya-8b
134
+ ```
135
+
136
+ Optional alternative reasoning model:
137
+
138
+ ```powershell
139
+ python insurechat/download_models.py --model nemotron-4b
140
+ ```
141
+
142
+ Recommended document extraction and reasoning model:
143
+
144
+ ```powershell
145
+ python insurechat/download_models.py --model llama3-8b
146
+ ```
147
+
148
+ The files are stored in `insurechat/models/`:
149
+
150
+ | Model | Role | Approximate Q4 size |
151
+ | --- | --- | --- |
152
+ | Aya Expanse 8B | Translation | 4.7 GB |
153
+ | Nemotron Mini 4B | Reasoning | 2-3 GB |
154
+ | Llama 3.1 8B | Extraction/reasoning fallback | 4.5-5 GB |
155
+
156
+ The app selects models by role and keeps only one GGUF loaded at a time with a 4,096-token context window. Switching between Llama reasoning and Aya translation unloads the current model before loading the next one. This lowers peak memory use, but the first request after a role switch can take longer while the next model loads.
157
+
158
+ Performance depends heavily on hardware. On integrated graphics or CPU-only systems, an 8B response or model switch may take from several seconds to a few minutes. A discrete GPU with sufficient VRAM will generally respond faster.
159
+
160
+ For the recommended setup, install Aya and Llama 3.1. Nemotron is an optional lighter English reasoning alternative and is not required when Llama is installed.
161
+
162
+ Without the models, the application still starts:
163
+
164
+ - Local glossary definitions continue to work.
165
+ - OCR and regex medical-bill extraction continue to work.
166
+ - Translation is unavailable without Aya.
167
+ - LLM reasoning/extraction is unavailable without Nemotron or Llama.
168
+
169
+ ## Model Verification
170
+
171
+ The recommended Aya and Llama configuration was tested locally with the downloaded Q4 GGUF files:
172
+
173
+ - Llama 3.1 8B generated a grounded explanation comparing deductible, copay, and coinsurance.
174
+ - Llama 3.1 8B completed the structured document-extraction path and returned valid JSON fields.
175
+ - Aya Expanse 8B translated an English insurance explanation into Spanish.
176
+ - Switching from Llama to Aya closed the previous model before loading the next model.
177
+ - Explicit cleanup released the active model after inference.
178
+
179
+ The complete reasoning, extraction, translation, and cleanup test took about six minutes on the tested integrated AMD Vulkan graphics system. This is a hardware-specific measurement, not an expected time for every computer.
180
+
181
+ ## Run
182
+
183
+ From the repository root:
184
+
185
+ ```powershell
186
+ python insurechat/app.py
187
+ ```
188
+
189
+ Open the URL printed by Gradio, normally <http://127.0.0.1:7860>.
190
+
191
+ ## Troubleshooting
192
+
193
+ ### Translation unavailable
194
+
195
+ Confirm that `insurechat/models/aya-expanse-8b-Q4_K_M.gguf` exists, then restart the app.
196
+
197
+ ### No text extracted from an image
198
+
199
+ Confirm both components are installed:
200
+
201
+ ```powershell
202
+ python -c "import pytesseract; print(pytesseract.get_tesseract_version())"
203
+ ```
204
+
205
+ If that fails, install `pytesseract` from the requirements and install the separate Tesseract application.
206
+
207
+ ### Scanned PDF has no text
208
+
209
+ Install `pymupdf` and `pytesseract`. InsureChat renders scanned PDF pages locally and sends the rendered images to Tesseract OCR.
210
+
211
+ ### llama-cpp tries to compile on Windows
212
+
213
+ `insurechat/requirements.txt` includes the official prebuilt CPU wheel index. A native compiler should not be required for supported Python versions.
214
+
215
+ ## Privacy
216
+
217
+ Uploaded documents, OCR text, retrieval, and GGUF inference remain on the local computer. Internet access is only needed during dependency and model installation, or when the app displays an external reference link for a definition not found locally.
218
+ >>>>>>> local-pdf-RAG-updated-with-medical-models-final
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+
4
+
5
+ def respond(
6
+ message,
7
+ history: list[dict[str, str]],
8
+ system_message,
9
+ max_tokens,
10
+ temperature,
11
+ top_p,
12
+ hf_token: gr.OAuthToken,
13
+ ):
14
+ """
15
+ For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
+ """
17
+ client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
+
19
+ messages = [{"role": "system", "content": system_message}]
20
+
21
+ messages.extend(history)
22
+
23
+ messages.append({"role": "user", "content": message})
24
+
25
+ response = ""
26
+
27
+ for message in client.chat_completion(
28
+ messages,
29
+ max_tokens=max_tokens,
30
+ stream=True,
31
+ temperature=temperature,
32
+ top_p=top_p,
33
+ ):
34
+ choices = message.choices
35
+ token = ""
36
+ if len(choices) and choices[0].delta.content:
37
+ token = choices[0].delta.content
38
+
39
+ response += token
40
+ yield response
41
+
42
+
43
+ """
44
+ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
+ """
46
+ chatbot = gr.ChatInterface(
47
+ respond,
48
+ additional_inputs=[
49
+ gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
+ gr.Slider(
53
+ minimum=0.1,
54
+ maximum=1.0,
55
+ value=0.95,
56
+ step=0.05,
57
+ label="Top-p (nucleus sampling)",
58
+ ),
59
+ ],
60
+ )
61
+
62
+ with gr.Blocks() as demo:
63
+ with gr.Sidebar():
64
+ gr.LoginButton()
65
+ chatbot.render()
66
+
67
+
68
+ if __name__ == "__main__":
69
+ demo.launch()
debug_index.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import insurechat.app as app
2
+ print('Index texts:', len(app.index.texts))
3
+ if app.index.texts:
4
+ print('Sample text 0:', app.index.texts[0][:200])
5
+ else:
6
+ print('No texts loaded')
7
+ print('Query copay results count:', len(app.index.query('copay', topk=3)))
gradio.err.log ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ ggml_vulkan: Found 1 Vulkan devices:
2
+ ggml_vulkan: 0 = AMD Radeon(TM) Graphics (AMD proprietary driver) | uma: 1 | fp16: 1 | bf16: 0 | warp size: 64 | shared memory: 65536 | int dot: 0 | matrix cores: none
gradio.out.log ADDED
File without changes
image_pdf_input.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ from PIL import Image
4
+ import pytesseract
5
+ import shutil
6
+ import pytesseract
7
+
8
+
9
+
10
+
11
+ from langchain_community.document_loaders import PyPDFLoader
12
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
13
+ from langchain_community.embeddings import HuggingFaceEmbeddings
14
+ from langchain_community.vectorstores import FAISS
15
+ #from langchain_community.llms import Ollama
16
+ from langchain_ollama import OllamaLLM
17
+
18
+ from langchain_core.documents import Document
19
+
20
+ vectorstore = None
21
+ retriever = None
22
+ llm = None
23
+
24
+
25
+ def process_files(files):
26
+ global vectorstore, retriever, llm
27
+
28
+ all_docs = []
29
+
30
+ for file in files:
31
+ print(" Processing:", file.name)
32
+
33
+ # PDF Processing
34
+ if file.name.endswith(".pdf"):
35
+ loader = PyPDFLoader(file.name)
36
+ documents = loader.load()
37
+ print(" 📄 Pages:", len(documents))
38
+ all_docs.extend(documents)
39
+
40
+ # Image Processing (OCR)
41
+ elif file.name.endswith((".jpg", ".jpeg", ".png")):
42
+ img = Image.open(file.name)
43
+ text = pytesseract.image_to_string(img)
44
+ print(" 🖼 Extracted text length:", len(text))
45
+
46
+ image_doc = Document(page_content=text)
47
+ all_docs.append(image_doc)
48
+
49
+ print(" Splitting text into chunks...")
50
+
51
+ splitter = RecursiveCharacterTextSplitter(
52
+ chunk_size=500,
53
+ chunk_overlap=100
54
+ )
55
+
56
+ chunks = splitter.split_documents(all_docs)
57
+ print(" Total chunks:", len(chunks))
58
+
59
+ print(" Creating embeddings...")
60
+ embeddings = HuggingFaceEmbeddings(
61
+ model_name="all-MiniLM-L6-v2"
62
+ )
63
+
64
+ vectorstore = FAISS.from_documents(chunks, embeddings)
65
+ #retriever = vectorstore.as_retriever() #not reading the numbers in the bill so added logging below
66
+ retriever = vectorstore.as_retriever(search_kwargs={"k": 8})
67
+
68
+ #llm = Ollama(model="llama3")
69
+ llm = OllamaLLM(model="llama3")
70
+
71
+ print(" Multi-source RAG ready!")
72
+
73
+ return f"{len(files)} files processed successfully!"
74
+
75
+
76
+ def chat_with_docs(question):
77
+ global retriever, llm
78
+
79
+ if retriever is None:
80
+ return "Please upload and process files first."
81
+
82
+ print(" Question:", question)
83
+
84
+ # docs = retriever.invoke(question) # not reading the numbers in the bill so added logging below
85
+ docs = retriever.invoke(question)
86
+
87
+ print("\n--- Retrieved Context ---")
88
+ for i, doc in enumerate(docs):
89
+ print(f"\nChunk {i+1}:\n", doc.page_content[:500])
90
+ print("\n-------------------------\n")
91
+ #
92
+ print(" Retrieved chunks:", len(docs))
93
+
94
+ context = "\n\n".join([doc.page_content for doc in docs])
95
+
96
+ prompt = f"""
97
+ You are a financial assistant.
98
+ Use ONLY the provided context.
99
+
100
+ Context:
101
+ {context}
102
+
103
+ Question:
104
+ {question}
105
+
106
+ Answer:
107
+ """
108
+
109
+ print(" Sending to LLM...")
110
+ response = llm.invoke(prompt)
111
+ print(" Response generated.")
112
+
113
+ return str(response)
114
+
115
+
116
+
117
+ with gr.Blocks() as demo:
118
+ gr.Markdown("# Multi-Document RAG (PDF + Image)")
119
+ gr.Markdown("Upload PDFs and/or Images, then ask questions.")
120
+
121
+ file_input = gr.File(
122
+ file_count="multiple",
123
+ file_types=[".pdf", ".jpg", ".jpeg", ".png"]
124
+ )
125
+
126
+ process_button = gr.Button("Process Files")
127
+ status_output = gr.Textbox(label="Status")
128
+
129
+ question_input = gr.Textbox(label="Ask a Question")
130
+ answer_output = gr.Textbox(label="Answer")
131
+
132
+ process_button.click(process_files, inputs=file_input, outputs=status_output)
133
+ question_input.submit(chat_with_docs, inputs=question_input, outputs=answer_output)
134
+
135
+ demo.launch()
insurechat/.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ models/
2
+ faiss_index/
3
+ __pycache__/
4
+ *.pyc
5
+ *.gguf
insurechat/app.py ADDED
@@ -0,0 +1,1288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ InsureChat - main Gradio app (minimal runnable scaffold)
3
+ - Local RAG with llama-cpp GGUF LLMs, FAISS persistence
4
+ - Lightweight fallbacks for OCR (pytesseract) and PDF (pymupdf/pypdf)
5
+
6
+ Run after setup:
7
+ python app.py
8
+ """
9
+
10
+ import os
11
+ import json
12
+ import threading
13
+ import gc
14
+ from contextlib import contextmanager
15
+ from pathlib import Path
16
+ import re
17
+ import io
18
+ from difflib import get_close_matches
19
+ try:
20
+ from . import sbc_utils
21
+ except Exception:
22
+ # When the module is executed as a script (e.g. `python insurechat/app.py`) the
23
+ # package-relative import can fail with "attempted relative import with no
24
+ # known parent package". Fall back to an absolute import so the module can
25
+ # be run both as a package and as a script (useful for Hugging Face Spaces).
26
+ import sbc_utils
27
+
28
+ # LLM + embeddings + vectorstore imports are optional until models are present
29
+ try:
30
+ from llama_cpp import Llama
31
+ from llama_cpp import llama_cpp as _llama_backend
32
+ # Initialize llama.cpp before Torch/FAISS load their native runtimes. On
33
+ # Windows, doing this in the opposite order can crash backend_init().
34
+ _llama_backend.llama_backend_init()
35
+ except Exception:
36
+ Llama = None
37
+
38
+ import gradio as gr
39
+
40
+ try:
41
+ from sentence_transformers import SentenceTransformer
42
+ from sklearn.feature_extraction.text import TfidfVectorizer
43
+ except Exception:
44
+ SentenceTransformer = None
45
+
46
+ try:
47
+ import faiss
48
+ except Exception:
49
+ faiss = None
50
+
51
+ # PDF and OCR
52
+ try:
53
+ from pypdf import PdfReader
54
+ except Exception:
55
+ PdfReader = None
56
+
57
+ try:
58
+ import fitz
59
+ except Exception:
60
+ fitz = None
61
+
62
+ try:
63
+ import pytesseract
64
+ from PIL import Image
65
+ except Exception:
66
+ pytesseract = None
67
+ Image = None
68
+
69
+ try:
70
+ from transformers import pipeline
71
+ except Exception:
72
+ pipeline = None
73
+
74
+ # Basic paths
75
+ ROOT = Path(__file__).parent
76
+ MODELS_DIR = ROOT / "models"
77
+ FAISS_DIR = ROOT / "faiss_index"
78
+ KB_DIR = ROOT / "knowledge_base"
79
+ FAISS_DIR.mkdir(exist_ok=True)
80
+ KB_DIR.mkdir(exist_ok=True)
81
+ MODELS_DIR.mkdir(exist_ok=True)
82
+
83
+ # System prompt
84
+ SYSTEM_PROMPT = (
85
+ "You are InsureChat, a local medical insurance assistant for people who may be new to U.S. health insurance.\n"
86
+ "Explain terms in plain language, define acronyms, and avoid assuming the user knows words like copay, deductible, EOB, claim, or allowed amount.\n"
87
+ "Use DOCUMENT CONTEXT first. If context comes from an uploaded bill, EOB, claim, or plan document, cite the source and explain any math step by step.\n"
88
+ "Never include local file paths in the answer. If context is missing, say what information is needed instead of guessing. Do not provide legal, tax, or medical advice.\n"
89
+ "For definitions, answer briefly with a simple example and source when available."
90
+ )
91
+
92
+ MODEL_ROLE_KEYWORDS = {
93
+ "extract": ("llama-3.1", "llama3.1", "meta-llama", "llama", "parse", "vl", "vision", "ocr", "asr"),
94
+ "reason": ("nemotron", "llama-3.1", "llama3.1", "meta-llama", "llama"),
95
+ "translate": ("aya", "tiny-aya", "expanse", "multilingual"),
96
+ "embed": ("embed", "embedding"),
97
+ }
98
+
99
+ LANGUAGE_NAMES = {
100
+ 'en': 'English', 'es': 'Spanish', 'fr': 'French', 'hi': 'Hindi',
101
+ 'hi-latn': 'Hindi (Romanized)',
102
+ 'zh': 'Chinese', 'ar': 'Arabic', 'pt': 'Portuguese', 'de': 'German',
103
+ 'ja': 'Japanese', 'ko': 'Korean', 'ru': 'Russian', 'vi': 'Vietnamese',
104
+ }
105
+
106
+ ONLINE_GLOSSARY_URL = "https://www.healthcare.gov/glossary/"
107
+
108
+ INSURANCE_TERM_ALIASES = {
109
+ 'health insurance': ['health insurance', 'medical insurance', 'insurance'],
110
+ 'copay': ['copay', 'copayment', 'co-pay'],
111
+ 'deductible': ['deductible'],
112
+ 'coinsurance': ['coinsurance', 'co-insurance'],
113
+ 'out-of-pocket maximum': ['out-of-pocket maximum', 'out of pocket maximum', 'oop max'],
114
+ 'allowed amount': ['allowed amount', 'allowable', 'eligible expense', 'negotiated rate'],
115
+ 'discount': ['discount', 'adjustment', 'network discount', 'provider discount'],
116
+ 'eob': ['eob', 'explanation of benefits'],
117
+ 'claim': ['claim'],
118
+ 'premium': ['premium'],
119
+ 'in-network': ['in-network', 'in network'],
120
+ 'out-of-network': ['out-of-network', 'out of network', 'non-participating'],
121
+ 'balance billing': ['balance billing', 'balance bill'],
122
+ }
123
+
124
+ _ACTIVE_LLM = None
125
+ _ACTIVE_LLM_PATH = None
126
+ _LLM_LOCK = threading.RLock()
127
+
128
+ # RAG index: uses FAISS + sentence-transformers when available, otherwise TF-IDF fallback
129
+ class RAGIndex:
130
+ def __init__(self, index_dir: Path, embed_model_name: str = 'all-MiniLM-L6-v2'):
131
+ self.index_dir = Path(index_dir)
132
+ self.embed_model_name = embed_model_name
133
+ self.texts = []
134
+ self.meta = []
135
+ self.embedding_model = None
136
+ self.faiss_index = None
137
+ self.dimension = None
138
+ self.use_faiss = faiss is not None
139
+
140
+ if SentenceTransformer is not None:
141
+ try:
142
+ self.embedding_model = SentenceTransformer(self.embed_model_name)
143
+ self.dimension = self.embedding_model.get_sentence_embedding_dimension()
144
+ except Exception:
145
+ self.embedding_model = None
146
+
147
+ self._load()
148
+
149
+ def _meta_path(self):
150
+ return self.index_dir / 'meta.json'
151
+
152
+ def _faiss_path(self):
153
+ return self.index_dir / 'index.faiss'
154
+
155
+ def _load(self):
156
+ if self._meta_path().exists():
157
+ with open(self._meta_path(), 'r', encoding='utf8') as f:
158
+ data = json.load(f)
159
+ self.texts = [d['text'] for d in data.get('docs', [])]
160
+ self.meta = [d.get('meta', {}) for d in data.get('docs', [])]
161
+
162
+ if self.use_faiss and self._faiss_path().exists() and self.dimension:
163
+ try:
164
+ self.faiss_index = faiss.read_index(str(self._faiss_path()))
165
+ except Exception:
166
+ self.faiss_index = None
167
+
168
+ def save(self):
169
+ self.index_dir.mkdir(parents=True, exist_ok=True)
170
+ data = {'docs': [{'text': t, 'meta': m} for t, m in zip(self.texts, self.meta)]}
171
+ with open(self._meta_path(), 'w', encoding='utf8') as f:
172
+ json.dump(data, f, ensure_ascii=False, indent=2)
173
+ if self.use_faiss and self.faiss_index is not None:
174
+ faiss.write_index(self.faiss_index, str(self._faiss_path()))
175
+
176
+ def _embed(self, texts):
177
+ if self.embedding_model is not None:
178
+ return self.embedding_model.encode(texts, convert_to_numpy=True)
179
+ # fallback: TF-IDF vectors (dense) via scikit-learn
180
+ try:
181
+ from sklearn.feature_extraction.text import TfidfVectorizer
182
+ vec = TfidfVectorizer().fit(self.texts + list(texts))
183
+ return vec.transform(texts).toarray()
184
+ except Exception:
185
+ # last resort: random vectors (deterministic hash)
186
+ import numpy as _np
187
+ vecs = []
188
+ for t in texts:
189
+ h = abs(hash(t)) % (10 ** 8)
190
+ _np.random.seed(h)
191
+ vecs.append(_np.random.rand(256))
192
+ return _np.vstack(vecs)
193
+
194
+ def add_documents(self, texts, metas=None):
195
+ metas = metas or [{}] * len(texts)
196
+ self.texts.extend(texts)
197
+ self.meta.extend(metas)
198
+
199
+ # build or update FAISS index if possible
200
+ if self.embedding_model is not None and self.use_faiss:
201
+ vecs = self._embed(texts)
202
+ if self.faiss_index is None:
203
+ import numpy as _np
204
+ self.dimension = vecs.shape[1]
205
+ self.faiss_index = faiss.IndexFlatIP(self.dimension)
206
+ self.faiss_index.add(vecs)
207
+ else:
208
+ self.faiss_index.add(vecs)
209
+
210
+ self.save()
211
+
212
+ def query(self, q, topk=6, kind=None):
213
+ def matches_kind(idx):
214
+ if kind is None:
215
+ return True
216
+ meta = self.meta[idx] if idx < len(self.meta) else {}
217
+ return isinstance(meta, dict) and meta.get('kind') == kind
218
+
219
+ if self.embedding_model is not None and self.use_faiss and self.faiss_index is not None:
220
+ qv = self._embed([q])
221
+ search_count = len(self.texts) if kind is not None else topk
222
+ D, I = self.faiss_index.search(qv, max(search_count, topk))
223
+ results = []
224
+ for idx in I[0]:
225
+ if 0 <= idx < len(self.texts) and matches_kind(idx):
226
+ results.append(self.texts[idx])
227
+ if len(results) >= topk:
228
+ break
229
+ return results
230
+ # Offline lexical fallback. Whole-question substring matching misses
231
+ # queries such as "what is a deductible?".
232
+ stopwords = {'a', 'an', 'and', 'define', 'definition', 'for', 'is', 'meaning',
233
+ 'of', 'please', 'the', 'to', 'what', 'whats'}
234
+ query_terms = set(re.findall(r"[a-z0-9]+", str(q).lower())) - stopwords
235
+ scored = []
236
+ for idx, text in enumerate(self.texts):
237
+ if not matches_kind(idx):
238
+ continue
239
+ text_terms = set(re.findall(r"[a-z0-9]+", text.lower()))
240
+ score = len(query_terms & text_terms)
241
+ if score:
242
+ scored.append((score, text))
243
+ scored.sort(key=lambda item: item[0], reverse=True)
244
+ return [text for _, text in scored[:topk]]
245
+
246
+ index = RAGIndex(FAISS_DIR)
247
+
248
+ # Seed local Markdown/text/PDF knowledge files. When a .txt and .pdf share a
249
+ # stem, prefer the text copy to avoid indexing the same content twice.
250
+ def seed_from_kb():
251
+ selected = {}
252
+ suffix_priority = {'.txt': 0, '.md': 1, '.pdf': 2}
253
+ for f in KB_DIR.iterdir():
254
+ suffix = f.suffix.lower()
255
+ if suffix not in suffix_priority:
256
+ continue
257
+ current = selected.get(f.stem.lower())
258
+ if current is None or suffix_priority[suffix] < suffix_priority[current.suffix.lower()]:
259
+ selected[f.stem.lower()] = f
260
+
261
+ files = list(selected.values())
262
+ indexed_sources = set()
263
+ for meta in index.meta:
264
+ if isinstance(meta, dict) and meta.get('source'):
265
+ indexed_sources.add(str(meta.get('source')))
266
+
267
+ for f in files:
268
+ source = str(f)
269
+ if source in indexed_sources:
270
+ continue
271
+ try:
272
+ txt = extract_text_from_pdf(f) if f.suffix.lower() == '.pdf' else f.read_text(encoding='utf8')
273
+ chunks = chunk_text(txt)
274
+ metas = [{'source': source, 'chunk': i, 'kind': 'knowledge_base'} for i in range(len(chunks))]
275
+ index.add_documents(chunks, metas=metas)
276
+ except Exception:
277
+ pass
278
+
279
+ # Utilities
280
+
281
+ def extract_text_from_pdf(path):
282
+ pages = []
283
+ if PdfReader is not None:
284
+ try:
285
+ reader = PdfReader(path)
286
+ pages = [p.extract_text() or "" for p in reader.pages]
287
+ except Exception:
288
+ pages = []
289
+
290
+ text = "\n\n".join(pages).strip()
291
+ if text:
292
+ return text
293
+
294
+ # Scanned PDFs have no embedded text. Render each page and OCR it locally.
295
+ if fitz is not None and pytesseract is not None and Image is not None:
296
+ try:
297
+ ocr_pages = []
298
+ with fitz.open(path) as document:
299
+ for page in document:
300
+ pixmap = page.get_pixmap(matrix=fitz.Matrix(2, 2), alpha=False)
301
+ image = Image.open(io.BytesIO(pixmap.tobytes("png")))
302
+ ocr_pages.append(pytesseract.image_to_string(image))
303
+ return "\n\n".join(ocr_pages).strip()
304
+ except Exception:
305
+ return ""
306
+ return ""
307
+
308
+
309
+ def ocr_image(path):
310
+ if pytesseract is None or Image is None:
311
+ return ""
312
+ try:
313
+ # path may be a file path, a file-like object, or raw bytes
314
+ if hasattr(path, 'read'):
315
+ data = path.read()
316
+ img = Image.open(io.BytesIO(data))
317
+ else:
318
+ img = Image.open(path)
319
+ return pytesseract.image_to_string(img)
320
+ except Exception:
321
+ return ""
322
+
323
+
324
+ def _extract_document_text(path, fileobj=None):
325
+ """Extract text using file content first, then its extension."""
326
+ target = fileobj if fileobj is not None else path
327
+
328
+ # Gradio uploads can have misleading extensions. Pillow verifies whether
329
+ # the bytes are actually an image before PDF parsing is attempted.
330
+ if Image is not None:
331
+ try:
332
+ if hasattr(target, 'read'):
333
+ target.seek(0)
334
+ data = target.read()
335
+ target.seek(0)
336
+ with Image.open(io.BytesIO(data)) as image:
337
+ image.load()
338
+ return ocr_image(io.BytesIO(data)), 'image'
339
+ with Image.open(target) as image:
340
+ image.verify()
341
+ return ocr_image(target), 'image'
342
+ except Exception:
343
+ pass
344
+
345
+ suffix = Path(str(path)).suffix.lower() if path else ''
346
+ if suffix == '.pdf':
347
+ return extract_text_from_pdf(path), 'pdf'
348
+ if suffix in {'.txt', '.md'}:
349
+ try:
350
+ return Path(path).read_text(encoding='utf8'), 'text'
351
+ except Exception:
352
+ return '', 'text'
353
+ return '', 'unknown'
354
+
355
+
356
+ def _extraction_error(kind):
357
+ if kind == 'image' and (pytesseract is None or Image is None):
358
+ return "OCR is unavailable. Install pytesseract and Pillow, and install the Tesseract OCR application."
359
+ if kind == 'pdf' and PdfReader is None:
360
+ return "PDF support is unavailable. Install pypdf."
361
+ if kind == 'pdf' and (fitz is None or pytesseract is None):
362
+ return "No embedded PDF text was found. Install pymupdf and pytesseract to OCR scanned PDFs."
363
+ return "No readable text was found. Check that the file is a valid PDF, image, or UTF-8 text file."
364
+
365
+ # Gradio handlers
366
+
367
+ def chunk_text(text, chunk_size=900, overlap=100):
368
+ out = []
369
+ start = 0
370
+ L = len(text)
371
+ while start < L:
372
+ end = min(L, start + chunk_size)
373
+ out.append(text[start:end])
374
+ start = end - overlap if end - overlap > start else end
375
+ return out
376
+
377
+
378
+ seed_from_kb()
379
+ print(f"[insurechat] RAG index loaded {len(index.texts)} chunks from knowledge_base or previous saves")
380
+
381
+
382
+ def ingest_file(file):
383
+ # Resolve input: can be Gradio dict, file-like, or path string
384
+ path = None
385
+ fileobj = None
386
+ if isinstance(file, dict):
387
+ path = file.get('tmp_path') or file.get('name') or file.get('file')
388
+ fileobj = file.get('file')
389
+ else:
390
+ # file may be an UploadedFile object with .name and .file
391
+ path = getattr(file, 'name', None) or file
392
+ fileobj = getattr(file, 'file', None)
393
+
394
+ if not path and not fileobj:
395
+ return "Could not resolve file path"
396
+
397
+ text, kind = _extract_document_text(path, fileobj=fileobj)
398
+
399
+ if not text:
400
+ return _extraction_error(kind)
401
+
402
+ chunks = chunk_text(text)
403
+ return f"Ingested {path} (chunks={len(chunks)})"
404
+
405
+
406
+ def _document_context_state(file, parsed):
407
+ """Attach the current upload's text to session state without persisting it."""
408
+ if not parsed:
409
+ return {}
410
+
411
+ path = None
412
+ fileobj = None
413
+ if isinstance(file, dict):
414
+ path = file.get('tmp_path') or file.get('name') or file.get('file')
415
+ fileobj = file.get('file')
416
+ else:
417
+ path = getattr(file, 'name', None) or file
418
+ fileobj = getattr(file, 'file', None)
419
+
420
+ text, _ = _extract_document_text(path, fileobj=fileobj)
421
+ state = dict(parsed)
422
+ state['_document_chunks'] = chunk_text(text) if text else []
423
+ state['_source_name'] = Path(str(path)).name if path else 'uploaded document'
424
+ return state
425
+
426
+
427
+ def _search_kb_for_terms(query, limit=4):
428
+ if not isinstance(query, str) or not query.strip():
429
+ return []
430
+
431
+ normalized = query.lower()
432
+ wanted = set()
433
+ for canonical, terms in INSURANCE_TERM_ALIASES.items():
434
+ if any(term in normalized for term in terms):
435
+ wanted.add(canonical)
436
+
437
+ if not wanted and re.search(r"\b(insurance|bill|claim|deduct|copay|coverage|medical term|meaning|define)\b", normalized):
438
+ wanted.update(['deductible', 'copay', 'coinsurance', 'allowed amount', 'eob'])
439
+
440
+ exact_hits = []
441
+ related_hits = []
442
+ for f in list(KB_DIR.glob('*.md')) + list(KB_DIR.glob('*.txt')):
443
+ try:
444
+ text = f.read_text(encoding='utf8')
445
+ except Exception:
446
+ continue
447
+ lines = text.splitlines()
448
+ for line in lines:
449
+ line_lower = line.lower()
450
+ if any(term in line_lower for term in wanted):
451
+ cleaned = line.strip()
452
+ if not (cleaned.startswith('|') or cleaned.startswith('- ')):
453
+ continue
454
+ if cleaned.startswith('|---'):
455
+ continue
456
+ if cleaned:
457
+ hit = f"Source: {f}\n{cleaned}"
458
+ heading = cleaned.strip('|').split('|', 1)[0].strip().lower()
459
+ target = exact_hits if any(term in heading for term in wanted) else related_hits
460
+ if hit not in exact_hits and hit not in related_hits:
461
+ target.append(hit)
462
+
463
+ # Plain-text glossary entries use an uppercase heading followed by a
464
+ # definition and optional example/note paragraphs.
465
+ query_terms = set(re.findall(r"[a-z0-9]+", normalized)) - {
466
+ 'a', 'an', 'define', 'definition', 'is', 'meaning', 'of', 'please', 'the', 'what', 'whats'
467
+ }
468
+ for block in re.split(r"\n\s*\n", text):
469
+ block_lines = [line.strip() for line in block.splitlines() if line.strip()]
470
+ if len(block_lines) < 2:
471
+ continue
472
+ heading = block_lines[0]
473
+ heading_terms = set(re.findall(r"[a-z0-9]+", heading.lower()))
474
+ if query_terms and query_terms <= heading_terms and heading.upper() == heading:
475
+ hit = f"Source: {f}\n{block.strip()}"
476
+ if hit not in exact_hits and hit not in related_hits:
477
+ exact_hits.append(hit)
478
+ return (exact_hits + related_hits)[:limit]
479
+
480
+
481
+ def _correct_insurance_terms(query):
482
+ """Correct close insurance-term misspellings without rewriting normal text."""
483
+ if not isinstance(query, str):
484
+ return query, []
485
+
486
+ vocabulary = {name for name in INSURANCE_TERM_ALIASES if ' ' not in name and '-' not in name}
487
+ for aliases in INSURANCE_TERM_ALIASES.values():
488
+ vocabulary.update(alias for alias in aliases if ' ' not in alias and '-' not in alias)
489
+ corrections = []
490
+
491
+ def replace_token(match):
492
+ token = match.group(0)
493
+ lowered = token.lower()
494
+ if lowered in vocabulary or lowered in {'allowed'} or len(lowered) < 5:
495
+ return token
496
+ close = get_close_matches(lowered, vocabulary, n=1, cutoff=0.72)
497
+ if not close:
498
+ return token
499
+ matched = close[0]
500
+ canonical = next(
501
+ (name for name, aliases in INSURANCE_TERM_ALIASES.items()
502
+ if matched == name or matched in aliases),
503
+ matched,
504
+ )
505
+ corrections.append((token, canonical))
506
+ return canonical
507
+
508
+ return re.sub(r"[A-Za-z][A-Za-z-]*", replace_token, query), corrections
509
+
510
+
511
+ def _is_definition_question(question):
512
+ text = (question or '').strip().lower()
513
+ if re.search(r"\b(what is|what's|define|definition of|meaning of)\b", text):
514
+ return True
515
+ return len(text.split()) == 1 and len(text) < 30
516
+
517
+
518
+ def _definition_term(question):
519
+ text = re.sub(r"[^a-z0-9\s-]", "", (question or '').strip().lower())
520
+ text = re.sub(r"^(?:what is|whats|define|definition of|meaning of)\s+", "", text)
521
+ return text.strip()
522
+
523
+
524
+ def _definition_suggestions(question, limit=3):
525
+ requested = _definition_term(question)
526
+ if not requested:
527
+ return []
528
+ return get_close_matches(requested, list(INSURANCE_TERM_ALIASES), n=limit, cutoff=0.5)
529
+
530
+
531
+ def _answer_from_active_bill(question, parsed):
532
+ if not isinstance(parsed, dict) or not parsed or parsed.get('error'):
533
+ return None
534
+
535
+ q = (question or '').lower()
536
+
537
+ def has_any(phrases):
538
+ return any(re.search(rf"\b{re.escape(phrase)}\b", q) for phrase in phrases)
539
+
540
+ bill_field_words = (
541
+ 'bill', 'document', 'upload', 'image', 'owe', 'owed', 'pay', 'balance',
542
+ 'discount', 'adjustment', 'service date', 'date of service', 'allowed amount',
543
+ 'insurance paid', 'plan paid', 'patient responsibility', 'total charge', 'total billed',
544
+ )
545
+ if _is_definition_question(question) and not has_any(bill_field_words):
546
+ return None
547
+
548
+ bill_words = (
549
+ 'bill', 'document', 'upload', 'image', 'owe', 'owed', 'pay', 'balance',
550
+ 'charge', 'charged', 'total', 'discount', 'adjustment', 'service date',
551
+ 'date of service', 'analyze', 'analyse', 'summary', 'summarize', 'explain',
552
+ 'warning', 'allowed amount', 'insurance paid', 'plan paid', 'patient responsibility',
553
+ )
554
+ if not has_any(bill_words):
555
+ return None
556
+
557
+ owed = parsed.get('patient_owed') or parsed.get('estimated_patient_responsibility')
558
+ billed = parsed.get('billed_amount')
559
+ discount = parsed.get('adjustment_or_discount')
560
+ allowed = parsed.get('allowed_amount')
561
+ plan_paid = parsed.get('plan_paid')
562
+ service_date = parsed.get('service_date')
563
+
564
+ if has_any(('owe', 'owed', 'pay', 'balance', 'patient responsibility')):
565
+ if owed:
566
+ return f"The bill lists your patient responsibility as {_format_money(_money_to_float(owed)) or owed}."
567
+ return "The uploaded bill does not clearly show a patient-responsibility or balance amount."
568
+ if has_any(('discount', 'adjustment')):
569
+ return (f"The bill shows an adjustment or discount of {_format_money(_money_to_float(discount))}."
570
+ if discount else "No labeled adjustment or discount was found on the uploaded bill.")
571
+ if has_any(('service date', 'date of service')):
572
+ return f"The service date shown is {service_date}." if service_date else "No service date was found."
573
+ if 'allowed amount' in q:
574
+ return (f"The allowed amount shown is {_format_money(_money_to_float(allowed))}."
575
+ if allowed else "No allowed amount was found. Compare this provider bill with the insurer EOB.")
576
+ if has_any(('insurance paid', 'plan paid')):
577
+ return (f"The plan-paid amount shown is {_format_money(_money_to_float(plan_paid))}."
578
+ if plan_paid else "No plan-paid amount was found on this provider bill.")
579
+ if has_any(('charge', 'charged', 'total')) and billed:
580
+ return f"The total billed amount is {_format_money(_money_to_float(billed))}."
581
+
582
+ details = []
583
+ if billed:
584
+ details.append(f"Total billed: {_format_money(_money_to_float(billed))}")
585
+ if discount:
586
+ details.append(f"Adjustment/discount: {_format_money(_money_to_float(discount))}")
587
+ if owed:
588
+ details.append(f"Patient responsibility: {_format_money(_money_to_float(owed)) or owed}")
589
+ if service_date:
590
+ details.append(f"Service date: {service_date}")
591
+ warnings = parsed.get('warnings') or []
592
+ if not details and not warnings:
593
+ return None
594
+
595
+ answer = "Uploaded bill summary:\n" + "\n".join(f"- {item}" for item in details)
596
+ if warnings:
597
+ answer += "\n\nImportant:\n" + "\n".join(f"- {warning}" for warning in warnings)
598
+ return answer
599
+
600
+
601
+ def _clean_source_label(source):
602
+ if not source:
603
+ return ""
604
+ try:
605
+ name = Path(str(source)).name
606
+ except Exception:
607
+ name = str(source)
608
+ if name == "insurance_glossary.md":
609
+ return "insurance glossary"
610
+ if name == "medical_insurance_terms.md":
611
+ return "medical insurance terms"
612
+ return name
613
+
614
+
615
+ def _parse_term_row(text):
616
+ line = (text or "").strip()
617
+ if line.startswith("Source:"):
618
+ line = line.split("\n", 1)[1].strip() if "\n" in line else ""
619
+ if line.startswith("- ") and ":" in line:
620
+ term, definition = line[2:].split(":", 1)
621
+ return {
622
+ "term": term.strip(),
623
+ "definition": definition.strip(),
624
+ "look_for": "",
625
+ "example": "",
626
+ }
627
+ if line.startswith("|"):
628
+ cells = [cell.strip().strip('"') for cell in line.strip("|").split("|")]
629
+ if len(cells) >= 4 and cells[0].lower() != "term":
630
+ return {
631
+ "term": cells[0],
632
+ "definition": cells[1],
633
+ "look_for": cells[2],
634
+ "example": cells[3],
635
+ }
636
+ plain_lines = [part.strip() for part in line.splitlines() if part.strip()]
637
+ if len(plain_lines) >= 2 and plain_lines[0].upper() == plain_lines[0]:
638
+ example = ""
639
+ definition_parts = []
640
+ for part in plain_lines[1:]:
641
+ if part.lower().startswith('example:'):
642
+ example = part.split(':', 1)[1].strip()
643
+ elif not part.lower().startswith('note:'):
644
+ definition_parts.append(part)
645
+ return {
646
+ "term": plain_lines[0],
647
+ "definition": " ".join(definition_parts),
648
+ "look_for": "",
649
+ "example": example,
650
+ }
651
+ return None
652
+
653
+
654
+ def _simple_context_answer(question, chunks):
655
+ source_labels = []
656
+ for chunk in chunks:
657
+ match = re.match(r"Source:\s*(.+)\n", str(chunk))
658
+ if match:
659
+ label = _clean_source_label(match.group(1))
660
+ if label and label not in source_labels:
661
+ source_labels.append(label)
662
+
663
+ rows = []
664
+ for chunk in chunks:
665
+ row = _parse_term_row(chunk)
666
+ if row and row not in rows:
667
+ rows.append(row)
668
+
669
+ if rows:
670
+ primary = rows[0]
671
+ answer = f"{primary['term']}: {primary['definition']}"
672
+ if primary.get('example'):
673
+ answer += f"\n\nExample: {primary['example']}"
674
+ if primary.get('look_for'):
675
+ look_for = primary['look_for'].replace('"', '').rstrip('.')
676
+ answer += f"\n\nOn a bill or EOB, look for: {look_for}."
677
+ else:
678
+ cleaned = []
679
+ for chunk in chunks[:3]:
680
+ text = re.sub(r"Source:\s*.*\n", "", str(chunk)).strip()
681
+ if text:
682
+ cleaned.append(text)
683
+ answer = "\n\n".join(cleaned) or "I do not have enough local context yet. Upload a bill/EOB/claim or ask about a common insurance term."
684
+
685
+ if source_labels:
686
+ answer += f"\n\nSource: {source_labels[0]}"
687
+ return answer
688
+
689
+
690
+ def _clean_model_answer(answer):
691
+ """Remove common local-model boilerplate and repeated closing text."""
692
+ text = (answer or '').strip()
693
+ text = re.sub(r"^Answer:\s*", "", text, flags=re.I)
694
+ stop_patterns = (
695
+ r"\n\s*Please provide (?:your )?feedback.*",
696
+ r"\n\s*Best regards,.*",
697
+ r"\n\s*Note:.*",
698
+ )
699
+ for pattern in stop_patterns:
700
+ text = re.sub(pattern, "", text, flags=re.I | re.S).strip()
701
+ return text
702
+
703
+
704
+ def _normalize_romanized_hindi(question):
705
+ """Normalize common Romanized Hindi insurance questions before translation."""
706
+ text = (question or '').strip().lower()
707
+ term_aliases = {
708
+ 'cope': 'copay', 'copay': 'copay', 'deductible': 'deductible',
709
+ 'coinsurance': 'coinsurance', 'premium': 'premium',
710
+ 'insurance': 'health insurance', 'insurence': 'health insurance',
711
+ }
712
+ match = re.fullmatch(r"(.+?)\s+(?:kya|kyaa)\s+(?:hai|h)\??", text)
713
+ if match:
714
+ term = term_aliases.get(match.group(1).strip(), match.group(1).strip())
715
+ return f"what is {term}?"
716
+ return question
717
+
718
+
719
+ def _normalize_input_question(question, input_lang):
720
+ if input_lang == 'hi-latn':
721
+ return _normalize_romanized_hindi(question)
722
+ if input_lang == 'hi':
723
+ normalized = (question or '').strip().lower().rstrip('?!। ')
724
+ hindi_definitions = {
725
+ 'कोपे क्या है': 'what is copay?',
726
+ 'कॉपी क्या है': 'what is copay?',
727
+ 'स्वास्थ्य बीमा क्या है': 'what is health insurance?',
728
+ 'बीमा क्या है': 'what is health insurance?',
729
+ }
730
+ return hindi_definitions.get(normalized, question)
731
+ return question
732
+
733
+
734
+ def ask_question(q, input_lang='en', active_document=None):
735
+ # Retrieve
736
+ # short-circuit greetings to avoid dumping documents for 'hi' etc.
737
+ greetings = {"hi", "hello", "hey", "good morning", "good afternoon", "good evening"}
738
+ if isinstance(q, str) and q.strip().lower() in greetings:
739
+ return "Hi — I can help with your bill or insurance questions. Ask me about a term (e.g. 'what is a copay') or upload a bill."
740
+ source_question = _normalize_input_question(q, input_lang)
741
+ english_q = source_question
742
+ try:
743
+ if input_lang and input_lang.lower() != 'en' and source_question == q:
744
+ english_q = translate_text(source_question, target_lang='en', source_lang=input_lang)
745
+ except Exception:
746
+ english_q = source_question
747
+
748
+ corrected_q, corrections = _correct_insurance_terms(english_q)
749
+
750
+ def finish(answer):
751
+ if corrections:
752
+ original, corrected = corrections[0]
753
+ return f"I interpreted '{original}' as '{corrected}'.\n\n{answer}"
754
+ return answer
755
+
756
+ bill_answer = _answer_from_active_bill(corrected_q, active_document)
757
+ if bill_answer:
758
+ return finish(bill_answer)
759
+
760
+ # Try the local glossary after normalizing the question into English.
761
+ preliminary_kb_hits = _search_kb_for_terms(corrected_q)
762
+
763
+ q_for_search = corrected_q
764
+
765
+ active_chunks = active_document.get('_document_chunks', []) if isinstance(active_document, dict) else []
766
+ chunks = list(active_chunks[:6]) if active_chunks else index.query(
767
+ q_for_search, topk=6, kind='knowledge_base'
768
+ )
769
+ # If no retrieved chunks and this looks like a definition request, try KB files directly
770
+ is_definition = _is_definition_question(corrected_q)
771
+
772
+ kb_hits = [] if active_chunks else (preliminary_kb_hits or _search_kb_for_terms(q_for_search))
773
+ if kb_hits:
774
+ chunks = kb_hits + [chunk for chunk in chunks if chunk not in kb_hits]
775
+ elif is_definition and not active_chunks:
776
+ # A similarity hit is not enough evidence that the requested term has
777
+ # a local definition.
778
+ chunks = []
779
+ # Build a compact context: include short excerpts and source metadata (if available)
780
+ context_parts = []
781
+ for chunk in chunks:
782
+ if active_chunks:
783
+ src = active_document.get('_source_name', 'uploaded document')
784
+ else:
785
+ try:
786
+ idx = index.texts.index(chunk)
787
+ meta = index.meta[idx] if idx < len(index.meta) else {}
788
+ src = meta.get('source', '') if isinstance(meta, dict) else ''
789
+ except Exception:
790
+ src = ''
791
+ excerpt = (chunk or '').strip()[:500]
792
+ if src:
793
+ context_parts.append(f"Source: {_clean_source_label(src)}\n{excerpt}")
794
+ else:
795
+ context_parts.append(excerpt)
796
+
797
+ context = "\n\n---\n\n".join(context_parts)
798
+
799
+ # Quick numeric Q&A using SBC parsing utilities when an uploaded plan/SBC is active
800
+ if active_chunks:
801
+ try:
802
+ full_text = "\n\n".join(active_chunks)
803
+ plan = sbc_utils.parse_plan_terms(full_text)
804
+ # If user asks for a deductible
805
+ if re.search(r"\bwhat is the overall deductible\b|\boverall deductible\b|\bdeductible\b", corrected_q, re.I):
806
+ d = plan.get('overall_deductible_network_individual')
807
+ if d is not None:
808
+ return finish(f"The plan's in-network individual deductible appears to be {_format_money(d)}.")
809
+ # If user asks a dollar-based 'how much would I pay' question
810
+ m = re.search(r"\$(\s?[0-9,]+)", corrected_q)
811
+ if m:
812
+ amt = float(re.sub(r"[^0-9.]", "", m.group(0)))
813
+ service_type = 'hospital' if re.search(r"hospital|facility|inpatient|delivery", corrected_q, re.I) else 'service'
814
+ est = sbc_utils.estimate_member_payment(amt, service_type, 'network', plan)
815
+ return finish(est)
816
+ except Exception:
817
+ pass
818
+
819
+ if is_definition and not active_chunks:
820
+ if kb_hits:
821
+ answer = _simple_context_answer(corrected_q, kb_hits)
822
+ return finish(f"{answer}\n\nLearn more: {ONLINE_GLOSSARY_URL}")
823
+
824
+ suggestions = _definition_suggestions(corrected_q)
825
+ suggestion_text = ""
826
+ if suggestions:
827
+ suggestion_text = " Did you mean " + ", ".join(f"'{term}'" for term in suggestions) + "?"
828
+ return finish(
829
+ f"I could not find a local definition for '{_definition_term(corrected_q)}'."
830
+ f"{suggestion_text}\n\nTrusted glossary: {ONLINE_GLOSSARY_URL}"
831
+ )
832
+
833
+ # General questions without an active upload stay on fast local RAG.
834
+ # Llama is reserved for reasoning over the current PDF, image, or text file.
835
+ if not active_chunks:
836
+ return finish(_simple_context_answer(corrected_q, chunks))
837
+
838
+ prompt_suffix = (
839
+ "Answer in no more than three short paragraphs using plain language. "
840
+ "Only show calculations when the user asks about an amount or calculation. Include Source when available. "
841
+ "Do not add an 'Answer' heading, notes about editing the response, feedback requests, signatures, "
842
+ "contact information, or repeated closing text."
843
+ )
844
+ prompt = (
845
+ f"{SYSTEM_PROMPT}\n\nDOCUMENT CONTEXT:\n{context}\n\n"
846
+ f"Question: {corrected_q}\n{prompt_suffix}"
847
+ )
848
+
849
+ if Llama is None:
850
+ return finish(_simple_context_answer(corrected_q, chunks))
851
+
852
+ llm_path = _select_model_for_role("reason")
853
+ if not llm_path:
854
+ return finish(_simple_context_answer(corrected_q, chunks))
855
+
856
+ # Keep prompts compact by limiting context length.
857
+ with _use_llm(llm_path) as llm:
858
+ resp = llm(
859
+ prompt=prompt,
860
+ max_tokens=256,
861
+ temperature=0.1,
862
+ stop=["\nNote:", "\nPlease provide", "\nBest regards,"],
863
+ )
864
+ text = resp.get('choices', [{}])[0].get('text') or resp.get('text') or ''
865
+ # If multilingual output requested and translator model available, translate back to requested language
866
+ # Always return English text from this function; translation is handled by the caller.
867
+ return _clean_model_answer(text)
868
+
869
+
870
+ def _find_gguf_by_keyword(keyword):
871
+ ggufs = list(MODELS_DIR.glob('*.gguf'))
872
+ for p in ggufs:
873
+ if keyword.lower() in p.name.lower():
874
+ return str(p)
875
+ return None
876
+
877
+
878
+ def _select_model_for_role(role):
879
+ ggufs = list(MODELS_DIR.glob('*.gguf'))
880
+ if not ggufs:
881
+ return None
882
+
883
+ keywords = MODEL_ROLE_KEYWORDS.get(role, ())
884
+ for keyword in keywords:
885
+ found = _find_gguf_by_keyword(keyword)
886
+ if found:
887
+ return found
888
+
889
+ # Never substitute a translation model for reasoning (or vice versa).
890
+ return None
891
+
892
+
893
+ def _unload_active_llm():
894
+ """Release the active GGUF before another role loads a different model."""
895
+ global _ACTIVE_LLM, _ACTIVE_LLM_PATH
896
+ if _ACTIVE_LLM is not None:
897
+ close = getattr(_ACTIVE_LLM, 'close', None)
898
+ if callable(close):
899
+ close()
900
+ _ACTIVE_LLM = None
901
+ _ACTIVE_LLM_PATH = None
902
+ gc.collect()
903
+
904
+
905
+ @contextmanager
906
+ def _use_llm(model_path):
907
+ """Keep one local GGUF loaded and prevent it being closed during inference."""
908
+ global _ACTIVE_LLM, _ACTIVE_LLM_PATH
909
+ if Llama is None or not model_path:
910
+ yield None
911
+ return
912
+
913
+ with _LLM_LOCK:
914
+ if _ACTIVE_LLM_PATH != model_path:
915
+ _unload_active_llm()
916
+ _ACTIVE_LLM = Llama(
917
+ model_path=model_path,
918
+ n_ctx=4096,
919
+ n_threads=max(1, os.cpu_count() // 2),
920
+ n_gpu_layers=-1,
921
+ verbose=False,
922
+ )
923
+ _ACTIVE_LLM_PATH = model_path
924
+ yield _ACTIVE_LLM
925
+
926
+
927
+ def translate_text(text, target_lang='en', source_lang='English'):
928
+ """Translate with the local Aya GGUF only; this function never uses the internet."""
929
+ target_code = (target_lang or 'en').lower()
930
+ if target_code == (source_lang or '').lower():
931
+ return text
932
+
933
+ if Llama is not None:
934
+ aya_path = _select_model_for_role("translate")
935
+ if aya_path:
936
+ source_name = LANGUAGE_NAMES.get((source_lang or '').lower(), source_lang or 'the source language')
937
+ target_name = LANGUAGE_NAMES.get(target_code, target_lang)
938
+ with _use_llm(aya_path) as llm:
939
+ resp = llm.create_chat_completion(
940
+ messages=[
941
+ {
942
+ 'role': 'system',
943
+ 'content': (
944
+ f"Translate from {source_name} to {target_name}. Return only the translation, "
945
+ "without notes, labels, or the original text."
946
+ ),
947
+ },
948
+ {'role': 'user', 'content': text},
949
+ ],
950
+ max_tokens=min(384, max(96, len(text) * 2)),
951
+ temperature=0.1,
952
+ )
953
+ translated = resp.get('choices', [{}])[0].get('message', {}).get('content', '')
954
+ return translated.strip() or text
955
+
956
+ return text
957
+
958
+
959
+ def _money_to_float(value):
960
+ if value is None:
961
+ return None
962
+ try:
963
+ return float(str(value).replace('$', '').replace(',', '').strip())
964
+ except Exception:
965
+ return None
966
+
967
+
968
+ def _format_money(value):
969
+ if value is None:
970
+ return None
971
+ return f"${value:,.2f}"
972
+
973
+
974
+ def _extract_labeled_amount(text, labels):
975
+ for label in labels:
976
+ # Keep the match on one OCR line so an address or account number on a
977
+ # later line cannot become a medical charge.
978
+ pattern = rf"{label}[ \t]*(?:amount|charge|paid|due|owed|responsibility|:)?[ \t]*\$?[ \t]*([0-9][0-9,]*(?:\.[0-9]{{2}})?)"
979
+ match = re.search(pattern, text, re.I)
980
+ if match:
981
+ return match.group(1).replace(',', '')
982
+ return None
983
+
984
+
985
+ def estimate_patient_responsibility(fields):
986
+ billed = _money_to_float(fields.get('billed_amount'))
987
+ allowed = _money_to_float(fields.get('allowed_amount'))
988
+ plan_paid = _money_to_float(fields.get('plan_paid'))
989
+ deductible = _money_to_float(fields.get('deductible'))
990
+ copay = _money_to_float(fields.get('copay'))
991
+ coinsurance = _money_to_float(fields.get('coinsurance'))
992
+ noncovered = _money_to_float(fields.get('noncovered_amount'))
993
+ explicit_owed = _money_to_float(fields.get('patient_owed'))
994
+
995
+ steps = []
996
+ if explicit_owed is not None:
997
+ steps.append(f"Document lists patient responsibility as {_format_money(explicit_owed)}.")
998
+ return {
999
+ 'estimated_patient_responsibility': _format_money(explicit_owed),
1000
+ 'calculation_steps': steps,
1001
+ 'confidence': 'high',
1002
+ }
1003
+
1004
+ total = 0.0
1005
+ if deductible:
1006
+ total += deductible
1007
+ steps.append(f"Deductible applied: {_format_money(deductible)}.")
1008
+ if copay:
1009
+ total += copay
1010
+ steps.append(f"Copay: {_format_money(copay)}.")
1011
+ if coinsurance:
1012
+ total += coinsurance
1013
+ steps.append(f"Coinsurance: {_format_money(coinsurance)}.")
1014
+ if noncovered:
1015
+ total += noncovered
1016
+ steps.append(f"Non-covered amount: {_format_money(noncovered)}.")
1017
+
1018
+ if total:
1019
+ return {
1020
+ 'estimated_patient_responsibility': _format_money(total),
1021
+ 'calculation_steps': steps,
1022
+ 'confidence': 'medium',
1023
+ }
1024
+
1025
+ if allowed is not None and plan_paid is not None:
1026
+ estimate = max(0.0, allowed - plan_paid)
1027
+ steps.append(f"Allowed amount minus plan paid: {_format_money(allowed)} - {_format_money(plan_paid)}.")
1028
+ return {
1029
+ 'estimated_patient_responsibility': _format_money(estimate),
1030
+ 'calculation_steps': steps,
1031
+ 'confidence': 'medium',
1032
+ }
1033
+
1034
+ if billed is not None and plan_paid is not None:
1035
+ estimate = max(0.0, billed - plan_paid)
1036
+ steps.append(f"Billed amount minus plan paid: {_format_money(billed)} - {_format_money(plan_paid)}.")
1037
+ steps.append("This is less reliable because patient responsibility is usually based on allowed amount, not billed charge.")
1038
+ return {
1039
+ 'estimated_patient_responsibility': _format_money(estimate),
1040
+ 'calculation_steps': steps,
1041
+ 'confidence': 'low',
1042
+ }
1043
+
1044
+ return {
1045
+ 'estimated_patient_responsibility': None,
1046
+ 'calculation_steps': ['Not enough labeled amounts were found to estimate patient responsibility.'],
1047
+ 'confidence': 'low',
1048
+ }
1049
+
1050
+
1051
+ def extract_structured(file):
1052
+ # Resolve path and extract text
1053
+ path = None
1054
+ if isinstance(file, dict):
1055
+ path = file.get('tmp_path') or file.get('name') or file.get('file')
1056
+ else:
1057
+ path = getattr(file, 'name', None) or file
1058
+ if not path:
1059
+ return json.dumps({'error': 'no file path'})
1060
+
1061
+ text, kind = _extract_document_text(path)
1062
+
1063
+ if not text:
1064
+ return json.dumps({'error': _extraction_error(kind)}, ensure_ascii=False)
1065
+
1066
+ schema = {
1067
+ 'document_type': None,
1068
+ 'member_id': None,
1069
+ 'patient_name': None,
1070
+ 'provider_name': None,
1071
+ 'service_date': None,
1072
+ 'billed_amount': None,
1073
+ 'allowed_amount': None,
1074
+ 'plan_paid': None,
1075
+ 'adjustment_or_discount': None,
1076
+ 'deductible': None,
1077
+ 'copay': None,
1078
+ 'coinsurance': None,
1079
+ 'noncovered_amount': None,
1080
+ 'patient_owed': None,
1081
+ 'CPT_codes': [],
1082
+ 'ICD10_codes': [],
1083
+ 'warnings': [],
1084
+ }
1085
+
1086
+ extract_model_path = _select_model_for_role("extract") or _select_model_for_role("reason")
1087
+ if Llama is not None and extract_model_path:
1088
+ prompt = (
1089
+ "Extract the following fields from the document and return valid JSON only. "
1090
+ "Fields: document_type, member_id, patient_name, provider_name, service_date, billed_amount, "
1091
+ "allowed_amount, plan_paid, adjustment_or_discount, deductible, copay, coinsurance, "
1092
+ "noncovered_amount, patient_owed, CPT_codes (list), ICD10_codes (list), warnings (list). "
1093
+ "Use null for missing fields. Preserve dollar amounts as strings.\n\n"
1094
+ f"Document text:\n{text[:10000]}\n\nReturn only JSON."
1095
+ )
1096
+ try:
1097
+ with _use_llm(extract_model_path) as llm:
1098
+ resp = llm(prompt=prompt, max_tokens=512)
1099
+ out = resp.get('choices',[{}])[0].get('text') or resp.get('text') or ''
1100
+ parsed = json.loads(out)
1101
+ if isinstance(parsed, dict):
1102
+ calc = estimate_patient_responsibility(parsed)
1103
+ parsed.update(calc)
1104
+ return json.dumps(parsed, ensure_ascii=False, indent=2)
1105
+ except Exception:
1106
+ # Fall through to deterministic extraction if inference or JSON parsing fails.
1107
+ pass
1108
+
1109
+ # Regex fallback: best-effort extraction
1110
+ res = dict(schema)
1111
+ lower_text = text.lower()
1112
+ if 'explanation of benefits' in lower_text or 'this is not a bill' in lower_text:
1113
+ res['document_type'] = 'explanation_of_benefits'
1114
+ elif 'claim' in lower_text:
1115
+ res['document_type'] = 'claim'
1116
+ elif 'amount due' in lower_text or 'balance due' in lower_text or 'hospital statement' in lower_text:
1117
+ res['document_type'] = 'provider_bill'
1118
+
1119
+ res['billed_amount'] = _extract_labeled_amount(text, [
1120
+ r'amount billed', r'billed', r'provider charge', r'total charges?', r'charge'
1121
+ ])
1122
+ res['allowed_amount'] = _extract_labeled_amount(text, [
1123
+ r'allowed amount', r'allowed', r'eligible expense', r'negotiated rate', r'allowable'
1124
+ ])
1125
+ res['plan_paid'] = _extract_labeled_amount(text, [
1126
+ r'plan paid', r'insurance paid', r'paid by plan', r'benefit paid', r'paid'
1127
+ ])
1128
+ res['adjustment_or_discount'] = _extract_labeled_amount(text, [
1129
+ r'adjustment', r'discount', r'network discount', r'provider discount'
1130
+ ])
1131
+ res['deductible'] = _extract_labeled_amount(text, [r'deductible'])
1132
+ res['copay'] = _extract_labeled_amount(text, [r'copay', r'co-pay', r'copayment'])
1133
+ res['coinsurance'] = _extract_labeled_amount(text, [r'coinsurance', r'co-insurance'])
1134
+ res['noncovered_amount'] = _extract_labeled_amount(text, [
1135
+ r'non-covered', r'not covered', r'noncovered'
1136
+ ])
1137
+ res['patient_owed'] = _extract_labeled_amount(text, [
1138
+ r'patient responsibility', r'member responsibility', r'you owe', r'amount due', r'balance due',
1139
+ r'patient owes?', r'total due', r'balanc(?:e)?'
1140
+ ])
1141
+
1142
+ # Require a CPT/procedure label so ZIP codes and account fragments are not
1143
+ # misreported as medical procedure codes.
1144
+ cpts = re.findall(r"(?:CPT|procedure(?: code)?)\s*[:#-]?\s*(\d{5})\b", text, re.I)
1145
+ res['CPT_codes'] = list(dict.fromkeys(cpts))
1146
+ icds = re.findall(r"\b([A-Z][0-9][0-9AB](?:\.[A-Z0-9]{1,4})?)\b", text)
1147
+ res['ICD10_codes'] = list(dict.fromkeys(icds))
1148
+
1149
+ # member id heuristic
1150
+ mem = re.search(r"Member(?: ID| #|:)?\s*([A-Z0-9\-]{5,})", text, re.I)
1151
+ if mem:
1152
+ res['member_id'] = mem.group(1)
1153
+
1154
+ # dates
1155
+ dt = re.search(r"(\d{1,2}/\d{1,2}/\d{2,4})", text)
1156
+ if dt:
1157
+ res['service_date'] = dt.group(1)
1158
+
1159
+ res.update(estimate_patient_responsibility(res))
1160
+ if not res.get('allowed_amount'):
1161
+ res['warnings'].append('Allowed amount was not found; patient responsibility may be harder to verify.')
1162
+ if res.get('document_type') == 'provider_bill':
1163
+ res['warnings'].append('Compare this provider bill with the insurer EOB before assuming the amount is final.')
1164
+
1165
+ return json.dumps(res, ensure_ascii=False, indent=2)
1166
+
1167
+
1168
+ def _parsed_document_state(structured_json):
1169
+ try:
1170
+ parsed = json.loads(structured_json)
1171
+ return parsed if isinstance(parsed, dict) and not parsed.get('error') else {}
1172
+ except Exception:
1173
+ return {}
1174
+
1175
+
1176
+ def ingest_and_activate(file):
1177
+ status_message = ingest_file(file)
1178
+ structured_json = extract_structured(file)
1179
+ parsed = _document_context_state(file, _parsed_document_state(structured_json))
1180
+ if parsed:
1181
+ status_message += " The parsed bill is now active in chat."
1182
+ return status_message, parsed, structured_json
1183
+
1184
+
1185
+ def extract_and_activate(file):
1186
+ structured_json = extract_structured(file)
1187
+ parsed = _document_context_state(file, _parsed_document_state(structured_json))
1188
+ status_message = "Parsed bill is now active in chat." if parsed else "Bill extraction failed."
1189
+ return structured_json, parsed, status_message
1190
+
1191
+ with gr.Blocks() as demo:
1192
+ active_document = gr.State({})
1193
+ gr.Markdown("# InsureChat - local medical insurance helper")
1194
+ with gr.Row():
1195
+ with gr.Column(scale=2):
1196
+ chat = gr.Chatbot()
1197
+ input_lang_dropdown = gr.Dropdown(choices=[
1198
+ ("English","en"),("Spanish","es"),("French","fr"),("Hindi","hi"),
1199
+ ("Hindi (Romanized)","hi-latn"),("Chinese","zh"),("Arabic","ar"),
1200
+ ("Portuguese","pt"),("German","de"),("Japanese","ja"),("Korean","ko"),
1201
+ ("Russian","ru"),("Vietnamese","vi")
1202
+ ], value='en', label='Question language')
1203
+ answer_lang_dropdown = gr.Dropdown(choices=[
1204
+ ("English","en"),("Spanish","es"),("French","fr"),("Hindi","hi"),
1205
+ ("Chinese","zh"),("Arabic","ar"),("Portuguese","pt"),("German","de"),
1206
+ ("Japanese","ja"),("Korean","ko"),("Russian","ru"),("Vietnamese","vi")
1207
+ ], value='en', label='Answer language')
1208
+ inp = gr.Textbox(placeholder='Ask about copay, deductible, an EOB, a claim, or an uploaded bill')
1209
+ submit = gr.Button('Ask')
1210
+ with gr.Column(scale=1):
1211
+ file_input = gr.File(label='Upload PDF/JPG/PNG/TXT')
1212
+ ingest_btn = gr.Button('Ingest file')
1213
+ status = gr.Textbox(label='Status')
1214
+
1215
+ extract_btn = gr.Button('Extract Bill / Claim (JSON)')
1216
+ extract_output = gr.Textbox(label='Structured insurance fields and estimate', lines=14)
1217
+
1218
+ ingest_btn.click(
1219
+ ingest_and_activate,
1220
+ inputs=file_input,
1221
+ outputs=[status, active_document, extract_output],
1222
+ )
1223
+ extract_btn.click(
1224
+ extract_and_activate,
1225
+ inputs=file_input,
1226
+ outputs=[extract_output, active_document, status],
1227
+ )
1228
+
1229
+ # Chat handler: accepts separate question and answer languages.
1230
+ def chat_submit(question, input_lang, answer_lang, active_bill=None, chat_history=None):
1231
+ if chat_history is None:
1232
+ chat_history = []
1233
+ # Normalize chat_history into list of {'role':..., 'content':...}
1234
+ normalized = []
1235
+ for item in chat_history:
1236
+ if isinstance(item, (list, tuple)) and len(item) == 2:
1237
+ role = str(item[0]).lower()
1238
+ # map display roles to 'user'/'assistant'
1239
+ if 'user' in role:
1240
+ r = 'user'
1241
+ elif 'assistant' in role or 'bot' in role:
1242
+ r = 'assistant'
1243
+ else:
1244
+ r = 'user'
1245
+ normalized.append({'role': r, 'content': str(item[1])})
1246
+ elif isinstance(item, dict):
1247
+ if 'role' in item and 'content' in item:
1248
+ normalized.append({'role': item['role'], 'content': item['content']})
1249
+ else:
1250
+ # try common keys
1251
+ if 'user' in item and 'assistant' in item:
1252
+ normalized.append({'role': 'user', 'content': str(item.get('user'))})
1253
+ else:
1254
+ normalized.append({'role': 'user', 'content': str(item)})
1255
+ else:
1256
+ normalized.append({'role': 'user', 'content': str(item)})
1257
+
1258
+ # Add user message
1259
+ normalized.append({'role': 'user', 'content': question})
1260
+
1261
+ # Produce an English grounded answer, then translate it exactly once.
1262
+ ans = ask_question(question, input_lang=input_lang, active_document=active_bill)
1263
+
1264
+ # Return only the selected language instead of English plus a translation.
1265
+ try:
1266
+ if answer_lang and answer_lang.lower() != 'en':
1267
+ translated = translate_text(ans, target_lang=answer_lang, source_lang='en')
1268
+ if translated and translated.strip() and translated.strip() != ans.strip():
1269
+ ans = translated.strip()
1270
+ else:
1271
+ ans = (
1272
+ f"Translation to {LANGUAGE_NAMES.get(answer_lang, answer_lang)} is unavailable because the local "
1273
+ "Aya translation model is not installed.\n\n" + ans
1274
+ )
1275
+ except Exception:
1276
+ ans = f"Translation failed; showing the English answer instead.\n\n{ans}"
1277
+
1278
+ normalized.append({'role': 'assistant', 'content': ans})
1279
+ return normalized
1280
+
1281
+ submit.click(
1282
+ chat_submit,
1283
+ inputs=[inp, input_lang_dropdown, answer_lang_dropdown, active_document, chat],
1284
+ outputs=chat,
1285
+ )
1286
+
1287
+ if __name__ == '__main__':
1288
+ demo.launch()
insurechat/download_models.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simple interactive downloader for GGUF models using huggingface_hub
3
+ This script is intentionally minimal: it downloads selected GGUF files into models/.
4
+ Run once during setup. Requires internet for downloads.
5
+ """
6
+ import argparse
7
+ from huggingface_hub import hf_hub_download
8
+ from pathlib import Path
9
+
10
+ MODELS = {
11
+ 'llama3-8b': {'repo':'bartowski/Meta-Llama-3.1-8B-Instruct-GGUF','filename':'Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf'},
12
+ 'nemotron-4b': {'repo':'bartowski/Nemotron-Mini-4B-Instruct-GGUF','filename':'Nemotron-Mini-4B-Instruct-Q4_K_M.gguf'},
13
+ 'aya-8b': {'repo':'bartowski/aya-expanse-8b-GGUF','filename':'aya-expanse-8b-Q4_K_M.gguf'},
14
+ 'moondream2': {'repo':'vikhyatk/moondream2','filename':'moondream2-text-model-f16.gguf'},
15
+ 'meta-llama-8b-quant': {'repo':'bartowski/Meta-Llama-3.1-8B-Instruct-GGUF','filename':'Meta-Llama-3.1-8B-Instruct-Q4_K_M.gguf'},
16
+ }
17
+
18
+ OUT = Path(__file__).parent / 'models'
19
+ OUT.mkdir(exist_ok=True)
20
+
21
+ parser = argparse.ArgumentParser()
22
+ parser.add_argument('--model', choices=list(MODELS.keys()), help='Model to download')
23
+ args = parser.parse_args()
24
+
25
+ if args.model:
26
+ m = MODELS[args.model]
27
+ print('Downloading', args.model)
28
+ p = hf_hub_download(repo_id=m['repo'], filename=m['filename'], local_dir=OUT)
29
+ dest = Path(p)
30
+ print('Saved to', dest)
31
+ else:
32
+ print('Available models:')
33
+ for k in MODELS:
34
+ print('-', k)
35
+ print('\nRun with --model <name> to download')
insurechat/knowledge_base/insurance_glossary.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Insurance glossary (minimal seed)
2
+
3
+ - Deductible: The amount you pay out-of-pocket before insurance starts paying.
4
+ - Copayment (copay): A fixed amount you pay for a covered service (e.g., $20).
5
+ - Coinsurance: A percentage of costs you pay after meeting your deductible.
6
+ - Out-of-pocket maximum (OOP): The most you'll pay in a plan year; after hitting it, insurance pays 100% of covered services.
7
+ - Explanation of Benefits (EOB): A statement from the insurer explaining what was billed, what they allowed, and what you owe.
8
+ - In-network vs Out-of-network: In-network providers have negotiated rates; out-of-network often costs more.
9
+
10
+ # UnitedHealthcare-specific notes
11
+ - For account-specific questions, call the number on the back of your insurance card.
12
+ - Coverage details and dollar amounts must be sourced from documents (EOBs, plan summaries).
insurechat/knowledge_base/medical_insurance_terms.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Medical insurance terms for newcomers
2
+
3
+ This file is a local knowledge base for InsureChat. It explains common U.S. medical insurance terms in plain language for people who may be unfamiliar with the U.S. health care system. Sources used: HealthCare.gov glossary pages for deductible, copayment, coinsurance, out-of-pocket maximum, and allowed amount.
4
+
5
+ ## Quick mental model
6
+
7
+ In the U.S., medical care often has three separate prices:
8
+
9
+ 1. The provider's billed charge: what the hospital, doctor, lab, or pharmacy asks for.
10
+ 2. The allowed amount: the price the insurance plan recognizes for a covered service.
11
+ 3. The patient responsibility: what the patient may owe after insurance rules are applied.
12
+
13
+ Insurance does not always pay the full bill. It usually follows plan rules: deductible first, then copay or coinsurance, up to an out-of-pocket maximum for covered in-network care.
14
+
15
+ ## Term table
16
+
17
+ | Term | Plain-language meaning | What to look for on bills, EOBs, or claims | Example |
18
+ |---|---|---|---|
19
+ | Health insurance | A plan or contract that helps pay for covered medical care in exchange for a premium. The member may still pay deductibles, copays, coinsurance, or non-covered costs. | Plan name, coverage dates, network, premium, deductible, copay, and coinsurance. | A health plan may pay part of an in-network doctor visit after the member pays the required cost sharing. |
20
+ | Premium | The regular amount paid to keep insurance active, usually monthly. | Usually not on a medical bill; appears in plan or account billing. | You pay a monthly premium even if you do not visit a doctor. |
21
+ | Deductible | The amount you pay for covered services before the plan starts paying many costs. | "Deductible", "applied to deductible", "deductible remaining". | If the deductible is $2,000, you may pay covered costs until $2,000 is reached. |
22
+ | Copayment / copay | A fixed dollar amount for a covered service. | "Copay", "office visit copay", "ER copay", "Rx copay". | A primary-care visit might have a $25 copay. |
23
+ | Coinsurance | A percentage of the allowed amount that you pay, usually after deductible. | "Coinsurance", "member coinsurance", "patient coinsurance". | If allowed amount is $100 and coinsurance is 20%, patient pays $20. |
24
+ | Out-of-pocket maximum | The yearly cap on what you pay for covered in-network services through deductible, copay, and coinsurance. | "OOP max", "out-of-pocket", "accumulator", "remaining". | After reaching the max, covered in-network benefits are generally paid 100% by the plan. |
25
+ | Allowed amount | The maximum amount the plan recognizes for a covered service; also called allowed charge, payment allowance, eligible expense, or negotiated rate. | "Allowed", "eligible", "negotiated", "plan discount". | Provider bills $300, allowed amount is $180; cost sharing is usually based on $180. |
26
+ | Discount / adjustment | The part of a provider's billed charge removed because of an insurer's negotiated rate or another billing adjustment. It is usually not an amount the patient pays. | "Discount", "adjustment", "network savings", "provider discount". | If the provider bills $300 and the allowed amount is $180, the discount or adjustment may be $120. |
27
+ | Provider charge / billed amount | The amount the doctor, hospital, lab, or pharmacy billed before plan discounts. | "Amount billed", "charge", "provider billed". | A hospital may bill $1,000 before discounts. |
28
+ | Plan paid | The amount the insurer paid to the provider or member. | "Plan paid", "insurance paid", "paid by plan". | If allowed is $180 and patient owes $40, plan may pay $140. |
29
+ | Patient responsibility | The amount the patient may owe after insurance processing. | "You owe", "patient responsibility", "member responsibility", "amount due". | This should generally match deductible + copay + coinsurance + non-covered amounts. |
30
+ | Explanation of Benefits (EOB) | A statement from insurance explaining how a claim was processed. It is not always a bill. | "This is not a bill", claim number, service date, provider, billed, allowed, paid, you owe. | Use the EOB to compare against a provider bill. |
31
+ | Claim | A request for payment sent to insurance for a medical service. | "Claim number", "claim status", "processed date". | A provider sends a claim after your visit. |
32
+ | In-network | A provider contracted with the insurance plan, usually at negotiated prices. | "Network", "participating provider", "preferred provider". | In-network care is usually cheaper. |
33
+ | Out-of-network | A provider not contracted with the plan; patient cost may be higher. | "Out of network", "non-participating". | Out-of-network charges may not count toward in-network limits. |
34
+ | Balance billing | When a provider bills the difference between its charge and the allowed amount. | "Balance", "above allowed amount", "not covered by plan". | If billed is $500 and allowed is $300, balance billing may be $200 when permitted. |
35
+ | Prior authorization | Approval required by the plan before some services. | "Authorization", "preauthorization", "approval required". | MRI or surgery may require prior authorization. |
36
+ | Referral | A direction from a primary-care doctor to see another provider, often a specialist. | "Referral required", "PCP referral". | Some HMO-style plans require referrals. |
37
+ | Formulary | The plan's list of covered drugs. | "Drug tier", "formulary", "preferred drug". | A generic drug may be cheaper than a brand drug. |
38
+ | CPT code | A procedure/service code used in medical billing. | Five-digit codes on bills or claims. | 99213 can indicate an office visit level. |
39
+ | ICD-10 code | A diagnosis code explaining the medical reason for care. | Codes such as E11.9 or J02.9. | Used to support medical necessity. |
40
+ | Denial | Insurance did not approve payment for all or part of a claim. | "Denied", "not covered", "reason code". | Denials may be appealable. |
41
+ | Appeal | A request for the insurer to review a denial or payment decision. | "Appeal rights", "how to appeal", deadline. | Appeal if records show the service should be covered. |
42
+ | Coordination of benefits | Rules for which insurer pays first when someone has more than one plan. | "Primary", "secondary", "COB". | One plan pays first, the second may pay some remaining amount. |
43
+ | Fixed indemnity insurance | A supplemental plan that pays a set dollar amount for covered events, not necessarily based on the full bill. | "Fixed benefit", "indemnity", "we pay per day/per visit". | It may pay $100 for a visit even if the bill is $72 or $175. |
44
+
45
+ ## How to explain a bill or claim
46
+
47
+ When a user uploads or describes a medical bill, EOB, or claim:
48
+
49
+ 1. Identify whether the document is a provider bill, an EOB, a plan summary, or a claim status page.
50
+ 2. Extract service date, provider, billed amount, allowed amount, plan paid, adjustments/discounts, deductible, copay, coinsurance, non-covered charges, and patient responsibility.
51
+ 3. Explain the math in simple steps.
52
+ 4. Flag mismatches, such as provider bill amount being higher than EOB patient responsibility.
53
+ 5. Suggest safe next actions: compare EOB with bill, call insurer/provider using the phone number on the card or bill, ask about coding, network status, prior authorization, appeal rights, and payment plans.
54
+
55
+ ## Safety rules
56
+
57
+ - Do not claim the user definitely owes or does not owe money unless the document clearly says so.
58
+ - Do not provide legal, tax, or medical advice.
59
+ - For non-U.S. users, explain that U.S. insurance terms are plan-specific and may not match their home country's system.
60
+ - Prefer document evidence over general knowledge.
61
+ - If a calculation is uncertain, show assumptions and ask for the missing value.
insurechat/knowledge_base/us_health_insurance_glossary.txt ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ US HEALTH INSURANCE — COMPLETE GLOSSARY OF TERMS
2
+ Compiled for InsureChat RAG Knowledge Base | 94+ Terms | UnitedHealthcare Focus
3
+ Sources: healthcare.gov, CMS.gov, KFF.org, IRS.gov, HHS.gov
4
+ For general information only — not legal, medical, or financial advice.
5
+ ================================================================================
6
+
7
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
8
+ SECTION A — BASIC COST TERMS
9
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
10
+
11
+ ALLOWED AMOUNT
12
+ The maximum dollar amount your insurance plan will pay for a covered service. Also called the "eligible expense," "payment allowance," or "negotiated rate." Your in-network provider has agreed to accept this as full payment. If an out-of-network provider charges more, you may owe the difference (balance billing).
13
+ Example: Your plan's allowed amount for a specialist visit is $200. The doctor charges $260. You may owe the extra $60 if out-of-network.
14
+
15
+ ANNUAL LIMIT
16
+ The maximum amount a plan pays for covered benefits in a single plan year. The ACA prohibits annual dollar limits on essential health benefits for most plans.
17
+
18
+ BALANCE BILLING
19
+ When an out-of-network provider bills you the difference between their charge and your plan's allowed amount. In-network providers agree NOT to balance bill — they accept the allowed amount as payment in full. Out-of-network providers can bill any amount above what your insurance pays.
20
+ Example: Doctor charges $500. Plan allows $300 and pays $240 (80% coinsurance). Out-of-network: you owe $60 coinsurance PLUS $200 balance bill = $260 total.
21
+
22
+ COINSURANCE
23
+ Your share of covered service costs expressed as a PERCENTAGE, paid AFTER you have met your deductible. The plan pays its percentage, you pay yours. Common splits: 80/20, 70/30, 60/40 (plan/you).
24
+ Example: MRI allowed amount $1,000. Deductible already met. With 80/20 coinsurance: you owe $200, plan pays $800.
25
+
26
+ COPAYMENT / COPAY
27
+ A FIXED dollar amount you pay for a specific covered service, usually at the time of service. A flat fee regardless of total cost. Copays often apply even before your deductible is met (check your plan).
28
+ Example: $25 copay for primary care visit, $50 for specialist, $10 for generic prescription.
29
+
30
+ DEDUCTIBLE
31
+ The amount you pay out-of-pocket for covered services BEFORE your insurance plan begins to pay (except services covered before the deductible, like preventive care). Resets every plan year. Family plans often have both individual AND family deductibles.
32
+ Example: $1,500 deductible. You have a $2,000 surgery. You pay $1,500; the plan pays its share of the remaining $500.
33
+
34
+ OUT-OF-POCKET MAXIMUM (OOP MAX)
35
+ The MOST you will pay for covered services in a plan year. After reaching this limit, your insurance pays 100% of covered services for the rest of the year. Includes deductibles, copays, and coinsurance — but NOT premiums, out-of-network costs beyond allowed amounts, or non-covered services.
36
+ Example: OOP max $6,000. Major illness costs $30,000. You pay until you hit $6,000, then the plan pays 100% the rest of the year.
37
+
38
+ PREMIUM
39
+ The amount you pay EVERY MONTH to keep your health insurance active, regardless of whether you use any health care. Premiums do NOT count toward your deductible or out-of-pocket maximum.
40
+ Example: Monthly premium $280. Your employer pays $500. Total coverage cost: $780/month.
41
+
42
+ COST SHARING
43
+ The portion of health care costs YOU pay — includes deductibles, copays, and coinsurance combined. Does not include premiums.
44
+
45
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
46
+ SECTION B — PLAN TYPES
47
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
48
+
49
+ EPO — EXCLUSIVE PROVIDER ORGANIZATION
50
+ A plan where you must use providers within the plan's network (except emergencies). No referrals needed for specialists, but NO out-of-network coverage at all. Combines lower cost of HMO with specialist flexibility of PPO.
51
+
52
+ HMO — HEALTH MAINTENANCE ORGANIZATION
53
+ A plan restricting coverage to a specific network. You choose a Primary Care Provider (PCP) who coordinates care and refers you to specialists. Generally lower premiums and copays, least flexibility. Out-of-network care is NOT covered except emergencies.
54
+ Example: Need a cardiologist? Your HMO PCP must write a referral first. Without it, the visit is not covered.
55
+
56
+ HDHP — HIGH DEDUCTIBLE HEALTH PLAN
57
+ A plan with higher deductibles than traditional plans but lower premiums. IRS minimum thresholds: $1,600 individual / $3,200 family (2024). HDHPs are the ONLY plans that allow you to open an HSA.
58
+ Note: With an HDHP, you pay full cost for most services until you hit the deductible. Pair with an HSA to save pre-tax dollars.
59
+
60
+ INDEMNITY PLAN / FEE-FOR-SERVICE
61
+ A traditional plan allowing you to see any doctor without network restrictions. You pay and submit claims for reimbursement. Most expensive premiums, most flexibility.
62
+
63
+ POS — POINT OF SERVICE PLAN
64
+ A hybrid of HMO and PPO. You choose a PCP and need referrals (like HMO) but can go out-of-network at higher cost (like PPO). Moderate premiums and flexibility.
65
+
66
+ PPO — PREFERRED PROVIDER ORGANIZATION
67
+ A plan with a network of preferred providers at discounted rates. You can see ANY provider in or out of network WITHOUT a referral, but pay more out-of-network. Most flexible plan type. Generally higher premiums than HMOs.
68
+ Example: PPO covers in-network specialists at 80% after deductible, out-of-network at 60%.
69
+
70
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
71
+ SECTION C — NETWORKS AND PROVIDERS
72
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
73
+
74
+ IN-NETWORK
75
+ Providers who have a contract with your insurance plan at pre-negotiated (discounted) rates. Using in-network providers costs you less and protects you from balance billing.
76
+
77
+ OUT-OF-NETWORK
78
+ Providers who have NOT contracted with your insurance plan. Your plan pays less (or nothing), and providers can balance bill you. HMO plans do not cover out-of-network care at all except emergencies.
79
+
80
+ PRIMARY CARE PROVIDER (PCP)
81
+ Your main doctor — general practitioner, family medicine physician, internist, pediatrician, OB-GYN, or nurse practitioner — who provides routine care and coordinates specialist referrals. HMO and POS plans require you to designate a PCP.
82
+
83
+ REFERRAL
84
+ A written order from your PCP for you to see a specialist or receive specific services. Required by most HMOs and some POS plans. PPO plans do not require referrals.
85
+ Example: Knee pain. Your HMO PCP must write a referral to an orthopedic surgeon. Without it, the visit is not covered.
86
+
87
+ SPECIALIST
88
+ A physician with advanced training in a specific area: cardiologist (heart), dermatologist (skin), neurologist (brain/nerves), oncologist (cancer), orthopedist (bones), psychiatrist (mental health), etc. Specialist visits usually have higher copays.
89
+
90
+ NETWORK ADEQUACY
91
+ The requirement that plans have sufficient in-network providers within reasonable distance and wait times. Regulated by state insurance departments.
92
+
93
+ PROVIDER DIRECTORY
94
+ A list of all in-network doctors, hospitals, labs, and providers for your plan. Always verify a provider is in-network BEFORE your appointment — directories can be outdated.
95
+ Note: Always call the provider's office to confirm they accept your specific plan, not just your insurer. For UHC: check myuhc.com.
96
+
97
+ TIERED NETWORK
98
+ Some plans organize in-network providers into tiers (Tier 1/Premium, Tier 2/Preferred, Tier 3/Standard). Tier 1 providers cost you the least. UHC and many large insurers use tiered networks.
99
+
100
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
101
+ SECTION D — CLAIMS AND DOCUMENTS
102
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
103
+
104
+ CLAIM
105
+ A request for payment submitted to your insurer — by you or your provider — after you receive covered health care services. The insurer reviews the claim, applies deductible/copay/coinsurance, and pays its share.
106
+
107
+ CLEAN CLAIM
108
+ A claim submitted with all required information and no errors. Clean claims are processed faster. Incomplete claims are rejected and must be resubmitted.
109
+
110
+ COORDINATION OF BENEFITS (COB)
111
+ Rules determining which insurance pays first (primary) and which pays second (secondary) when a person has more than one health plan. Prevents collecting more than 100% of costs.
112
+ Example: You have coverage through your job AND your spouse's job. COB determines which plan is primary and how the two plans split your costs.
113
+
114
+ CPT CODE
115
+ Current Procedural Terminology code — a standardized 5-digit code assigned to every medical procedure. Used on claims to tell insurers what was performed. Example: 99213 = routine office visit (established patient, moderate complexity).
116
+
117
+ DENIAL / CLAIM DENIAL
118
+ When your insurer refuses to pay for a service, fully or partially. Common reasons: not covered, no prior authorization, out-of-network, missing information, not medically necessary. You have the right to appeal every denial.
119
+
120
+ ICD-10 / DIAGNOSIS CODE
121
+ International Classification of Diseases, 10th Revision — standardized codes identifying a patient's medical condition or reason for a visit. Appear on EOBs and medical bills. Example: J06.9 = acute upper respiratory infection.
122
+
123
+ EOB — EXPLANATION OF BENEFITS
124
+ A statement your insurer sends AFTER you receive care. It is NOT a bill. It shows: (1) what was billed, (2) the allowed amount, (3) what the plan paid, (4) what you owe, (5) why any part was denied. Always compare your EOB to the actual bill from your provider to catch errors.
125
+ Note: If the patient responsibility on your EOB differs from your provider's bill, call both the insurer and provider to resolve before paying.
126
+
127
+ REMITTANCE ADVICE
128
+ Similar to an EOB but sent to your PROVIDER explaining what the insurer paid on your claim. Providers use this to reconcile their billing records.
129
+
130
+ REMARK CODE / ADJUSTMENT REASON CODE
131
+ Codes on your EOB explaining why a claim was adjusted, reduced, or denied.
132
+ Common codes: CO-45 = charge exceeds fee schedule. PR-1 = deductible amount. PR-2 = coinsurance. PR-3 = copay. OA-23 = previously paid claim.
133
+
134
+ SUBROGATION
135
+ The right of your insurer to recover money it paid from a third party responsible for your injury. Example: car accident — your insurer can seek reimbursement from the at-fault driver's liability insurer.
136
+
137
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
138
+ SECTION E — AUTHORIZATIONS AND UTILIZATION MANAGEMENT
139
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
140
+
141
+ CONCURRENT REVIEW
142
+ Ongoing review by your insurer of a hospitalization to determine if continued coverage is medically necessary. The insurer may approve a hospital stay initially then review each additional day.
143
+
144
+ MEDICAL NECESSITY
145
+ The standard insurers use to decide whether a treatment or service is appropriate and required based on accepted medical standards. Insurers can deny claims as "not medically necessary." You can appeal this determination.
146
+
147
+ PRIOR AUTHORIZATION / PRE-AUTHORIZATION (PA)
148
+ Approval you must get from your insurer BEFORE receiving certain services, procedures, or medications for them to be covered. Your doctor usually handles this, but you are responsible for ensuring it was obtained. Failure to get required PA can result in full denial.
149
+ Example: Doctor orders MRI. Plan requires prior auth. Doctor submits request with clinical documentation. Plan approves or denies. If denied, you or your doctor can appeal.
150
+
151
+ PRE-CERTIFICATION
152
+ Similar to prior authorization — advance approval for non-emergency hospitalizations or surgeries. Without it, your claim may be denied or subject to a penalty.
153
+
154
+ PRE-DETERMINATION
155
+ Optional advance review (not required) to find out how much your plan will pay for a planned service. Unlike prior auth, pre-determination does not guarantee payment.
156
+
157
+ STEP THERAPY / FAIL FIRST
158
+ A policy requiring you to try lower-cost medications before your plan covers a more expensive option. Example: must try generic antidepressant before plan covers brand-name. If the first option fails (documented), you proceed to the next.
159
+
160
+ UTILIZATION MANAGEMENT (UM)
161
+ Techniques insurers use to evaluate appropriateness and efficiency of health care services. Includes prior authorization, concurrent review, retrospective review, step therapy, and quantity limits.
162
+
163
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
164
+ SECTION F — PRESCRIPTION DRUG COVERAGE
165
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
166
+
167
+ DRUG FORMULARY
168
+ Your plan's list of covered prescription drugs organized into cost tiers. Tier 1 (generics) = lowest cost. Tier 2 (preferred brand-name) = medium cost. Tier 3 (non-preferred brand-name) = higher cost. Tier 4 (specialty drugs) = highest cost. Non-formulary drugs may not be covered.
169
+
170
+ GENERIC DRUG
171
+ A drug with the same active ingredients, dosage, safety, and intended use as a brand-name drug, approved by the FDA as bioequivalent. Almost always much cheaper. Tier 1 on most formularies.
172
+ Example: Lisinopril is the generic for Prinivil/Zestril. Metformin is the generic for Glucophage.
173
+
174
+ SPECIALTY DRUG
175
+ High-cost medications for complex conditions (cancer, MS, rheumatoid arthritis, hepatitis C). Often require special handling or administration. Usually Tier 4 or 5. May require prior authorization and specialty pharmacy dispensing.
176
+
177
+ MAIL-ORDER PHARMACY
178
+ A pharmacy delivering 90-day supplies of maintenance medications by mail, often at lower cost than retail. Most plans encourage or require mail-order for long-term prescriptions.
179
+
180
+ QUANTITY LIMITS
181
+ Restrictions on the number of pills or doses your plan will cover in a given time period. Example: 30-day supply limit on controlled substances. Exceeding limits requires prior authorization.
182
+
183
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
184
+ SECTION G — SPECIAL ACCOUNTS AND PROGRAMS
185
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
186
+
187
+ COBRA
188
+ Consolidated Omnibus Budget Reconciliation Act — lets you continue employer-sponsored health insurance for up to 18 months after losing coverage due to job loss, reduced hours, divorce, or other qualifying events. You pay the FULL premium (employer + employee share) plus 2% admin fee.
189
+ Note: COBRA is good for short gaps. ACA Marketplace with subsidies or Medicaid may be cheaper.
190
+
191
+ FSA — FLEXIBLE SPENDING ACCOUNT
192
+ Employer-sponsored account funded with PRE-TAX dollars for eligible medical, dental, and vision expenses. Reduces taxable income. Annual limit ~$3,200 (2024 IRS limit). KEY RULE: Use it or lose it — most funds expire at year-end. Covers copays, deductibles, prescriptions, glasses, contacts, and many OTC items.
193
+
194
+ HRA — HEALTH REIMBURSEMENT ARRANGEMENT
195
+ Employer-FUNDED account (not employee) used to reimburse employees for qualified medical expenses and insurance premiums. Employer decides the contribution. Unused funds may roll over depending on plan design. You cannot take HRA funds if you leave the job.
196
+
197
+ HSA — HEALTH SAVINGS ACCOUNT
198
+ Triple-tax-advantaged savings account available ONLY with a High Deductible Health Plan (HDHP). Contributions are tax-deductible, growth is tax-free, withdrawals for qualified medical expenses are tax-free. Funds roll over every year indefinitely — yours even if you change jobs. Can be invested. After age 65, withdraw for any reason (taxed like income if not medical).
199
+ Example: Contribute $3,000 to HSA. Save ~$750 in federal taxes (25% bracket). Use $1,200 for medical expenses tax-free. Remaining $1,800 rolls over.
200
+
201
+ LIMITED PURPOSE FSA
202
+ An FSA only usable for dental and vision expenses (not general medical). Can be used alongside an HSA.
203
+
204
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
205
+ SECTION H — ACA MARKETPLACE AND ENROLLMENT
206
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
207
+
208
+ ACA — AFFORDABLE CARE ACT
209
+ The 2010 federal law (also called Obamacare) expanding health coverage through: Marketplace exchanges, Medicaid expansion, requirements to cover essential health benefits, prohibition on denying coverage for pre-existing conditions, allowing children on parents' plans until age 26, and premium tax credits.
210
+
211
+ CATASTROPHIC PLAN
212
+ A low-premium, high-deductible Marketplace plan available only to people under 30 or with a hardship exemption. Covers 3 primary care visits/year before deductible and all ACA preventive services.
213
+
214
+ ESSENTIAL HEALTH BENEFITS (EHBs)
215
+ Ten categories all ACA-compliant plans must cover:
216
+ 1. Ambulatory patient services
217
+ 2. Emergency services
218
+ 3. Hospitalization
219
+ 4. Maternity and newborn care
220
+ 5. Mental health and substance use disorder services
221
+ 6. Prescription drugs
222
+ 7. Rehabilitative services and devices
223
+ 8. Laboratory services
224
+ 9. Preventive and wellness services
225
+ 10. Pediatric services including dental and vision
226
+
227
+ METAL TIERS (BRONZE / SILVER / GOLD / PLATINUM)
228
+ ACA Marketplace plan categories based on actuarial value (how costs are split):
229
+ - Bronze: plan pays ~60%, you pay ~40%
230
+ - Silver: plan pays ~70%, you pay ~30%
231
+ - Gold: plan pays ~80%, you pay ~20%
232
+ - Platinum: plan pays ~90%, you pay ~10%
233
+ Higher metal = higher premium, lower cost-sharing.
234
+ Note: Cost-sharing reductions (CSRs) are only available on SILVER plans for eligible lower-income individuals.
235
+
236
+ OPEN ENROLLMENT PERIOD (OEP)
237
+ Annual window to enroll in or change health insurance. ACA Marketplace: November 1 – January 15. Coverage starts January 1 if enrolled by December 15; February 1 if enrolled December 16 – January 15. Employer plans: typically fall, once per year.
238
+
239
+ PREMIUM TAX CREDIT (PTC)
240
+ ACA subsidy reducing your monthly premium based on household income and size. Available as advance payments to your insurer (APTC) or claimed on your tax return. Income range: 100%-400% of federal poverty level.
241
+
242
+ QUALIFYING LIFE EVENT (QLE)
243
+ A change allowing you to enroll in or change health insurance outside of open enrollment. Examples: losing job-based coverage, getting married or divorced, having a baby, moving, aging off a parent's plan at 26.
244
+
245
+ SPECIAL ENROLLMENT PERIOD (SEP)
246
+ A limited time (usually 60 days) after a qualifying life event to enroll in, change, or cancel health insurance outside of open enrollment.
247
+
248
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
249
+ SECTION I — GOVERNMENT PROGRAMS
250
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
251
+
252
+ CHIP — CHILDREN'S HEALTH INSURANCE PROGRAM
253
+ Government program providing low-cost health coverage to children in families earning too much for Medicaid but unable to afford private insurance. Jointly funded by federal and state governments.
254
+
255
+ MEDICAID
256
+ Joint federal and state program providing free or low-cost coverage for people with low income, including families, pregnant women, elderly adults, and people with disabilities. Eligibility and coverage vary by state. ACA expanded eligibility in most states to adults up to 138% of federal poverty level.
257
+
258
+ MEDICARE
259
+ Federal health insurance primarily for people 65+, plus younger people with certain disabilities and people with End-Stage Renal Disease.
260
+ - Part A: Hospital (inpatient, skilled nursing, hospice, some home health)
261
+ - Part B: Medical/outpatient (doctor visits, preventive care, DME)
262
+ - Part C: Medicare Advantage (private plans covering A+B+usually D)
263
+ - Part D: Prescription drug coverage
264
+
265
+ MEDICARE ADVANTAGE (PART C)
266
+ Alternative to Original Medicare offered by private insurers approved by Medicare. Must cover everything Parts A and B cover. Often includes Part D, dental, vision, and hearing. May have network restrictions. Over half of Medicare beneficiaries are enrolled.
267
+
268
+ MEDIGAP / MEDICARE SUPPLEMENT
269
+ Private insurance filling the "gaps" in Original Medicare (Parts A and B) — covering deductibles, coinsurance, and copayments. Standardized plans labeled A through N. Cannot be used with Medicare Advantage.
270
+
271
+ TRICARE
272
+ Health care program for active duty military personnel, veterans, and their families, administered by the Department of Defense.
273
+
274
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
275
+ SECTION J — APPEALS AND PATIENT RIGHTS
276
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
277
+
278
+ APPEAL
279
+ A formal request asking your insurer to reconsider a denial. You have the right to appeal any adverse decision. Two levels:
280
+ 1. Internal appeal — reviewed by the insurer, decision within 30 days (non-urgent) or 72 hours (urgent).
281
+ 2. External review — reviewed by an independent organization if internal appeal is denied.
282
+ Note: Always appeal in writing. Keep copies of everything. Include supporting documentation from your doctor. Meet all deadlines (usually 180 days from denial).
283
+
284
+ EXTERNAL REVIEW
285
+ Independent review of your insurer's denial by an organization with no connection to your plan. If the reviewer decides in your favor, your insurer MUST cover the service. Protected by federal law for most plans.
286
+
287
+ GRIEVANCE
288
+ A formal complaint to your insurer about quality of care or customer service (not about a claim denial — that's an appeal). Your insurer must have a formal grievance process.
289
+
290
+ NO SURPRISES ACT / SURPRISE BILLING PROTECTIONS
291
+ Federal law effective January 1, 2022 protecting patients from unexpected bills from out-of-network providers in situations where they couldn't choose (emergencies, out-of-network providers at in-network facilities). Limits cost-sharing to in-network levels in these situations.
292
+
293
+ MENTAL HEALTH PARITY
294
+ Federal law (MHPAEA) requiring mental health and substance use disorder benefits to be no more restrictive than medical/surgical benefits. Applies to visit limits, dollar limits, prior auth requirements, and network adequacy.
295
+
296
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
297
+ SECTION K — ADDITIONAL KEY TERMS
298
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
299
+
300
+ ACTUARIAL VALUE (AV)
301
+ The percentage of total average costs a plan pays for a standard population. Bronze=60%, Silver=70%, Gold=80%, Platinum=90%.
302
+
303
+ BIRTHDAY RULE
304
+ When a child is covered by both parents' plans, the parent whose birthday falls first in the calendar year has the primary plan.
305
+
306
+ CONTINUATION COVERAGE
307
+ The right to temporarily continue health insurance after losing eligibility. COBRA is the most common form for employer plans.
308
+
309
+ CREDITABLE COVERAGE
310
+ Prior health insurance that counts toward satisfying waiting periods. Relevant for Medicare Part D — prior creditable drug coverage avoids late enrollment penalties.
311
+
312
+ DEPENDENT
313
+ A person covered by your health plan other than the subscriber. Typically includes a spouse and children up to age 26 under the ACA, regardless of marital status or financial dependency.
314
+
315
+ DME — DURABLE MEDICAL EQUIPMENT
316
+ Medical equipment ordered by a doctor for home use — wheelchairs, walkers, hospital beds, oxygen equipment, CPAP machines, insulin pumps. Covered by most major plans with varying cost-sharing. Usually requires a prescription and sometimes prior authorization.
317
+
318
+ EFFECTIVE DATE
319
+ The date your health insurance coverage begins. Services BEFORE this date are not covered.
320
+
321
+ EXCLUDED SERVICES
322
+ Health care services your plan does NOT cover at all. Common exclusions: cosmetic procedures, weight loss programs, fertility treatments (varies), long-term care, hearing aids (varies), routine vision (varies). Always check your plan's exclusions list.
323
+
324
+ GRACE PERIOD
325
+ The time after your premium due date during which you can still pay and keep coverage. Employer plans: typically 30 days. ACA Marketplace plans with APTC: up to 90 days (claims may be held after day 30).
326
+
327
+ GUARANTEED ISSUE
328
+ A requirement that insurers sell and renew policies to any applicant regardless of health status. The ACA requires guaranteed issue for individual and small group markets.
329
+
330
+ LIFETIME MAXIMUM
331
+ The total amount an insurer will pay over your lifetime. The ACA prohibits lifetime dollar limits on essential health benefits.
332
+
333
+ NPI — NATIONAL PROVIDER IDENTIFIER
334
+ A unique 10-digit ID number for every health care provider in the US. Appears on claims, EOBs, and medical bills.
335
+
336
+ PLAN YEAR
337
+ A 12-month period of benefits coverage. Your deductible, OOP max, and other accumulators RESET at the start of each plan year — which may not be January 1.
338
+ Note: Timing elective procedures relative to your plan year reset can save significant money.
339
+
340
+ PRE-EXISTING CONDITION
341
+ A health condition diagnosed or treated before starting a new insurance plan. The ACA prohibits most plans from denying coverage, charging higher premiums, or limiting benefits because of pre-existing conditions.
342
+
343
+ PREVENTIVE CARE
344
+ Routine health care aimed at preventing illness or early detection — annual physicals, vaccinations, cancer screenings, blood pressure/cholesterol checks. ACA-compliant plans must cover preventive services at NO COST, even before your deductible is met.
345
+
346
+ RIDER
347
+ An optional add-on to an insurance policy providing additional benefits (dental, vision, accident) for an additional premium.
348
+
349
+ SBC — SUMMARY OF BENEFITS AND COVERAGE
350
+ A standardized, plain-language summary (required by the ACA) describing what your plan covers and costs. Maximum 8 pages. Download yours from your insurer's website or ask HR. Use it to compare plans.
351
+
352
+ URGENT CARE
353
+ Care for conditions not life-threatening but needing attention within 24 hours — ear infections, minor cuts, sprains, UTIs, flu. Lower copays than the ER, shorter waits. Not appropriate for chest pain, stroke symptoms, or severe injuries.
354
+
355
+ WAITING PERIOD
356
+ Time an employee must wait before employer-sponsored coverage begins (typically 30-90 days after hire). ACA limits waiting periods to 90 days for employer plans.
357
+
358
+ WORKERS COMPENSATION
359
+ Separate from health insurance — a state-mandated program covering medical treatment and lost wages for work-related injuries. Your health insurance should NOT be billed for work-related injuries.
360
+
361
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
362
+ UNITEDHEALTHCARE-SPECIFIC INFORMATION
363
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
364
+
365
+ MYUHC.COM
366
+ UnitedHealthcare's member portal at myuhc.com. Access your EOBs, ID cards, claims history, find in-network providers, view plan documents, manage prior authorizations, and download your Summary of Benefits and Coverage (SBC).
367
+
368
+ UHC MEMBER ID CARD
369
+ Your insurance card showing your member ID, group number, plan name, and member services phone number. The phone number on the back is your first call for any coverage or claims question. Always carry it or have it in the UHC mobile app.
370
+
371
+ UHC PRIOR AUTHORIZATION
372
+ UHC requires prior auth for many procedures, specialty drugs, certain imaging (MRI, CT), and out-of-network referrals. Your provider usually handles submission, but you are responsible for confirming it was obtained before the service. Check requirements at myuhc.com or call member services.
373
+
374
+ UHC APPEALS PROCESS
375
+ Step 1 — Internal Appeal: Submit within 180 days of denial. UHC must decide within 30 days (non-urgent), 72 hours (urgent/expedited), or 60 days (post-service).
376
+ Step 2 — External Review: If UHC upholds the denial, request independent external review.
377
+ Contact: Use the address and phone number on your denial letter. Document everything in writing.
378
+
379
+ UHC TELEHEALTH / VIRTUAL VISITS
380
+ UHC covers telehealth through UnitedHealth Group's virtual care platform and participating providers. Typically lower copay than in-person visits. Available for primary care, mental health, and some specialty care. Check your plan for telehealth-specific copay amounts.
381
+
382
+ UHC TIERED NETWORK
383
+ Many UHC plans organize in-network providers into tiers: Premium (Tier 1, lowest cost), Preferred (Tier 2), and Standard (Tier 3). Using Tier 1 (Premium) providers saves the most money. Always check the tier of a provider at myuhc.com before your appointment.
384
+
385
+ UHC HEALTH PLAN TYPES OFFERED
386
+ UHC offers HMO, PPO, EPO, HDHP, Medicare Advantage, Medicare Supplement, Medicaid managed care, and ACA Marketplace plans. Plan availability varies by state and employer.
387
+
388
+ UHC PRIOR AUTH LOOKUP
389
+ To check if a service requires prior authorization: log in to myuhc.com > My Plan > Prior Authorization, or call the member services number on your ID card, or have your provider check through UHC's provider portal (UnitedHealthCareOnline.com).
390
+
391
+ ================================================================================
392
+ END OF GLOSSARY | 100+ Terms Defined
393
+ Sources: healthcare.gov, CMS.gov, KFF.org, IRS.gov, HHS.gov, UHC public resources
394
+ For general information only — not legal, medical, or financial advice.
395
+ ================================================================================
insurechat/requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python dependencies only. GGUF model files and the Tesseract application
2
+ # must be installed separately; see the repository README.
3
+ --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu
4
+
5
+ gradio>=4.40.0
6
+ llama-cpp-python
7
+ sentence-transformers
8
+ faiss-cpu
9
+ pypdf
10
+ pymupdf
11
+ pytesseract
12
+ Pillow
13
+ scikit-learn
14
+ huggingface-hub
15
+ requests
16
+ transformers
17
+ cryptography
insurechat/sbc_utils.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ def parse_plan_terms(text: str) -> dict:
4
+ """Extract common plan numeric terms from SBC text.
5
+
6
+ Returns a dict with keys like 'overall_deductible_network_individual',
7
+ 'out_of_pocket_limit_network_individual', 'pcp_copay', 'specialist_copay',
8
+ 'urgent_copay', 'hospital_coinsurance', 'other_coinsurance'. Values are numbers.
9
+ """
10
+ terms = {}
11
+ # overall deductible (network) individual
12
+ m = re.search(r"For network providers\s*\$\s?([0-9,]+)\s*individual", text, re.I)
13
+ if m:
14
+ terms['overall_deductible_network_individual'] = float(m.group(1).replace(',', ''))
15
+ else:
16
+ m2 = re.search(r"deductible[^\$]{0,60}\$\s?([0-9,]+)", text, re.I)
17
+ if m2:
18
+ terms['overall_deductible_network_individual'] = float(m2.group(1).replace(',', ''))
19
+
20
+ # out-of-pocket limit
21
+ m = re.search(r"For network providers\s*\$\s?([0-9,]+)\s*individual\s*/\s*\$\s?([0-9,]+)\s*family", text, re.I)
22
+ if m:
23
+ terms['out_of_pocket_limit_network_individual'] = float(m.group(1).replace(',', ''))
24
+ else:
25
+ m2 = re.search(r"out-of-pocket limit[\s\S]{0,80}\$\s?([0-9,]+)\s*individual", text, re.I)
26
+ if m2:
27
+ terms['out_of_pocket_limit_network_individual'] = float(m2.group(1).replace(',', ''))
28
+
29
+ # copays
30
+ m = re.search(r"Primary care visit[\s\S]{0,80}\$\s?([0-9,]+)", text, re.I)
31
+ if m:
32
+ terms['pcp_copay'] = float(m.group(1).replace(',', ''))
33
+ m = re.search(r"Specialist\s*Visit[\s\S]{0,80}\$\s?([0-9,]+)", text, re.I)
34
+ if m:
35
+ terms['specialist_copay'] = float(m.group(1).replace(',', ''))
36
+ m = re.search(r"Urgent care[\s\S]{0,80}\$\s?([0-9,]+)", text, re.I)
37
+ if m:
38
+ terms['urgent_copay'] = float(m.group(1).replace(',', ''))
39
+
40
+ # coinsurance selection by nearby context
41
+ for mm in re.finditer(r"([0-9]{1,3})%\s*(?:\n|\s)*Coinsurance", text, re.I):
42
+ pct = float(mm.group(1)) / 100.0
43
+ head = text[max(0, mm.start()-80):mm.start()].lower()
44
+ if any(k in head for k in ('hospital', 'facility', 'hospital (facility)', 'facility fee')):
45
+ terms['hospital_coinsurance'] = pct
46
+ break
47
+ if 'hospital_coinsurance' not in terms:
48
+ for mm in re.finditer(r"([0-9]{1,3})%\s*(?:\n|\s)*Coinsurance", text, re.I):
49
+ pct = float(mm.group(1)) / 100.0
50
+ head = text[max(0, mm.start()-80):mm.start()].lower()
51
+ if 'other' in head:
52
+ terms['other_coinsurance'] = pct
53
+ break
54
+
55
+ # fallback: any coinsurance
56
+ if 'hospital_coinsurance' not in terms and 'other_coinsurance' not in terms:
57
+ m = re.search(r"([0-9]{1,3})%\s*Coinsurance", text, re.I)
58
+ if m:
59
+ terms['other_coinsurance'] = float(m.group(1)) / 100.0
60
+
61
+ return terms
62
+
63
+
64
+ def estimate_member_payment(bill_amount: float, service_type: str, network: str, plan: dict) -> str:
65
+ """Estimate member payment for a single service given plan terms.
66
+
67
+ Simplified rules:
68
+ - Member pays deductible first up to overall deductible
69
+ - After deductible, coinsurance applies to remaining amount
70
+ - Cap at out-of-pocket limit if available
71
+ """
72
+ ded = plan.get('overall_deductible_network_individual', 0.0)
73
+ oop = plan.get('out_of_pocket_limit_network_individual', None)
74
+ if service_type == 'hospital':
75
+ coin = plan.get('hospital_coinsurance', plan.get('other_coinsurance', 0.0))
76
+ else:
77
+ coin = plan.get('other_coinsurance', 0.0)
78
+
79
+ # member pays up to deductible first
80
+ member_ded = min(ded, bill_amount)
81
+ remaining = max(0.0, bill_amount - member_ded)
82
+ member_after_ded = coin * remaining
83
+ member_total = member_ded + member_after_ded
84
+
85
+ if oop is not None:
86
+ member_total_capped = min(member_total, oop)
87
+ else:
88
+ member_total_capped = member_total
89
+
90
+ return f"Estimate for ${bill_amount:,.0f} {('in-network' if network=='network' else '')} {service_type} bill: member pays ${member_total_capped:,.2f} (raw calc ${member_total:,.2f})"
insurechat/seed_knowledge_base.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Seed the knowledge_base/insurance_glossary.md by fetching public URLs (optional).
3
+ This is designed to be run once with network access.
4
+ """
5
+ import requests
6
+ from pathlib import Path
7
+
8
+ KB = Path(__file__).parent / 'knowledge_base' / 'insurance_glossary.md'
9
+ KB.parent.mkdir(exist_ok=True)
10
+
11
+ SOURCES = [
12
+ 'https://www.healthcare.gov/what-are-premiums-deductibles-copayments-and-coinsurance/',
13
+ ]
14
+
15
+ out = []
16
+ for url in SOURCES:
17
+ try:
18
+ r = requests.get(url, timeout=10)
19
+ if r.ok:
20
+ out.append(f"# Source: {url}\n\n"+r.text[:20000])
21
+ except Exception as e:
22
+ print('Failed', url, e)
23
+
24
+ KB.write_text('\n\n'.join(out), encoding='utf8')
25
+ print('Wrote', KB)
requirements.txt ADDED
Binary file (5.09 kB). View file
 
run_insurechat.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Launcher for InsureChat that imports the package and starts the Gradio demo.
2
+
3
+ This file is intended as a simple entrypoint for Hugging Face Spaces which
4
+ executes a top-level script. It imports the `insurechat.app` module and then
5
+ launches the `demo` Gradio interface defined there.
6
+ """
7
+ from insurechat import app as _app
8
+ import atexit
9
+ import asyncio
10
+
11
+
12
+ def _close_async_loop():
13
+ try:
14
+ loop = asyncio.get_event_loop()
15
+ if loop and not loop.is_closed():
16
+ try:
17
+ loop.stop()
18
+ except Exception:
19
+ pass
20
+ try:
21
+ loop.close()
22
+ except Exception:
23
+ pass
24
+ except Exception:
25
+ pass
26
+
27
+
28
+ atexit.register(_close_async_loop)
29
+
30
+
31
+ if __name__ == "__main__":
32
+ try:
33
+ # Explicit server args help Spaces and make behavior predictable.
34
+ _app.demo.launch(server_name="0.0.0.0", server_port=7860, share=False, inbrowser=False)
35
+ except Exception as e:
36
+ print("Failed to launch InsureChat demo:", e)
37
+ raise
38
+ finally:
39
+ _close_async_loop()
40
+
41
+ if __name__ == "__main__":
42
+ try:
43
+ _app.demo.launch()
44
+ except Exception as e:
45
+ print("Failed to launch InsureChat demo:", e)
46
+ raise
single_pdf_input.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ # Try to import the original (heavy) dependencies; if they fail (e.g. torch DLL issues),
4
+ # fall back to lightweight implementations that avoid torch/transformers.
5
+ try:
6
+ from langchain_community.document_loaders import PyPDFLoader
7
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
8
+ from langchain_community.embeddings import HuggingFaceEmbeddings
9
+ from langchain_community.vectorstores import FAISS
10
+ from langchain_community.llms import Ollama
11
+ from langchain_core.prompts import PromptTemplate
12
+ HEAVY_BACKEND = True
13
+ except Exception as _err:
14
+ HEAVY_BACKEND = False
15
+ print("Falling back to lightweight PDF loader/retriever due to import error:", _err)
16
+ # Lightweight PDF loader using pypdf
17
+ from pypdf import PdfReader
18
+ import re
19
+
20
+ class _SimpleDoc:
21
+ def __init__(self, text, page_index=0):
22
+ self.page_content = text
23
+ self.metadata = {"page": page_index}
24
+
25
+ def PyPDFLoader(path):
26
+ class L:
27
+ def __init__(self, p):
28
+ self.p = p
29
+
30
+ def load(self):
31
+ reader = PdfReader(self.p)
32
+ docs = []
33
+ for i, page in enumerate(reader.pages):
34
+ text = page.extract_text() or ""
35
+ docs.append(_SimpleDoc(text, i))
36
+ return docs
37
+
38
+ return L(path)
39
+
40
+ # Simple character splitter
41
+ class RecursiveCharacterTextSplitter:
42
+ def __init__(self, chunk_size=500, chunk_overlap=100):
43
+ self.chunk_size = chunk_size
44
+ self.chunk_overlap = chunk_overlap
45
+
46
+ def split_documents(self, documents):
47
+ out = []
48
+ for d in documents:
49
+ text = d.page_content
50
+ if not text:
51
+ continue
52
+ start = 0
53
+ while start < len(text):
54
+ end = start + self.chunk_size
55
+ chunk = text[start:end]
56
+ out.append(_SimpleDoc(chunk, d.metadata.get("page", 0)))
57
+ start = max(end - self.chunk_overlap, end)
58
+ return out
59
+
60
+ # Simple retriever using TF-IDF if available, otherwise substring match
61
+ try:
62
+ from sklearn.feature_extraction.text import TfidfVectorizer
63
+ from sklearn.metrics.pairwise import cosine_similarity
64
+
65
+ class SimpleRetriever:
66
+ def __init__(self, docs):
67
+ self.docs = docs
68
+ self.texts = [d.page_content for d in docs]
69
+ self.vectorizer = TfidfVectorizer().fit(self.texts)
70
+ self.vectors = self.vectorizer.transform(self.texts)
71
+
72
+ def invoke(self, query, topk=3):
73
+ qv = self.vectorizer.transform([query])
74
+ sims = cosine_similarity(qv, self.vectors)[0]
75
+ idxs = sims.argsort()[::-1][:topk]
76
+ return [self.docs[i] for i in idxs]
77
+
78
+ except Exception:
79
+ class SimpleRetriever:
80
+ def __init__(self, docs):
81
+ self.docs = docs
82
+
83
+ def invoke(self, query, topk=3):
84
+ hits = [d for d in self.docs if query.lower() in d.page_content.lower()]
85
+ return hits[:topk]
86
+
87
+ # Lightweight LLM fallback (echo / context-based) if Ollama unavailable
88
+ class Ollama:
89
+ def __init__(self, model=None):
90
+ self.model = model
91
+
92
+ def invoke(self, prompt):
93
+ # Very small heuristic: return the context first 1000 chars as an answer stub
94
+ if "Context:" in prompt:
95
+ parts = prompt.split("Context:")
96
+ if len(parts) > 1:
97
+ ctx = parts[1].split("Question:")[0].strip()
98
+ return ctx[:1000] or "(no context found)"
99
+ return "(LLM fallback)"
100
+
101
+ vectorstore = None
102
+ retriever = None
103
+ llm = None
104
+ latest_text = None
105
+ plan_terms = {}
106
+
107
+ def process_pdf(file):
108
+ global vectorstore, retriever, llm
109
+ global latest_text, plan_terms
110
+
111
+ import traceback
112
+
113
+ def _resolve_path(f):
114
+ # Accept a file path string, a file-like with .name, or a Gradio dict
115
+ if isinstance(f, str):
116
+ return f
117
+ if isinstance(f, dict):
118
+ return f.get("name") or f.get("tmp_path") or f.get("file")
119
+ if hasattr(f, "name"):
120
+ return f.name
121
+ return None
122
+ try:
123
+ path = _resolve_path(file)
124
+ print(" PDF received:", path)
125
+ if not path:
126
+ raise ValueError("Could not resolve uploaded file path")
127
+
128
+ # Load PDF
129
+ loader = PyPDFLoader(path)
130
+ documents = loader.load()
131
+ print(" Loaded pages:", len(documents))
132
+
133
+ # concatenate raw text for parsing
134
+ latest_text = "\n\n".join([d.page_content for d in documents])
135
+
136
+ # Split text
137
+ splitter = RecursiveCharacterTextSplitter(
138
+ chunk_size=500,
139
+ chunk_overlap=100
140
+ )
141
+ chunks = splitter.split_documents(documents)
142
+ print(" Created chunks:", len(chunks))
143
+
144
+ # Create embeddings
145
+ print(" Creating embeddings...")
146
+ embeddings = None
147
+ if HEAVY_BACKEND:
148
+ embeddings = HuggingFaceEmbeddings(
149
+ model_name="all-MiniLM-L6-v2"
150
+ )
151
+
152
+ # Create vector DB
153
+ if HEAVY_BACKEND and embeddings is not None:
154
+ vectorstore = FAISS.from_documents(chunks, embeddings)
155
+ retriever = vectorstore.as_retriever()
156
+ else:
157
+ # lightweight retriever
158
+ retriever = SimpleRetriever(chunks)
159
+
160
+ print(" Vector DB ready!")
161
+
162
+ # Load LLM
163
+ llm = Ollama(model="llama3")
164
+ print(" Ollama LLM ready!")
165
+
166
+ # parse plan terms for numeric Q&A
167
+ try:
168
+ plan_terms = parse_plan_terms(latest_text)
169
+ print('Parsed plan terms:', plan_terms)
170
+ except Exception:
171
+ plan_terms = {}
172
+
173
+ return "PDF processed successfully! You can now ask questions."
174
+ except Exception as e:
175
+ tb = traceback.format_exc()
176
+ print(tb)
177
+ return f"ERROR processing PDF: {e}\n{tb}"
178
+
179
+
180
+ def chat_with_pdf(question):
181
+ global retriever, llm
182
+ global latest_text, plan_terms
183
+ import traceback
184
+ try:
185
+ if retriever is None:
186
+ return "Please upload and process a PDF first."
187
+
188
+ print(" Question:", question)
189
+
190
+ docs = retriever.invoke(question)
191
+ print(" Retrieved chunks:", len(docs))
192
+
193
+ context = "\n\n".join([doc.page_content for doc in docs])
194
+
195
+ prompt = f"""
196
+ You are a helpful assistant.
197
+ Answer ONLY from the provided context.
198
+
199
+ Context:
200
+ {context}
201
+
202
+ Question:
203
+ {question}
204
+
205
+ Answer:
206
+ """
207
+
208
+ print(" Sending to LLM...")
209
+ # detect direct numeric cost questions and answer using parsed plan terms
210
+ m = re.search(r"\$(\s?[0-9,]+)", question)
211
+ if m and plan_terms:
212
+ # get numeric value
213
+ amt = float(re.sub(r"[^0-9.]", "", m.group(0)))
214
+ # basic detection for hospital
215
+ if re.search(r"hospital|facility|inpatient|delivery", question, re.I):
216
+ est = estimate_member_payment(amt, service_type='hospital', network='network', plan=plan_terms)
217
+ return est
218
+
219
+ response = llm.invoke(prompt)
220
+ print(" Response generated.")
221
+ return response
222
+ except Exception as e:
223
+ tb = traceback.format_exc()
224
+ print(tb)
225
+ return f"ERROR in chat: {e}\n{tb}"
226
+
227
+
228
+ with gr.Blocks() as demo:
229
+ gr.Markdown("# Local RAG Chatbot (Modern Version)")
230
+ gr.Markdown("Upload a PDF, process it, then ask questions.")
231
+
232
+ file_input = gr.File(label="Upload PDF", file_types=[".pdf"])
233
+ process_button = gr.Button("Process PDF")
234
+ status_output = gr.Textbox(label="Status")
235
+
236
+ question_input = gr.Textbox(label="Ask a Question")
237
+ answer_output = gr.Textbox(label="Answer")
238
+
239
+ process_button.click(process_pdf, inputs=file_input, outputs=status_output)
240
+ question_input.submit(chat_with_pdf, inputs=question_input, outputs=answer_output)
241
+
242
+ if __name__ == '__main__':
243
+ demo.launch()
244
+
245
+ def parse_plan_terms(text: str) -> dict:
246
+ """Extract common plan numeric terms from SBC text.
247
+
248
+ Returns keys: overall_deductible_network_individual, out_of_pocket_limit_network_individual,
249
+ specialist_copay, pcp_copay, urgent_copay, hospital_coinsurance, other_coinsurance
250
+ """
251
+ import re
252
+ terms = {}
253
+ # overall deductible (network) individual
254
+ m = re.search(r"For network providers\s*\$\s?([0-9,]+)\s*individual", text, re.I)
255
+ if m:
256
+ terms['overall_deductible_network_individual'] = float(m.group(1).replace(',', ''))
257
+ else:
258
+ # fallback: first occurrence of 'deductible' followed by $xxx
259
+ m2 = re.search(r"deductible[^\$]{0,40}\$\s?([0-9,]+)", text, re.I)
260
+ if m2:
261
+ terms['overall_deductible_network_individual'] = float(m2.group(1).replace(',', ''))
262
+
263
+ # out-of-pocket limit network individual
264
+ m = re.search(r"out-of-pocket limit[\s\S]{0,80}For network providers\s*\$\s?([0-9,]+)\s*individual", text, re.I)
265
+ if m:
266
+ terms['out_of_pocket_limit_network_individual'] = float(m.group(1).replace(',', ''))
267
+ else:
268
+ m2 = re.search(r"out-of-pocket limit[\s\S]{0,80}\$\s?([0-9,]+)\s*individual", text, re.I)
269
+ if m2:
270
+ terms['out_of_pocket_limit_network_individual'] = float(m2.group(1).replace(',', ''))
271
+ # alternative pattern: "For network providers $8,000 individual / $16,000 family"
272
+ m_alt = re.search(r"For network providers\s*\$\s?([0-9,]+)\s*individual\s*/\s*\$\s?([0-9,]+)\s*family", text, re.I)
273
+ if m_alt:
274
+ terms['out_of_pocket_limit_network_individual'] = float(m_alt.group(1).replace(',', ''))
275
+
276
+ # copays
277
+ m = re.search(r"Primary care visit[\s\S]{0,80}\$\s?([0-9,]+)", text, re.I)
278
+ if m:
279
+ terms['pcp_copay'] = float(m.group(1).replace(',', ''))
280
+ m = re.search(r"Specialist\s*Visit[\s\S]{0,80}\$\s?([0-9,]+)", text, re.I)
281
+ if m:
282
+ terms['specialist_copay'] = float(m.group(1).replace(',', ''))
283
+ m = re.search(r"Urgent care[\s\S]{0,80}\$\s?([0-9,]+)", text, re.I)
284
+ if m:
285
+ terms['urgent_copay'] = float(m.group(1).replace(',', ''))
286
+
287
+ # coinsurance percentages (hospital/other)
288
+ # find all percent coinsurance occurrences and choose the one nearest 'hospital' or 'facility'
289
+ for mm in re.finditer(r"([0-9]{1,3})%\s*(?:\n|\s)*Coinsurance", text, re.I):
290
+ pct = float(mm.group(1)) / 100.0
291
+ head = text[max(0, mm.start()-80):mm.start()].lower()
292
+ if any(k in head for k in ('hospital', 'facility', 'hospital (facility)', 'facility fee')):
293
+ terms['hospital_coinsurance'] = pct
294
+ break
295
+ # if not found, try generic 'Other' context
296
+ if 'hospital_coinsurance' not in terms:
297
+ for mm in re.finditer(r"([0-9]{1,3})%\s*(?:\n|\s)*Coinsurance", text, re.I):
298
+ pct = float(mm.group(1)) / 100.0
299
+ head = text[max(0, mm.start()-80):mm.start()].lower()
300
+ if 'other' in head:
301
+ terms['other_coinsurance'] = pct
302
+ break
303
+
304
+ # fallback coinsurance general
305
+ if 'hospital_coinsurance' not in terms:
306
+ m = re.search(r"([0-9]{1,3})%\s*Coinsurance", text, re.I)
307
+ if m:
308
+ terms['other_coinsurance'] = float(m.group(1)) / 100.0
309
+
310
+ return terms
311
+
312
+ def estimate_member_payment(bill_amount: float, service_type: str, network: str, plan: dict) -> str:
313
+ """Estimate member payment for a single service given plan terms. Simplified rules:
314
+ - Member pays deductible first up to overall deductible
315
+ - After deductible, coinsurance applies to remaining amount
316
+ - Copays are ignored for facility inpatient calculations
317
+ - Cap at out-of-pocket limit if available
318
+ """
319
+ ded = plan.get('overall_deductible_network_individual', 0.0)
320
+ oop = plan.get('out_of_pocket_limit_network_individual', None)
321
+ if service_type == 'hospital':
322
+ coin = plan.get('hospital_coinsurance', plan.get('other_coinsurance', 0.0))
323
+ else:
324
+ coin = plan.get('other_coinsurance', 0.0)
325
+
326
+ remaining = max(0.0, bill_amount - ded)
327
+ member_after_ded = coin * remaining
328
+ member_total = min(ded, bill_amount) + member_after_ded
329
+
330
+ if oop is not None:
331
+ # cap at out-of-pocket
332
+ member_total_capped = min(member_total, oop)
333
+ else:
334
+ member_total_capped = member_total
335
+
336
+ return f"Estimate for ${bill_amount:,.0f} {('in-network' if network=='network' else '')} {service_type} bill: member pays ${member_total_capped:,.2f} (raw calc ${member_total:,.2f})"
337
+
skills-lock.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": 1,
3
+ "skills": {
4
+ "chat-sdk": {
5
+ "source": "vercel/chat",
6
+ "sourceType": "github",
7
+ "skillPath": "skills/chat/SKILL.md",
8
+ "computedHash": "eec16293cb0044b8e4376dec986b96dc70bf425854c6fb7aa062890faa020a25"
9
+ }
10
+ }
11
+ }