Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,9 +1,15 @@
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
from openai import OpenAI
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
# Configure the OpenAI client with your custom API endpoint and API key.
|
6 |
-
client = OpenAI(base_url=
|
7 |
|
8 |
medical_recommendations = "MEDICAL RECOMMENDATIONS:\n\n" + "Birth control options sorted by effectiveness (typical-use rates), with brief pros, cons, and side effects:\n\nHighly Effective Methods (failure rate <1%)\n-Sterilization\n- Prevention rate: >99%\n- Pros: Permanent and low maintenance\n- Cons: Irreversible; requires surgery\n- Side effects: Surgical risks (infection, pain)\n\n-Intrauterine Devices (IUDs) – Hormonal and Copper\n- Prevention rate: >99%\n- Pros: Long-term (3–10 years), low maintenance, reversible\n- Cons: Requires provider insertion; possible initial discomfort\n- Side effects:\n - Hormonal IUD: Initial irregular bleeding\n - Copper IUD: Heavier periods, cramping; rare risk of expulsion or uterine perforation\n\n-Implant (e.g., Nexplanon)\n- Prevention rate: >99%\n- Pros: Lasts up to 3 years, low maintenance, reversible\n- Cons: Requires minor procedure for insertion and removal; may cause irregular bleeding\n- Side effects: Mood changes, headaches, weight gain, pain at insertion site\n\nModerately Effective Methods (failure rate ~1–9%)\n-Injectable (e.g., Depo-Provera)\n- Prevention rate: ~96%\n- Pros: Injection every 3 months; high efficacy when on schedule\n- Cons: Can cause irregular bleeding; fertility may be delayed after stopping\n- Side effects: Weight gain, mood swings, potential bone density loss, injection site reactions\n\n-Oral Contraceptive Pills (combined or progestin-only)\n- Prevention rate: ~91%\n- Pros: Regulates cycles, may reduce cramps and help with acne; quick return to fertility\n- Cons: Must be taken daily; effectiveness depends on correct use\n- Side effects: Risk of blood clots (especially for smokers or women over 35), nausea, breast tenderness, mood changes, possible increased blood pressure\n- Prescriptions: Yaz, Yasmin, Ortho TriCyclen, Alesse, Loestrin\n- OTC: OPill $20/month, Taken Daily\n\n-Transdermal Patch (e.g., Ortho Evra)\n- Prevention rate: ~91%\n- Pros: Weekly application; steady hormone delivery\n- Cons: May cause skin irritation; visible on skin; less effective if detached\n- Side effects: Similar to pills (blood clots, nausea, breast tenderness, headaches)\n\n-Vaginal Ring (e.g., NuvaRing)\n- Prevention rate: ~91%\n- Pros: Monthly insertion; lower systemic hormone levels\n- Cons: Requires comfort with insertion and removal; possible vaginal discomfort\n- Side effects: Risk of blood clots, mood changes, headaches, vaginal irritation\n\nLess Effective Methods (failure rate 10% or higher)\n-Barrier Methods\n- Male Condoms\n - Prevention rate: ~87%\n - Pros: Also protect against STIs; non-hormonal; widely available\n - Cons: Effectiveness depends on correct use; may break or slip\n - Side effects: Possible latex allergy\n- Female Condoms\n - Prevention rate: ~79%\n - Pros: Offer STI protection; female-controlled\n - Cons: More expensive; less available; may be harder to use\n - Side effects: Possible irritation or allergic reaction\n- Diaphragms and Cervical Caps\n - Prevention rate: ~83–88%\n - Pros: Reusable; non-hormonal\n - Cons: Must be used with spermicide; requires proper fitting and timing\n - Side effects: Potential irritation, allergic reactions, increased risk of UTIs\n\n-Spermicides (used alone)\n- Prevention rate: ~79%\n- Pros: Over-the-counter; can be combined with other methods\n- Cons: Lower effectiveness when used alone; requires application every time\n- Side effects: May cause irritation or allergic reactions\n\n-Fertility Awareness Methods\n- Prevention rate: ~76% (varies widely)\n- Pros: No hormones or devices; increases understanding of your cycle\n- Cons: Requires daily tracking and strict adherence; higher risk of unintended pregnancy if not followed precisely\n- Side effects: None medically\n\n-Withdrawal (Coitus Interruptus)\n- Prevention rate: ~78%\n- Pros: No cost; non-hormonal\n- Cons: Relies heavily on timing; risk from pre-ejaculate\n- Side effects: No direct side effects; may cause stress if it fails\n\nTreatments for Managing HIV:\n- **Integrase Strand Transfer Inhibitor (INSTI)–Based Regimens:** \n - Bictegravir/emtricitabine/tenofovir alafenamide (Biktarvy) \n - Dolutegravir/lamivudine/abacavir (Triumeq)\n\n- **Non-Nucleoside Reverse Transcriptase Inhibitor (NNRTI)–Based Regimen:** \n - Efavirenz/emtricitabine/tenofovir disoproxil fumarate (Atripla)\n\n- **Protease Inhibitor (PI)–Based Regimen:** \n - Darunavir (boosted with ritonavir or cobicistat) plus two NRTIs"
|
9 |
|
@@ -58,6 +64,37 @@ max_phrase_length = max(len(phrase) for phrase, _ in replacements)
|
|
58 |
|
59 |
MIN_FLUSH_SIZE = max(50, max_phrase_length * 2)
|
60 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
def apply_replacements(text):
|
62 |
"""
|
63 |
Replace all specified phrases in the text.
|
@@ -93,15 +130,18 @@ def chat_with_openai(message: str, history: list, temperature: float, max_new_to
|
|
93 |
conversation.append({"role": "user", "content": user_msg})
|
94 |
conversation.append({"role": "assistant", "content": assistant_msg})
|
95 |
conversation.append({"role": "user", "content": message})
|
96 |
-
# Force the model to begin its answer with a "<think>" block.
|
97 |
-
conversation.append({"role": "assistant", "content": "<think> "})
|
98 |
|
99 |
# Immediately yield a "thinking" status message.
|
100 |
yield "HealthAssistant is Thinking! Please wait, your response will output shortly...\n\n"
|
101 |
|
|
|
|
|
|
|
|
|
|
|
102 |
# Call the API with streaming enabled.
|
103 |
response = client.chat.completions.create(
|
104 |
-
model=
|
105 |
messages=conversation,
|
106 |
temperature=temperature,
|
107 |
max_tokens=max_new_tokens,
|
@@ -122,31 +162,15 @@ def chat_with_openai(message: str, history: list, temperature: float, max_new_to
|
|
122 |
token_text = delta.content or ""
|
123 |
full_response += token_text
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
if len(pending_buffer) >= MIN_FLUSH_SIZE:
|
135 |
-
# Flush all but the last max_phrase_length characters.
|
136 |
-
safe_portion = pending_buffer[:-max_phrase_length] if len(pending_buffer) > max_phrase_length else ""
|
137 |
-
if safe_portion:
|
138 |
-
display_text += apply_replacements(safe_portion)
|
139 |
-
yield display_text
|
140 |
-
pending_buffer = pending_buffer[-max_phrase_length:]
|
141 |
-
else:
|
142 |
-
# After the </think> marker, add tokens to pending_buffer.
|
143 |
-
pending_buffer += token_text
|
144 |
-
if len(pending_buffer) >= MIN_FLUSH_SIZE:
|
145 |
-
safe_portion = pending_buffer[:-max_phrase_length] if len(pending_buffer) > max_phrase_length else ""
|
146 |
-
if safe_portion:
|
147 |
-
display_text += apply_replacements(safe_portion)
|
148 |
-
yield display_text
|
149 |
-
pending_buffer = pending_buffer[-max_phrase_length:]
|
150 |
|
151 |
# After processing all tokens, flush any remaining text.
|
152 |
if pending_buffer:
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
from openai import OpenAI
|
4 |
+
import json
|
5 |
+
import requests
|
6 |
+
|
7 |
+
openai_api_key = os.getenv("OPENROUTER_API_KEY")
|
8 |
+
openai_base_url = os.getenv("OPENAI_BASE_URL")
|
9 |
+
ai_model = os.getenv("AI_MODEL")
|
10 |
|
11 |
# Configure the OpenAI client with your custom API endpoint and API key.
|
12 |
+
client = OpenAI(base_url=openai_base_url, api_key=openai_api_key)
|
13 |
|
14 |
medical_recommendations = "MEDICAL RECOMMENDATIONS:\n\n" + "Birth control options sorted by effectiveness (typical-use rates), with brief pros, cons, and side effects:\n\nHighly Effective Methods (failure rate <1%)\n-Sterilization\n- Prevention rate: >99%\n- Pros: Permanent and low maintenance\n- Cons: Irreversible; requires surgery\n- Side effects: Surgical risks (infection, pain)\n\n-Intrauterine Devices (IUDs) – Hormonal and Copper\n- Prevention rate: >99%\n- Pros: Long-term (3–10 years), low maintenance, reversible\n- Cons: Requires provider insertion; possible initial discomfort\n- Side effects:\n - Hormonal IUD: Initial irregular bleeding\n - Copper IUD: Heavier periods, cramping; rare risk of expulsion or uterine perforation\n\n-Implant (e.g., Nexplanon)\n- Prevention rate: >99%\n- Pros: Lasts up to 3 years, low maintenance, reversible\n- Cons: Requires minor procedure for insertion and removal; may cause irregular bleeding\n- Side effects: Mood changes, headaches, weight gain, pain at insertion site\n\nModerately Effective Methods (failure rate ~1–9%)\n-Injectable (e.g., Depo-Provera)\n- Prevention rate: ~96%\n- Pros: Injection every 3 months; high efficacy when on schedule\n- Cons: Can cause irregular bleeding; fertility may be delayed after stopping\n- Side effects: Weight gain, mood swings, potential bone density loss, injection site reactions\n\n-Oral Contraceptive Pills (combined or progestin-only)\n- Prevention rate: ~91%\n- Pros: Regulates cycles, may reduce cramps and help with acne; quick return to fertility\n- Cons: Must be taken daily; effectiveness depends on correct use\n- Side effects: Risk of blood clots (especially for smokers or women over 35), nausea, breast tenderness, mood changes, possible increased blood pressure\n- Prescriptions: Yaz, Yasmin, Ortho TriCyclen, Alesse, Loestrin\n- OTC: OPill $20/month, Taken Daily\n\n-Transdermal Patch (e.g., Ortho Evra)\n- Prevention rate: ~91%\n- Pros: Weekly application; steady hormone delivery\n- Cons: May cause skin irritation; visible on skin; less effective if detached\n- Side effects: Similar to pills (blood clots, nausea, breast tenderness, headaches)\n\n-Vaginal Ring (e.g., NuvaRing)\n- Prevention rate: ~91%\n- Pros: Monthly insertion; lower systemic hormone levels\n- Cons: Requires comfort with insertion and removal; possible vaginal discomfort\n- Side effects: Risk of blood clots, mood changes, headaches, vaginal irritation\n\nLess Effective Methods (failure rate 10% or higher)\n-Barrier Methods\n- Male Condoms\n - Prevention rate: ~87%\n - Pros: Also protect against STIs; non-hormonal; widely available\n - Cons: Effectiveness depends on correct use; may break or slip\n - Side effects: Possible latex allergy\n- Female Condoms\n - Prevention rate: ~79%\n - Pros: Offer STI protection; female-controlled\n - Cons: More expensive; less available; may be harder to use\n - Side effects: Possible irritation or allergic reaction\n- Diaphragms and Cervical Caps\n - Prevention rate: ~83–88%\n - Pros: Reusable; non-hormonal\n - Cons: Must be used with spermicide; requires proper fitting and timing\n - Side effects: Potential irritation, allergic reactions, increased risk of UTIs\n\n-Spermicides (used alone)\n- Prevention rate: ~79%\n- Pros: Over-the-counter; can be combined with other methods\n- Cons: Lower effectiveness when used alone; requires application every time\n- Side effects: May cause irritation or allergic reactions\n\n-Fertility Awareness Methods\n- Prevention rate: ~76% (varies widely)\n- Pros: No hormones or devices; increases understanding of your cycle\n- Cons: Requires daily tracking and strict adherence; higher risk of unintended pregnancy if not followed precisely\n- Side effects: None medically\n\n-Withdrawal (Coitus Interruptus)\n- Prevention rate: ~78%\n- Pros: No cost; non-hormonal\n- Cons: Relies heavily on timing; risk from pre-ejaculate\n- Side effects: No direct side effects; may cause stress if it fails\n\nTreatments for Managing HIV:\n- **Integrase Strand Transfer Inhibitor (INSTI)–Based Regimens:** \n - Bictegravir/emtricitabine/tenofovir alafenamide (Biktarvy) \n - Dolutegravir/lamivudine/abacavir (Triumeq)\n\n- **Non-Nucleoside Reverse Transcriptase Inhibitor (NNRTI)–Based Regimen:** \n - Efavirenz/emtricitabine/tenofovir disoproxil fumarate (Atripla)\n\n- **Protease Inhibitor (PI)–Based Regimen:** \n - Darunavir (boosted with ritonavir or cobicistat) plus two NRTIs"
|
15 |
|
|
|
64 |
|
65 |
MIN_FLUSH_SIZE = max(50, max_phrase_length * 2)
|
66 |
|
67 |
+
def think(request):
|
68 |
+
question = request
|
69 |
+
|
70 |
+
url = "https://openrouter.ai/api/v1/chat/completions"
|
71 |
+
headers = {
|
72 |
+
"Authorization": f"Bearer {openai_api_key}",
|
73 |
+
"Content-Type": "application/json"
|
74 |
+
}
|
75 |
+
|
76 |
+
def do_req(model, content, include_reasoning=False, reasoning=""):
|
77 |
+
messages = [{"role": "user", "content": content}]
|
78 |
+
|
79 |
+
if reasoning != "":
|
80 |
+
messages.append({"role": "assistant", "content": "<think>\n" + reasoning + "</think>\n"})
|
81 |
+
|
82 |
+
payload = {
|
83 |
+
"model": model,
|
84 |
+
"messages": messages,
|
85 |
+
"include_reasoning": include_reasoning,
|
86 |
+
"stop": "</think>"
|
87 |
+
}
|
88 |
+
|
89 |
+
return requests.post(url, headers=headers, data=json.dumps(payload))
|
90 |
+
|
91 |
+
|
92 |
+
# R1 will reliably return "done" for the content portion of the response
|
93 |
+
content = f"{question} Please think this through, but don't output an answer"
|
94 |
+
reasoning_response = do_req("deepseek/deepseek-r1", content, True)
|
95 |
+
reasoning = reasoning_response.json()['choices'][0]['message']['reasoning']
|
96 |
+
return reasoning
|
97 |
+
|
98 |
def apply_replacements(text):
|
99 |
"""
|
100 |
Replace all specified phrases in the text.
|
|
|
130 |
conversation.append({"role": "user", "content": user_msg})
|
131 |
conversation.append({"role": "assistant", "content": assistant_msg})
|
132 |
conversation.append({"role": "user", "content": message})
|
|
|
|
|
133 |
|
134 |
# Immediately yield a "thinking" status message.
|
135 |
yield "HealthAssistant is Thinking! Please wait, your response will output shortly...\n\n"
|
136 |
|
137 |
+
think_result = think(message)
|
138 |
+
|
139 |
+
# Force the model to begin its answer with a "<think>" block.
|
140 |
+
conversation.append({"role": "assistant", "content": "<think>\n"+think_result+"\n</think>"})
|
141 |
+
|
142 |
# Call the API with streaming enabled.
|
143 |
response = client.chat.completions.create(
|
144 |
+
model=ai_model, # Replace with your actual model identifier.
|
145 |
messages=conversation,
|
146 |
temperature=temperature,
|
147 |
max_tokens=max_new_tokens,
|
|
|
162 |
token_text = delta.content or ""
|
163 |
full_response += token_text
|
164 |
|
165 |
+
|
166 |
+
# After the </think> marker, add tokens to pending_buffer.
|
167 |
+
pending_buffer += token_text
|
168 |
+
if len(pending_buffer) >= MIN_FLUSH_SIZE:
|
169 |
+
safe_portion = pending_buffer[:-max_phrase_length] if len(pending_buffer) > max_phrase_length else ""
|
170 |
+
if safe_portion:
|
171 |
+
display_text += apply_replacements(safe_portion)
|
172 |
+
yield display_text
|
173 |
+
pending_buffer = pending_buffer[-max_phrase_length:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
|
175 |
# After processing all tokens, flush any remaining text.
|
176 |
if pending_buffer:
|