Skip to content

Commit 19ac52a

Browse files
committed
examples and applications
1 parent 7b7d434 commit 19ac52a

7 files changed

Lines changed: 20227 additions & 0 deletions

File tree

examples_and_applications/__init__.py

Whitespace-only changes.

examples_and_applications/healthcare_conversation_rag/__init__.py

Whitespace-only changes.
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
from datasets import load_dataset
2+
from datetime import date
3+
4+
# ── config ────────────────────────────────────────────────────────────────────
5+
REPO_ID = "pavanmantha/doctor_patient_conversation"
6+
COLLECTION = "doctor_patient_conversation"
7+
OUTPUT_FILE = "data_sets/source_data.qql"
8+
TODAY = date.today().isoformat() # e.g. 2026-05-16
9+
BATCH_SIZE = 200 # rows per INSERT block (stays under 33MB)
10+
# ─────────────────────────────────────────────────────────────────────────────
11+
12+
13+
def escape(text: str) -> str:
14+
"""Escape single-quotes inside field values."""
15+
return text.replace("\\", "\\\\").replace("'", "\\'")
16+
17+
18+
def build_record(row: dict) -> str:
19+
description = escape((row.get("description") or "").strip())
20+
text = escape((row.get("conversation") or "").strip())
21+
status = escape((row.get("status") or "").strip())
22+
23+
return (
24+
" {\n"
25+
f" 'description': '{description}',\n"
26+
f" 'text': '{text}',\n"
27+
f" 'status': '{status}'\n"
28+
" }"
29+
)
30+
31+
32+
def write_batch(f, batch: list, batch_num: int, collection: str):
33+
f.write(f"\n-- Batch {batch_num} ({len(batch)} records)\n")
34+
f.write(f"INSERT BULK INTO COLLECTION {collection} VALUES [\n")
35+
for i, record in enumerate(batch):
36+
is_last = (i == len(batch) - 1)
37+
f.write(record)
38+
f.write("\n" if is_last else ",\n")
39+
f.write("]\n")
40+
41+
42+
def main():
43+
print(f"Loading dataset from '{REPO_ID}' ...")
44+
ds = load_dataset(REPO_ID, split="train")
45+
total = len(ds)
46+
num_batches = (total + BATCH_SIZE - 1) // BATCH_SIZE
47+
print(f" -> {total} rows loaded")
48+
print(f" -> {BATCH_SIZE} rows per INSERT block")
49+
print(f" -> {num_batches} total batches\n")
50+
51+
header = f"""\
52+
-- Qdrant Query Language
53+
-- BULK INSERT -- DOCTOR PATIENT CONVERSATION (BATCHED)
54+
55+
-- ============================================================
56+
-- QQL -- Doctor Patient Conversation
57+
-- Collection : {COLLECTION}
58+
-- Source : {REPO_ID}
59+
-- Total rows : {total}
60+
-- Batch size : {BATCH_SIZE}
61+
-- Generated : {TODAY}
62+
-- ============================================================
63+
64+
-- Step 0: Show Collections
65+
SHOW COLLECTIONS
66+
67+
-- Step 1: Create the collection
68+
CREATE COLLECTION {COLLECTION}
69+
70+
-- ============================================================
71+
-- BULK INSERT -- BATCHED (each block <= {BATCH_SIZE} records)
72+
-- ============================================================
73+
"""
74+
75+
print(f"Writing {OUTPUT_FILE} ...")
76+
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
77+
f.write(header)
78+
79+
batch = []
80+
batch_num = 1
81+
82+
for i, row in enumerate(ds):
83+
batch.append(build_record(row))
84+
85+
if len(batch) == BATCH_SIZE:
86+
write_batch(f, batch, batch_num, COLLECTION)
87+
print(f" batch {batch_num} written ({i + 1}/{total} rows)")
88+
batch = []
89+
batch_num += 1
90+
91+
# flush remaining rows
92+
if batch:
93+
write_batch(f, batch, batch_num, COLLECTION)
94+
print(f" batch {batch_num} written ({total}/{total} rows)")
95+
96+
print(f"\nDone. '{OUTPUT_FILE}' written -- {total} records across {batch_num} INSERT blocks.")
97+
98+
99+
if __name__ == "__main__":
100+
main()

examples_and_applications/healthcare_conversation_rag/data_sets/ground_truth.jsonl

Lines changed: 30 additions & 0 deletions
Large diffs are not rendered by default.

examples_and_applications/healthcare_conversation_rag/data_sets/source_data.qql

Lines changed: 20039 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from agno.agent import Agent
2+
from agno.models.ollama import Ollama
3+
from qql import Connection
4+
5+
def search_medical_records(question: str) -> str:
6+
"""
7+
Use this function when you need to retrieve relevant medical context
8+
for a single natural language question from the 'medical_records'
9+
collection stored in Qdrant via QQL.
10+
11+
This function performs a semantic similarity search against the
12+
collection and aggregates the top matching document texts into a
13+
single context string, which can then be passed to an LLM or used
14+
for further processing (e.g. RAG pipelines, answer generation).
15+
16+
Args:
17+
question (str): A single medical question in natural language.
18+
19+
Returns:
20+
str: Aggregated context text from the top matching records.
21+
Returns an empty string if no results are found or an
22+
error occurs.
23+
"""
24+
LIMIT = 5
25+
CONTEXT = ""
26+
27+
try:
28+
with Connection(url="http://localhost:6333", secret="th3s3cr3tk3y") as conn:
29+
query = f"SEARCH medical_records SIMILAR TO '{question}' LIMIT {LIMIT} WITH {{ hnsw_ef: 128, mmr_diversity: 0.5, mmr_candidates: 50}}"
30+
result = conn.run_query(query=query)
31+
for hit in result.data:
32+
CONTEXT += hit["payload"]["text"]
33+
except Exception as e:
34+
print(f"Search failed for question: '{question}' | Error: {e}")
35+
36+
return CONTEXT
37+
38+
agent = Agent(
39+
tools=[search_medical_records],
40+
model=Ollama(id="qwen3.5:latest", host="http://localhost:11434", timeout=300),
41+
markdown=True,
42+
debug_mode=True,
43+
reasoning=True,
44+
enable_agentic_memory=True
45+
)
46+
agent.print_response("hi doctor I am just wondering what is abutting and abutment of the nerve root means in a back issue please explain what treatment is required for annular bulging and tear", stream=True)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
[project]
2+
name = "qql-application"
3+
version = "0.1.0"
4+
description = "QQL and its application"
5+
requires-python = ">=3.13"
6+
dependencies = [
7+
"qql-cli>=2.4.1",
8+
"datasets>=4.8.5",
9+
"agno>=2.6.7",
10+
"ollama>=0.6.2",
11+
"openai>=2.37.0"
12+
]

0 commit comments

Comments
 (0)