Dama03 commited on
Commit
c8ebe73
·
1 Parent(s): 411a994
Files changed (3) hide show
  1. .gitignore +1 -1
  2. README.md +284 -12
  3. app/ai_agent/agent.py +3 -2
.gitignore CHANGED
@@ -1,4 +1,3 @@
1
-
2
  __pycache__
3
  .pytest_cache
4
  .cache_cameroon
@@ -7,3 +6,4 @@ __pycache__
7
  image-test1.jpg
8
  image-test2.jpg
9
  test-audio1.wav
 
 
 
1
  __pycache__
2
  .pytest_cache
3
  .cache_cameroon
 
6
  image-test1.jpg
7
  image-test2.jpg
8
  test-audio1.wav
9
+
README.md CHANGED
@@ -1,12 +1,284 @@
1
- ---
2
- title: Medilang Tech
3
- emoji: 🏆
4
- colorFrom: indigo
5
- colorTo: purple
6
- sdk: docker
7
- pinned: false
8
- license: mit
9
- short_description: AI for medical assistance in Cameroon
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Carehelp (medicare-backend)
2
+
3
+ A FastAPI backend providing AI-powered medical assistance tailored for Cameroon, with multilingual support, conversation history, moderation for emergencies, and AI backends via Hugging Face Inference (default) or local providers (Ollama, LM Studio). OpenAI is no longer required.
4
+
5
+ Quick start
6
+
7
+ 1) Requirements
8
+ - Python 3.11+
9
+ - Create a .env file (see variables below)
10
+
11
+ 2) Install
12
+ pip install -r requirements.txt
13
+
14
+ 3) Run
15
+ uvicorn main:app --reload
16
+
17
+ Environment variables (.env)
18
+
19
+ - APP_NAME=Carehelp
20
+ - ENVIRONMENT=development
21
+ - PORT=8000
22
+ - CORS_ALLOW_ORIGINS=*
23
+ - JWT_SECRET=change_this_secret
24
+ - JWT_ALGORITHM=HS256
25
+ - ACCESS_TOKEN_EXPIRE_MINUTES=43200
26
+ - AI_PROVIDER=hf # hf | ollama | lmstudio (default: hf)
27
+
28
+ # Hugging Face
29
+ - HF_API_TOKEN= # required for private models or higher rate limits
30
+ - HF_TEXT_MODEL=meta-llama/Meta-Llama-3-8B-Instruct
31
+ - HF_ASR_MODEL=distil-whisper/distil-large-v3
32
+ - HF_VISION_CAPTION_MODEL=Salesforce/blip-image-captioning-large
33
+
34
+ # Local: Ollama
35
+ - OLLAMA_BASE_URL=http://localhost:11434
36
+ - OLLAMA_MODEL=llama3.1:8b
37
+ - OLLAMA_VISION_MODEL=llava:latest
38
+
39
+ # Local: LM Studio (OpenAI-compatible)
40
+ - LMSTUDIO_BASE_URL=http://localhost:1234/v1
41
+ - LMSTUDIO_MODEL=local-model
42
+ - PATIENT_DATA_PATH=../patient_records.json
43
+ - HF_TRANSLATION_MODEL=facebook/nllb-200-distilled-600M
44
+
45
+ # Supabase (recommended)
46
+
47
+ - SUPABASE_URL=https://your-project-ref.supabase.co
48
+ - SUPABASE_ANON_KEY=eyJhbGciOi...
49
+ - SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOi... # keep secret; server-side only
50
+ - SUPABASE_DB_PASSWORD=your-postgres-password # from Project Settings → Database → Connection
51
+
52
+ Database setup on Supabase (step-by-step)
53
+
54
+ 1) Create your Supabase project
55
+ - Go to `https://supabase.com` → New Project.
56
+ - Set a strong database password (you will use it as SUPABASE_DB_PASSWORD).
57
+ - Wait for the project to be provisioned.
58
+
59
+ 2) Configure environment variables
60
+ - In Supabase: Project Settings → API, copy `Project URL` and `anon` and `service_role` keys.
61
+ - In your backend `.env`, set SUPABASE_URL, SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY, SUPABASE_DB_PASSWORD (see above).
62
+
63
+ 3) Full SQL schema and secure RLS policies
64
+ - Open Supabase SQL Editor and run this script. It uses Supabase Auth users and keeps a separate `users` profile table keyed by `auth.users.id` (UUID):
65
+
66
+ ```sql
67
+ -- Enable UUID extension if not enabled
68
+ create extension if not exists "uuid-ossp";
69
+
70
+ -- Profiles table linked to Supabase Auth users
71
+ create table if not exists public.users (
72
+ id uuid primary key references auth.users(id) on delete cascade,
73
+ email text unique,
74
+ preferred_language text default 'fr',
75
+ created_at timestamptz default now()
76
+ );
77
+
78
+ -- Conversations table
79
+ create table if not exists public.conversations (
80
+ id bigint generated always as identity primary key,
81
+ user_id uuid references public.users(id) on delete set null,
82
+ started_at timestamptz default now(),
83
+ context text default ''
84
+ );
85
+
86
+ -- Messages table
87
+ create table if not exists public.messages (
88
+ id bigint generated always as identity primary key,
89
+ conversation_id bigint references public.conversations(id) on delete cascade,
90
+ message_type text default 'text',
91
+ content text not null,
92
+ role text default 'user',
93
+ timestamp timestamptz default now()
94
+ );
95
+
96
+ create index if not exists idx_messages_conversation_id on public.messages(conversation_id);
97
+
98
+ -- Row Level Security
99
+ alter table public.users enable row level security;
100
+ alter table public.conversations enable row level security;
101
+ alter table public.messages enable row level security;
102
+
103
+ -- Helper function to check if the auth user matches profile id
104
+ create or replace function public.is_me(profile_id uuid)
105
+ returns boolean language sql stable as $$
106
+ select auth.uid() = profile_id
107
+ $$;
108
+
109
+ -- Users policies: each user can see and update own profile
110
+ create policy "users_select_own" on public.users for select
111
+ using (is_me(id));
112
+
113
+ create policy "users_insert_self" on public.users for insert
114
+ with check (is_me(id));
115
+
116
+ create policy "users_update_own" on public.users for update
117
+ using (is_me(id)) with check (is_me(id));
118
+
119
+ -- Conversations policies: owner-only access
120
+ create policy "conversations_owner_select" on public.conversations for select
121
+ using (is_me(user_id));
122
+
123
+ create policy "conversations_owner_insert" on public.conversations for insert
124
+ with check (is_me(user_id));
125
+
126
+ create policy "conversations_owner_update" on public.conversations for update
127
+ using (is_me(user_id)) with check (is_me(user_id));
128
+
129
+ create policy "conversations_owner_delete" on public.conversations for delete
130
+ using (is_me(user_id));
131
+
132
+ -- Messages policies: access restricted by parent conversation ownership
133
+ create policy "messages_owner_select" on public.messages for select
134
+ using (exists (select 1 from public.conversations c where c.id = messages.conversation_id and is_me(c.user_id)));
135
+
136
+ create policy "messages_owner_insert" on public.messages for insert
137
+ with check (exists (select 1 from public.conversations c where c.id = conversation_id and is_me(c.user_id)));
138
+
139
+ create policy "messages_owner_update" on public.messages for update
140
+ using (exists (select 1 from public.conversations c where c.id = messages.conversation_id and is_me(c.user_id)))
141
+ with check (exists (select 1 from public.conversations c where c.id = conversation_id and is_me(c.user_id)));
142
+
143
+ create policy "messages_owner_delete" on public.messages for delete
144
+ using (exists (select 1 from public.conversations c where c.id = messages.conversation_id and is_me(c.user_id)));
145
+
146
+ -- Optional: service role bypass via RPC or using the service key (server-side)
147
+ -- Keep service key server-side only.
148
+ ```
149
+
150
+ 4) Enable Row Level Security (RLS) and basic policies
151
+ - For a quick start, you can keep RLS disabled while developing.
152
+ - Recommended (secure): enable RLS and add policies to restrict access to each user's data.
153
+ - Example policies (adjust to your auth model):
154
+
155
+ ```sql
156
+ -- WARNING: Example only. Adjust for your auth model.
157
+ alter table public.users enable row level security;
158
+ alter table public.conversations enable row level security;
159
+ alter table public.messages enable row level security;
160
+
161
+ -- If you use Supabase Auth, link auth.uid() to users.id via a mapping table or store auth.uid in users table.
162
+ -- For now, allow all for development:
163
+ create policy "allow all users read" on public.users for select using (true);
164
+ create policy "allow all users read" on public.conversations for select using (true);
165
+ create policy "allow all users read" on public.messages for select using (true);
166
+ create policy "allow all users insert" on public.users for insert with check (true);
167
+ create policy "allow all users insert" on public.conversations for insert with check (true);
168
+ create policy "allow all users insert" on public.messages for insert with check (true);
169
+ ```
170
+
171
+ 5) Install the Supabase Python client in your backend
172
+
173
+ ```bash
174
+ pip install supabase
175
+ ```
176
+
177
+ 6) Initialize the Supabase client in your backend
178
+ - Create a helper, for example `app/utils/supabase_client.py`:
179
+
180
+ ```python
181
+ from supabase import create_client, Client
182
+ import os
183
+
184
+ SUPABASE_URL = os.getenv("SUPABASE_URL")
185
+ SUPABASE_ANON_KEY = os.getenv("SUPABASE_ANON_KEY")
186
+
187
+ def get_supabase_client() -> Client:
188
+ if not SUPABASE_URL or not SUPABASE_ANON_KEY:
189
+ raise RuntimeError("Supabase credentials are not configured")
190
+ return create_client(SUPABASE_URL, SUPABASE_ANON_KEY)
191
+ ```
192
+
193
+ 7) Replace 501 stubs with Supabase queries
194
+ - Users: use Supabase Auth for registration/login; store profile in `public.users` keyed by auth.user.id.
195
+ - Conversations: insert into `conversations`, then insert messages into `messages`.
196
+ - Example (create conversation and add first message):
197
+
198
+ ```python
199
+ from app.utils.supabase_client import get_supabase_client
200
+
201
+ sb = get_supabase_client()
202
+
203
+ # Create conversation
204
+ conv = sb.table("conversations").insert({"user_id": user_id, "context": ""}).execute()
205
+ conv_id = conv.data[0]["id"]
206
+
207
+ # Add a message
208
+ sb.table("messages").insert({
209
+ "conversation_id": conv_id,
210
+ "content": user_text,
211
+ "role": "user",
212
+ "message_type": "text",
213
+ }).execute()
214
+
215
+ # Fetch last N messages
216
+ history = (
217
+ sb.table("messages")
218
+ .select("role, content")
219
+ .eq("conversation_id", conv_id)
220
+ .order("timestamp", desc=True)
221
+ .limit(10)
222
+ .execute()
223
+ ).data
224
+ ```
225
+
226
+ 8) Authentication
227
+ - Using Supabase Auth: the backend now uses `sign_in_with_password` and returns the Supabase access token.
228
+ - Protect endpoints by sending the `Authorization: Bearer <access_token>` header. RLS policies enforce per-user data access.
229
+
230
+ 9) Environment and deployment
231
+ - Set SUPABASE_* variables in your production environment.
232
+ - Ensure outbound access to `your-project-ref.supabase.co` is allowed from your server.
233
+ - Do not expose `SERVICE_ROLE` to the browser or mobile apps; keep it server-side only.
234
+
235
+ Security
236
+
237
+ - Use strong JWT secrets and rotate periodically.
238
+ - Do not store raw medical data without consent. The example schema stores message content; consider encrypting sensitive fields at rest.
239
+
240
+ API
241
+
242
+ - Auth: register /api/users/register, login /api/users/login (currently 501 until Supabase integration)
243
+ - Chat: /api/chat (currently 501 until Supabase integration)
244
+ - Transcribe: /api/transcribe
245
+ - Analyze image: /api/analyze-image
246
+ - Translate: /api/translate
247
+ - Health: /health
248
+ - Single gateway endpoint: POST /gateway with body {"action": "chat|transcribe|analyze-image|translate", "payload": { ... }}
249
+
250
+ Docker
251
+
252
+ docker build -t carehelp-backend .
253
+ docker run -p 8000:8000 --env-file .env carehelp-backend
254
+
255
+ Providers and local setup
256
+
257
+ - Hugging Face (default)
258
+ - Set `AI_PROVIDER=hf` and `HF_API_TOKEN` if needed.
259
+ - Models used:
260
+ - Text: `HF_TEXT_MODEL` (default: Meta-Llama 3 8B Instruct)
261
+ - ASR: `HF_ASR_MODEL` (default: Distil-Whisper large v3)
262
+ - Vision caption: `HF_VISION_CAPTION_MODEL` (BLIP captioning)
263
+
264
+ - Ollama (local)
265
+ - Install: https://ollama.com
266
+ - Start server: `ollama serve` (default `http://localhost:11434`)
267
+ - Pull models: `ollama pull llama3.1:8b` and `ollama pull llava:latest`
268
+ - Set `.env`: `AI_PROVIDER=ollama`, optionally customize `OLLAMA_*` vars.
269
+
270
+ - LM Studio (local)
271
+ - Install: https://lmstudio.ai
272
+ - Start the server (OpenAI-compatible) and note its base URL (default `http://localhost:1234/v1`).
273
+ - Set `.env`: `AI_PROVIDER=lmstudio`, `LMSTUDIO_BASE_URL=...`, `LMSTUDIO_MODEL=<model name in LM Studio>`.
274
+
275
+ Deploy
276
+
277
+ - Render/Heroku: deploy container or repo, set environment variables, and expose port 8000. Ensure DATABASE_URL and OPENAI_API_KEY are configured.
278
+ - AWS (ECS/Fargate or EC2): use the Dockerfile, attach secrets, and security groups to allow DB egress.
279
+
280
+ Notes
281
+
282
+ - Responses include a medical disclaimer and emergency triage to redirect urgent cases.
283
+ - RAG: primary context is `clinical_summaries.csv` (configurable via `CAMEROON_DATA_CSV`); falls back to `patient_records.json` if CSV is missing.
284
+ - Tests patch OpenAI clients in `app/ai_services.py`, and are kept compatible; runtime uses HF/Ollama/LM Studio based on `AI_PROVIDER`.
app/ai_agent/agent.py CHANGED
@@ -1,5 +1,5 @@
1
  from typing import List, Dict, Any, Optional
2
- from langchain.agents import AgentExecutor, create_react_agent, initialize_agent, AgentType
3
  from langchain_openai import ChatOpenAI
4
  from langchain_community.chat_models import ChatOllama
5
  from langchain_community.tools import Tool
@@ -505,7 +505,8 @@ Begin!
505
  )
506
  agent = create_react_agent(llm, tools, prompt)
507
  logger.info("Messages-based agent created successfully")
508
- return AgentExecutor(agent=agent, tools=tools, **common_kwargs)
 
509
 
510
  except Exception as e:
511
  logger.error(f"Error creating agent: {str(e)}", exc_info=True)
 
1
  from typing import List, Dict, Any, Optional
2
+ from langchain.agents import create_react_agent, initialize_agent, AgentType
3
  from langchain_openai import ChatOpenAI
4
  from langchain_community.chat_models import ChatOllama
5
  from langchain_community.tools import Tool
 
505
  )
506
  agent = create_react_agent(llm, tools, prompt)
507
  logger.info("Messages-based agent created successfully")
508
+ # Return the runnable agent directly (compatible with newer LangChain versions)
509
+ return agent
510
 
511
  except Exception as e:
512
  logger.error(f"Error creating agent: {str(e)}", exc_info=True)