url large_stringlengths 44 174 | chunk_text large_stringlengths 202 3.43k | chunk_vector listlengths 768 768 | chunk_id large_stringlengths 21 21 | parent_id large_stringlengths 16 16 | title large_stringlengths 4 115 | __source large_stringclasses 14
values | chunk_index int64 0 15 | token_count int64 34 586 |
|---|---|---|---|---|---|---|---|---|
https://www.acibadem.com.tr/hayat/3-yasindaki-cocugunuz-konusamiyorsa-/ | - Dil ve konuşma terapisi nedir?
- Sesini fazla kullanan meslek grupları terapiste ihtiyaç duyabilir
- Dil ve konuşma bozukluğu türleri
- Çocuklarda oyundan da yararlanılıyor
- Dil ve konuşma bozuklukları
- Aşırı teknoloji kullanımı dil ve konuşma bozukluğu nedeni
- Dil ve konuşma terapisinde pratik önemli
- Dil... | [
0.033447265625,
0.021484375,
0.057373046875,
0.03369140625,
0.0634765625,
0.03857421875,
0.032470703125,
0.044677734375,
-0.0272216796875,
-0.00168609619140625,
0.046875,
0.06103515625,
0.0228271484375,
-0.036865234375,
0.00885009765625,
0.002410888671875,
0.0008392333984375,
0.112... | a2959b7be886893f-0000 | a2959b7be886893f | 3 yaşındaki çocuğunuz konuşamıyorsa… | acibadem | 0 | 449 |
https://www.acibadem.com.tr/hayat/3-yasindaki-cocugunuz-konusamiyorsa-/ | Meslek grubu açısından her türlü bozukluk için genelleme yapmak doğru olmaz. Dil ve konuşma bozukluğu kişilerin mesleğine bağlı olarak gelişen bir durum değildir çünkü. Bu tür bir genelleme sadece ses bozuklukları için yapılabilir. Çünkü ses bozuklukları bireyin ses kullanım biçimi ve miktarıyla ilişkili olabilmektedir... | [
0.018310546875,
-0.0098876953125,
0.058349609375,
0.035400390625,
0.0291748046875,
0.0269775390625,
0.0341796875,
0.03466796875,
-0.028564453125,
0.0033416748046875,
0.03759765625,
0.0517578125,
0.0062255859375,
-0.03857421875,
0.0546875,
-0.0162353515625,
0.000370025634765625,
0.1... | a2959b7be886893f-0001 | a2959b7be886893f | 3 yaşındaki çocuğunuz konuşamıyorsa… | acibadem | 1 | 387 |
https://www.acibadem.com.tr/hayat/3-yasindaki-cocugunuz-konusamiyorsa-/ | Çocuklarda oyundan da yararlanılıyor
3. Dil ve konuşma terapisi hangi ortamlarda ve nasıl yapılır? Terapi ne kadar sürer?
Dil ve konuşma terapisi hastanelerindeki dil ve konuşma terapisi polikliniklerinde, mobil olmayan hastalar için ise odalarında yatak başı terapi denilen şekilde ya da ev ortamında; hastane dışında... | [
0.037109375,
0.000019311904907226562,
0.05029296875,
0.03564453125,
0.0286865234375,
0.01507568359375,
0.0247802734375,
0.02490234375,
-0.029296875,
-0.01080322265625,
0.05810546875,
0.0458984375,
0.01287841796875,
-0.0322265625,
0.04248046875,
-0.00701904296875,
0.01019287109375,
... | a2959b7be886893f-0002 | a2959b7be886893f | 3 yaşındaki çocuğunuz konuşamıyorsa… | acibadem | 2 | 441 |
https://www.acibadem.com.tr/hayat/3-yasindaki-cocugunuz-konusamiyorsa-/ | Beyin hasarına bağlı olarak ortaya çıkan edinilmiş dil bozukluğu (afazi), dil-konuşma gecikmesi (gecikmiş dil-konuşma), nörolojik bozukluklara bağlı dil konuşma bozuklukları (serebral palsi vb.), otizm ve diğer yaygın gelişimsel bozukluklarla ilişkili dil-konuşma ve iletişim bozuklukları, özgül dil bozukluğu, sendromla... | [
0.04931640625,
0.024169921875,
0.056396484375,
-0.00396728515625,
0.037353515625,
0.016845703125,
-0.014892578125,
0.05810546875,
-0.04052734375,
0.028076171875,
0.01068115234375,
0.0380859375,
0.0068359375,
-0.0228271484375,
0.01373291015625,
-0.0023193359375,
0.00592041015625,
0.... | a2959b7be886893f-0003 | a2959b7be886893f | 3 yaşındaki çocuğunuz konuşamıyorsa… | acibadem | 3 | 505 |
https://www.acibadem.com.tr/hayat/3-yasindaki-cocugunuz-konusamiyorsa-/ | Son zamanlarda yukarıda sayılan nedenlerin hiç biri olmaksızın dil- konuşma ve iletişimi etkileyen en önemli şeylerden biri de ekrana maruz kalmadır. TV, telefon, tablet gibi cihazlar, çocukların beyin gelişimini olumsuz yönde etkiler. Dolayısıyla bu çocuklardan normal bir dil-konuşma ve iletişim becerisi geliştirmeler... | [
0.038818359375,
0.026611328125,
0.045166015625,
0.0093994140625,
0.056884765625,
0.02587890625,
0.030029296875,
0.017578125,
-0.025634765625,
-0.00469970703125,
0.044677734375,
0.06005859375,
0.01239013671875,
-0.03857421875,
0.0235595703125,
-0.024658203125,
-0.0002384185791015625,
... | a2959b7be886893f-0004 | a2959b7be886893f | 3 yaşındaki çocuğunuz konuşamıyorsa… | acibadem | 4 | 520 |
https://www.acibadem.com.tr/hayat/3-yasindaki-cocugunuz-konusamiyorsa-/ | Dil ve konuşma bozukluğunda bunlara dikkat!
8.Dil ve konuşma bozukluğu olan çocuklarda ailelerin nelere dikkat etmelerini önerirsiniz?
Çocuklarında dil ve konuşma bozukluğu olan ya da olduğundan şüphe eden ailelerin, çocuklarının hem dil alanına hem de diğer gelişim alanlarına ilişkin gözlem yapıyor olmaları önemlidi... | [
0.04248046875,
0.02197265625,
0.05810546875,
0.0135498046875,
0.05517578125,
0.0361328125,
0.01434326171875,
0.059814453125,
-0.035888671875,
-0.0064697265625,
0.060546875,
0.01434326171875,
0.0211181640625,
-0.0255126953125,
-0.00811767578125,
0.005950927734375,
0.029296875,
0.096... | a2959b7be886893f-0005 | a2959b7be886893f | 3 yaşındaki çocuğunuz konuşamıyorsa… | acibadem | 5 | 300 |
https://www.acibadem.com.tr/hayat/anestezi-sonrasi-uyanmama-ihtimali-var-mi/ | Tıp fakültesini bitirdikten sonra bu meslekte 4 sene uzmanlığını tamamlamış kişiler anestezi doktoru olarak görev yapar. Halk arasında bilinenlere ek olarak anestezi doktoru yalnızca hastayı ameliyat başında uyutup, sonunda da uyandırmakla kalmaz. Onun misyonu, işlem boyunca hastaların güvenliğini ve tüm yaşamsal fonks... | [
0.033203125,
-0.0113525390625,
0.04541015625,
-0.061279296875,
-0.0208740234375,
-0.044677734375,
-0.00323486328125,
0.006805419921875,
0.053955078125,
-0.031494140625,
-0.025390625,
0.015625,
0.01397705078125,
-0.0244140625,
0.01361083984375,
0.00299072265625,
-0.009033203125,
0.0... | 8e25e06c640adacc-0000 | 8e25e06c640adacc | Anestezi sonrası uyanmama ihtimali var mı? | acibadem | 0 | 448 |
https://www.acibadem.com.tr/hayat/anestezi-sonrasi-uyanmama-ihtimali-var-mi/ | Anestezi; hastaya başlangıçta verilen ve bitince alınan bir materyal değildir. Ne kadar anestezi verileceği, anestezinin ne kadar süreceği konularında bir ölçü yoktur. Anestezi sürecinin kabaca bir öngörüsü ve ön programı bulunur. Süresi ise planlanmaz çünkü ameliyat dinamik bir işlemdir. Anestezist, gerçekleşmekte ola... | [
0.035888671875,
-0.007232666015625,
0.043212890625,
-0.04052734375,
-0.00701904296875,
-0.045166015625,
0.0142822265625,
-0.0169677734375,
0.0260009765625,
-0.0211181640625,
-0.0203857421875,
0.025634765625,
0.001617431640625,
-0.01043701171875,
0.0240478515625,
-0.00848388671875,
0.... | 8e25e06c640adacc-0001 | 8e25e06c640adacc | Anestezi sonrası uyanmama ihtimali var mı? | acibadem | 1 | 380 |
https://www.acibadem.com.tr/hayat/anestezi-sonrasi-uyanmama-ihtimali-var-mi/ | Bölgesel anestezi bazen omurilikten sinirlerin çıkma bölgesine tek doz ilaç yapılarak bazen de buraya yerleştirilen kateterden sürekli ilaç vererek uygulanır. Spinal anestezi, epidural anestezi, kombine spinal-epidural anestezi diye bahsedilen yöntemler bunlardır. Bu yöntemler bu alanlarda eğitim almış anestezi doktorl... | [
0.0279541015625,
0.0023651123046875,
0.0032501220703125,
-0.061767578125,
0.0167236328125,
-0.041015625,
0.00848388671875,
-0.01080322265625,
0.0458984375,
0.0086669921875,
-0.0311279296875,
0.0272216796875,
-0.018798828125,
0.0284423828125,
0.036376953125,
-0.0181884765625,
0.024047... | 8e25e06c640adacc-0002 | 8e25e06c640adacc | Anestezi sonrası uyanmama ihtimali var mı? | acibadem | 2 | 255 |
https://www.acibadem.com.tr/hayat/ani-salgin-nedir-yaygin-ani-salginlar-nelerdir/ | - Ani Salgın Nedir?Ani Salgınların Nedenleri Nelerdir?Ani Salgınların Belirtileri Nelerdir?Ani Salgınların Teşhisi Nasıl Yapılır?Ani Salgılnar Nasıl Kontrol Altına Alınır?Sıkça Sorulan Sorular (SSS)
Ani Salgın Nedir?
Ani salgın, belirli bir bölgede kısa sürede çok sayıda insanı etkileyen bulaşıcı hastalıkların ortaya... | [
0.05029296875,
0.01104736328125,
-0.0191650390625,
-0.01080322265625,
0.02099609375,
0.01055908203125,
0.016845703125,
-0.02294921875,
-0.0145263671875,
0.00095367431640625,
-0.044189453125,
0.04052734375,
-0.0380859375,
-0.034912109375,
0.01953125,
0.0130615234375,
0.0230712890625,
... | 2efae7a85989a87e-0000 | 2efae7a85989a87e | Ani Salgın Nedir? Ani Salgınlar Nelerdir? | acibadem | 0 | 523 |
https://www.acibadem.com.tr/hayat/ani-salgin-nedir-yaygin-ani-salginlar-nelerdir/ | - Covid-19 ve SARS gibi koronavirüs kaynaklı salgınlar
- Norovirüs ve rotavirüs gibi mide-bağırsak enfeksiyonları
- Gıda zehirlenmesine neden olanSalmonella,E. colisalgınları
- Su yoluyla bulaşankolera, tifo gibi bakteriyel enfeksiyonlar
- Menenjit salgınları (özellikle toplu yaşam alanlarında)
- Kızamık, kabakula... | [
0.0625,
0.0115966796875,
0.00396728515625,
-0.008544921875,
-0.00927734375,
-0.0008392333984375,
0.0022735595703125,
-0.01007080078125,
-0.0118408203125,
-0.0023193359375,
-0.033203125,
0.042236328125,
-0.031005859375,
-0.035400390625,
0.0228271484375,
0.005340576171875,
0.0185546875... | 2efae7a85989a87e-0001 | 2efae7a85989a87e | Ani Salgın Nedir? Ani Salgınlar Nelerdir? | acibadem | 1 | 530 |
https://www.acibadem.com.tr/hayat/ani-salgin-nedir-yaygin-ani-salginlar-nelerdir/ | Ani salgınlar genellikle kısa sürelidir ve hızla zirve noktasına ulaşıp kısa zamanda etkisini yitirir. Buna karşılıkendemik,epidemikveyapandemiksalgınlar daha uzun süre devam edebilir. Örneğin, bir pandemi aylar hatta yıllar sürebilirken ani salgınlar günler veya haftalar içinde sona erebilir.
Ani salgınlar çoğunlukla... | [
0.0595703125,
0.01239013671875,
-0.00262451171875,
-0.00799560546875,
0.0150146484375,
0.0107421875,
0.0034942626953125,
-0.00836181640625,
-0.021728515625,
0.0024261474609375,
-0.031494140625,
0.047607421875,
-0.0238037109375,
-0.040283203125,
0.019287109375,
0.01483154296875,
0.021... | 2efae7a85989a87e-0002 | 2efae7a85989a87e | Ani Salgın Nedir? Ani Salgınlar Nelerdir? | acibadem | 2 | 520 |
https://www.acibadem.com.tr/hayat/ani-salgin-nedir-yaygin-ani-salginlar-nelerdir/ | Özellikle kapalı ve kalabalık ortamlarda bu tür bulaşıcı hastalıkların yayılma riski daha fazla olabilir.
Bağışıklık sistemi zayıf olan bireyler veya kronik hastalığı olanlar, enfeksiyonlara karşı daha savunmasızdır ve bu da ani salgınların yayılmasını hızlandırabilir. Özellikle ellere ve yüzeylere doğru hijyenik önle... | [
0.046142578125,
0.0145263671875,
0.00927734375,
0.0106201171875,
0.01373291015625,
0.053955078125,
0.0164794921875,
-0.00994873046875,
-0.04150390625,
0.01214599609375,
-0.0654296875,
0.038818359375,
-0.02734375,
-0.0087890625,
0.004241943359375,
-0.00677490234375,
0.0208740234375,
... | 2efae7a85989a87e-0003 | 2efae7a85989a87e | Ani Salgın Nedir? Ani Salgınlar Nelerdir? | acibadem | 3 | 488 |
- Two independent refusal layers
- Technology stack
- Quick start
- 1. Article selection and chunking
- 2. Vector database schema
- 3. Embedding model
- 4. Evaluation set (30 questions)
- 5. Threshold analysis
- 6. Parent-context expansion
- 7. Security
- 8. LLM configuration
- 9. Project structure
- 10. API
- Licence and disclaimer
e-hekim — Turkish Medical Semantic Search + RAG
An end-to-end system for semantic search and retrieval-augmented generation over a vector database built from health articles published by 14 Turkish hospitals.
Two modes are selectable from a single interface:
| Mode | API key | What it does |
|---|---|---|
| Semantic search | not required | Vectorizes the question and returns chunks ranked by cosine similarity. This mode alone is enough to evaluate the project without any credentials. |
| RAG | the user's own key | Passes the chunks that clear the threshold to an LLM and produces a Turkish answer with [1], [2] citations. |
The corpus and the user interface are Turkish, because the source articles are Turkish; this document is in English.
Two independent refusal layers
Preventing hallucination needs more than a similarity cut-off, so the system refuses
in two distinct places and reports which one fired via refusal_reason.
Layer 1 — retrieval gate (below_threshold). If the best-matching chunk scores
below the cosine threshold, our own code emits the refusal and the LLM is never
called at all. No prompt can talk the system out of this, because no prompt is
ever sent.
Bu sorunun cevabı belgelerimde bulunmamaktadır.("The answer to this question is not found in my documents.")
Layer 2 — model gate (model_insufficient_context). A similarity score cannot
tell whether a passage actually answers a question, only that it is on the same
topic. "What is Hodgkin lymphoma?" and "What is the five-year survival rate in
Hodgkin lymphoma?" retrieve the same chunk with a high score, yet only the first is
answerable from it. The model is therefore instructed — as the opening principle of
its system prompt — that it has no knowledge of its own for this task, and must
decline rather than fill the gap from its pretrained knowledge:
Bu bilgiyi bilmiyorum; bu konuda size yardımcı olamıyorum.("I do not know this information; I cannot help you with this.")
Partial answers, hedges such as "the documents do not say, but generally…", and adding even a single detail absent from the passages are all forbidden. Measured behaviour on the live system:
| Question | Best similarity | Outcome |
|---|---|---|
| "Bitcoin bugün kaç dolar?" | 0.4298 | Layer 1 — LLM never invoked |
| "Hodgkin lenfomada 5 yıllık sağkalım oranı yüzde kaç?" | 0.6153 | Layer 2 — passages passed, model declined |
| "Eritrositler nerede üretilir ve nerede yıkılır?" | 0.5931 | Answered, with citation |
Technology stack
| Layer | Choice | Note |
|---|---|---|
| Vector database | ChromaDB 1.5 (PersistentClient) |
Collection created with hnsw:space=cosine; distance = 1 − cosine. |
| Embeddings | magibu/embeddingmagibu-200m |
768 dimensions, 8,192-token context, L2-normalized output. |
| Backend | FastAPI + Uvicorn | Binds to 127.0.0.1 only. |
| Frontend | Dependency-free HTML/CSS/JS | Strict CSP; no inline script or style. |
| LLM access | OpenAI SDK | Every provider speaks the OpenAI wire format; only base_url changes. |
| Data | umutertugrul/turkish-hospital-medical-articles |
CC BY 4.0, ~25K articles, 14 hospitals. |
Supported models — DeepSeek (direct) and OpenRouter (multi-provider):
deepseek-v4-flash(default, thinking enabled),deepseek-v4-pro- Via OpenRouter:
anthropic/claude-haiku-4.5,openai/gpt-4.1-mini,google/gemini-2.5-flash,meta-llama/llama-3.3-70b-instruct
Quick start
Requirements: Python ≥ 3.11 and uv. A GPU is optional — everything runs on CPU, only the initial indexing is slower.
git clone https://huggingface.co/datasets/ErenYanic/e-hekim && cd e-hekim
uv venv && uv pip install -e ".[dev]"
cp .env.example .env # add HUGGINGFACE_TOKEN (the source dataset is gated)
uv run python scripts/ingest.py # ~5 min on GPU — 1,000 articles to 2,714 chunks
uv run python scripts/benchmark.py # threshold analysis (optional, writes a report)
uv run python -m ehekim.api # http://127.0.0.1:8000
Open http://127.0.0.1:8000. Semantic search works immediately. For RAG, paste
your own API key into the field in the interface.
Tests: uv run pytest -q (104 tests).
Note:
.envis used only by the offline scripts (downloading the source data and uploading to the Hub). The web application never reads an LLM provider key from the environment under any circumstances.
1. Article selection and chunking
Selection. 24,612 raw articles, then cleaning (empty bodies, texts shorter than
400 characters, non-http URLs, cookie/KVKK boilerplate, duplicate URLs and
byte-identical bodies), leaves 20,549 eligible articles, from which 1,000 are
selected.
Rather than mirroring the raw distribution, selection is balanced across the 14
hospitals (71–72 articles per source). In the raw data Acıbadem (6,071) and
Memorial (5,264) alone make up half the eligible pool; proportional sampling would
have handed half the index to two institutions' house style and topic choices. An
equal quota buys wider medical coverage for the same 1,000 documents, which is what
makes both the positive and the negative benchmark questions meaningful. Selection is
deterministic under seed=42.
Chunking strategy: paragraph-aware, token-bounded, with overlap (hybrid).
- Target 512 tokens, 64-token overlap, 32-token minimum.
- Paragraph integrity comes first: whole paragraphs are packed greedily until the token budget is exhausted.
- A paragraph that overflows the budget is split into sentences (Turkish
abbreviations such as
Dr.,vb.,mg.and initials such asM. Aliare not treated as sentence ends). - If a single sentence still overflows, it is split on a token window as a last resort.
Why this strategy? The corpus is hospital patient-education prose: short titled
sections ("Belirtileri nelerdir?", "Nasıl tedavi edilir?"). Paragraph boundaries are
genuine semantic boundaries, and blind N-token splitting routinely severs a symptom
list from the condition it belongs to. But paragraph lengths are wildly uneven — a
one-line introduction next to a 900-token procedure description — so splitting on
\n\n alone yields chunks that are both too small to stand alone and too large to be
precise. The hybrid approach avoids both failure modes.
A corpus-specific detail: only 35% of the articles contain blank lines (
\n\n); the rest separate paragraphs with a single\n(about 44 line breaks per article on average). The chunker therefore treats any run of newlines as a paragraph boundary. Had it looked for\n\nonly, two thirds of the corpus would have been processed as one enormous paragraph.
Result: 1,000 articles produce 2,714 chunks (2.71 per article). Tokens: mean 420, median 477, p95 534, max 586.
2. Vector database schema
data/ehekim_chunks.parquet — the required delivery schema plus auxiliary metadata:
| Column | Type | Description |
|---|---|---|
url |
string | Source link of the article the chunk belongs to |
chunk_text |
string | The chunked text |
chunk_vector |
list<float32>[768] | Embedding vector (L2-normalized) |
chunk_id |
string | {parent_id}-{index} |
parent_id |
string | Article identifier (first 16 hex of the URL's SHA-1), the parent-child link |
title |
string | Article title |
__source |
string | Source hospital (one of 14) |
chunk_index |
int | Position within the article |
token_count |
int | Token count of the chunk |
The same data is stored in ChromaDB in the ehekim_chunks collection in cosine space.
3. Embedding model
magibu/embeddingmagibu-200m — 768 dimensions, 8,192-token context, ~200M parameters.
Why it was chosen:
- Turkish-focused. Adapted from a multilingual teacher through tokenizer surgery
and offline distillation; its TR-MTEB average of 69.5 and STSbTR Spearman of 0.798
put it close to
ytu-ce-cosmos/turkish-e5-largeat a substantially smaller size. - Long context. 8,192 tokens is far more than 512-token chunks need, so moving to larger chunks later would not force a change of model.
- Size/quality balance. 768 dimensions give 2,714 × 768 float32 ≈ 8 MB, and the whole corpus vectorizes in about 4.5 minutes on a laptop GPU (GTX 1650).
- L2-normalized output. The dot product equals cosine similarity directly, so
Chroma's cosine distance is exactly
1 − similarity.
⚠️ The model is asymmetric. Queries and documents must be encoded with different prefixes:
task: search result | query:andtitle: <title> | text:. The wrong prefix silently depresses similarities and invalidates the threshold calibration. All encoding therefore goes through a single class (ehekim.embedding.Embedder), and a test asserts that the string we build is byte-identical to the model's own registered prompts. The article title is written into the document prefix with its real value.
4. Evaluation set (30 questions)
The repository ships two viewable tables, selectable in the dataset viewer:
| Config | Split | Rows | Contents |
|---|---|---|---|
chunks (default) |
train |
2,714 | The vector database: url, chunk_text, chunk_vector + metadata |
benchmark |
test |
30 | The evaluation set with its measured outcomes |
from datasets import load_dataset
chunks = load_dataset("ErenYanic/e-hekim", "chunks", split="train")
tests = load_dataset("ErenYanic/e-hekim", "benchmark", split="test")
The benchmark table holds 20 positive questions, each written by reading an actual indexed chunk and paired with the URL of the article that answers it, and 10 negative questions whose answers are certainly absent from the corpus (software, sport, finance, history, space, automotive, veterinary medicine). Columns:
| Column | Description |
|---|---|
id, label |
P01–P20 / N01–N10; positive or negative |
question |
The question put to the system |
topic, expected_answer, expected_url |
Ground truth for positives |
rationale |
Why a negative is out of scope |
best_similarity |
Highest cosine similarity actually retrieved |
expected_source_rank |
Rank at which the expected article was retrieved |
top_match_title, top_match_url |
What the retriever returned first |
system_decision, expected_decision, correct |
Answer/refuse outcome at the 0.53 threshold |
Result: 30/30 correct — all 20 positives answered, all 10 negatives refused.
5. Threshold analysis
scripts/benchmark.py runs that 30-question set through the real retrieval path and
sweeps the threshold from 0.20 to 0.90, regenerating both the report and the benchmark
table above. Full report: data/threshold_report.md.
Separation is decisive:
| Group | Mean | Min | Max |
|---|---|---|---|
| Positive (20) | 0.7376 | 0.5819 | 0.8784 |
| Negative (10) | 0.2749 | 0.1615 | 0.4777 |
There is a 0.1042 gap between the lowest positive and the highest negative, so
every threshold in [0.50, 0.58] separates the two sets perfectly (F1 = 1.000,
accuracy = 1.000, zero false answers on negatives).
Chosen threshold: 0.53 — the midpoint of that plateau. Picking either edge would
leave the system on a cliff: at 0.50 the highest negative (the Bitcoin question,
0.4777) is only 0.02 away, and at 0.58 the lowest positive (pharyngeal cancer, 0.5819)
is a mere 0.002 away. The midpoint maximizes the margin against both failure modes.
| Threshold | Positives answered | False answers on negatives | F1 |
|---|---|---|---|
| 0.30 | 20/20 | 2/10 | 0.952 |
| 0.45 | 20/20 | 1/10 | 0.976 |
| 0.53 | 20/20 | 0/10 | 1.000 |
| 0.65 | 17/20 | 0/10 | 0.919 |
| 0.80 | 5/20 | 0/10 | 0.333 |
Source recall: the expected article appears in the top 5 for 20/20 questions, and ranks first for 15/20.
An honest caveat. This measurement is at the article (URL) level. Retrieving the right article does not guarantee retrieving the chunk that carries the answer, and the distinction bites in practice, which is what motivated the next section.
6. Parent-context expansion
Chunking necessarily cuts articles at arbitrary points, and the highest-scoring chunk is not always the one holding the answer sentence. Observed case: for "Eritrositler nerede üretilir ve nerede yıkılır?", chunk 1 of the RBC article scores 0.5931 (it discusses low counts) while chunk 0 — which states verbatim that erythrocytes are produced in red bone marrow and broken down in the spleen — scores 0.5176 and falls below the threshold. Given only the passing chunk, the model correctly refused a question the corpus genuinely answers.
So once the threshold gate has decided the query is in scope, each passing chunk
brings its immediate siblings (chunk_index ± 1, via parent_id) along as context.
- The gate is not weakened: expansion happens strictly after it and only around chunks that already cleared it, so it can never turn an out-of-scope question into an answered one.
- The cosine values shown in the interface remain the real, unexpanded scores.
- The numbering given to the model and the list rendered in the interface are
identical, and siblings added purely for context are marked
—("komşu bölüm"), so a[1]citation always points at the[1]the user can see.
7. Security
Because the user types an API key into the browser, credential handling is the central design constraint of the project:
- The server never stores a key. It arrives in the
X-Provider-Keyheader (not the URL — Uvicorn's access log records paths, so a key in a query string would leak into our own logs), is used for exactly one call, and then goes out of scope. - No persistence in the browser. No
localStorage,sessionStorage, cookie or URL is used; the key lives only in the input value and for the duration of a singlefetch. Reloading the page discards it. - Structural validation. Before a key is placed in an
Authorizationheader it is checked to be a single line of printable ASCII, which stops CRLF header injection at the door. - Log and error sanitization. Providers echo the submitted key back in 401 bodies
(DeepSeek does). Every log record passes through a scrubbing filter, and every error
relayed to the client passes through the same scrubber, which replaces
credential-shaped substrings with
[REDACTED]. - Response models cannot carry a key. No Pydantic model has such a field, and tests assert the key never appears in a response body.
- No CORS, bound to
127.0.0.1, strict CSP (default-src 'self', no inline script or style),nosniff,frame-ancestors 'none',Cache-Control: no-storeon API responses, and a 64 KB request-body cap. - Prompt injection. Retrieved text is fenced inside a
<belgeler>element and declared untrusted in the system prompt; the model is told to execute no instruction found inside it. - Upload protection.
scripts/push_to_hub.pyworks from an explicit allow-list, then applies a deny-list and a secret scan; on any finding it aborts before sending a single byte, and after uploading it re-lists the remote repository to verify both that nothing sensitive leaked and that every expected file arrived.
8. LLM configuration
client.chat.completions.create(
model="deepseek-v4-flash",
messages=...,
reasoning_effort="medium", # as specified in the brief
extra_body={"thinking": {"type": "enabled"}}, # thinking enabled
)
DeepSeek's documentation defines
low | high | maxforreasoning_effortand, for compatibility, mapsmediumontohigh. The requested value (medium) is sent verbatim; this provider-side mapping is recorded here rather than silently worked around.
OpenRouter models are called with plain completions (no thinking parameters).
9. Project structure
src/ehekim/
config.py Settings, prompts, threshold and refusal constants (holds no secrets)
chunking.py Paragraph-aware, token-bounded, overlapping chunker
corpus.py Article cleaning, balanced selection, chunk records
embedding.py SentenceTransformer wrapper with the asymmetric prompts
vectorstore.py ChromaDB (cosine) plus sibling-chunk access
retrieval.py Threshold gate, context expansion, RAG prompt, refusal detection
llm.py Provider catalogue, OpenAI SDK call, error normalization
security.py Key validation and credential scrubbing
api.py FastAPI application, security headers, endpoints
scripts/ ingest.py, benchmark.py, push_to_hub.py
frontend/ index.html, app.js, styles.css (no dependencies)
tests/ 104 tests — security, chunking, selection, retrieval, HTTP
data/ benchmark_questions.json, threshold_report.md,
benchmark_results.json, ingest_manifest.json, *.parquet
10. API
| Endpoint | Key | Description |
|---|---|---|
GET /api/health |
— | Readiness and chunk count |
GET /api/config |
— | Threshold/top-k defaults, provider catalogue, refusal messages |
POST /api/search |
no | Semantic search; chunks with their cosine values |
POST /api/ask |
X-Provider-Key |
RAG; refuses below the threshold without calling the model |
GET /api/docs |
— | OpenAPI interface |
curl -X POST http://127.0.0.1:8000/api/search \
-H 'Content-Type: application/json' \
-d '{"query":"Hodgkin lenfomayı ayıran hücre tipi nedir?","top_k":3,"threshold":0.53}'
Licence and disclaimer
The code is MIT. The source data is CC BY 4.0 (umutertugrul/turkish-hospital-medical-articles). This system is for information only; it is not medical diagnosis, treatment or prescribing advice.
- Downloads last month
- 28