Notebooks
F
Fireworks AI
[External] Healthcare Generation With Reasoning Mode DeepSeek (V3 & R1)

[External] Healthcare Generation With Reasoning Mode DeepSeek (V3 & R1)

fireworks-aifireworks-cookbookarchivedlearntutorialsmachine-learningjupyter-notebooksfunction-callingai-workflowsintegrationsproduction-examplesgenerative-aiagentic-systemsragstructured_response

Open in Colab

Introduction to Structured Responses for Healthcare Data

This script demonstrates how to use structured responses with DeepSeek Models (V3 and R1) on Fireworks AI to generate reliable and structured healthcare data.

Why Use Structured Responses?

  • Predictability: Enforces medical data constraints to ensure logical outputs.
  • Automation: Structured outputs can be used for patient record generation, automated reports, and clinical decision support.
  • Integration: JSON and Grammar Mode allow seamless integration into electronic health record (EHR) systems and research databases.

What You'll Learn

  1. Basic API Setup: Connecting to Fireworks AI and using DeepSeek v3 and R1.
  2. Grammar Mode: Generating structured healthcare data within predefined constraints.
  3. JSON Mode: Ensuring machine-readable structured responses.
  4. Reasoning JSON Mode: Capturing the model's thought process alongside structured responses.

Setup

Install all the dependencies and import the required python modules.

[19]

Setup your API Key

In order to use the DeepSeek models, you must first obtain Fireworks API Keys. If you don't already have one, create a Fireworks AI account. Under Account Settings, click on API Keys to create one.

[20]

0️⃣ Basic API Call to DeepSeek v3

Chat Completions API

This is a simple test call to ensure the Fireworks API is working correctly.

[21]
The field of AI in healthcare is rapidly evolving, with numerous advancements that are transforming diagnosis, treatment, patient care, and administrative processes. Here are some of the latest advancements as of 2023:

---

### 1. **AI in Medical Imaging and Diagnostics**
   - **Improved Accuracy in Radiology**: AI algorithms are now being integrated into radiology workflows, enhancing the detection of diseases like cancer, fractures, and neurological disorders (e.g., Alzheimer’s) in X-rays, MRIs, and CT scans.
   - **Point-of-Care Ultrasound (POCUS)**: AI-powered portable ultrasound devices are enabling faster and more accurate diagnoses in emergency settings.
   - **Ophthalmology**: AI systems like Google's DeepMind are being used to detect diabetic retinopathy and macular degeneration from retinal scans.

---

### 2. **Generative AI in Drug Discovery**
   - **Accelerating Drug Development**: AI models like AlphaFold by DeepMind and others are predicting protein structures, speeding up drug discovery and reducing costs.
   - **Generative AI for Molecule Design**: Tools like OpenAI’s GPT-4 and specialized models are being used to generate novel drug compounds and optimize existing ones.

---

### 3. **AI in Personalized Medicine**
   - **Genomics and AI**: AI is being used to analyze genomic data to identify disease risks and tailor treatments based on an individual’s genetic makeup.
   - **Predictive Analytics**: Machine learning models are predicting patient outcomes and recommending personalized treatment plans.

---

### 4. **AI in Remote Patient Monitoring**
   - **Wearable Devices**: AI-powered wearables (e.g., Apple Watch, Fitbit) are monitoring vital signs like heart rate, blood oxygen levels, and sleep patterns, enabling early detection of health issues.
   - **Chronic Disease Management**: AI systems are helping manage chronic conditions like diabetes by analyzing continuous glucose monitoring data and providing real-time recommendations.

---

### 5. **Natural Language Processing (NLP) in Healthcare**
   - **Clinical Documentation**: NLP tools are automating medical transcription, reducing the burden on clinicians and improving accuracy.
   - **Patient Interaction**: AI chatbots and virtual assistants are being used for triage, symptom checking, and patient engagement.

---

### 6. **AI in Surgery**
   - **Robotic-Assisted Surgery**: AI-powered surgical robots are improving precision and outcomes in minimally invasive procedures.
   - **Preoperative Planning**: AI algorithms are analyzing patient data to predict surgical risks and optimize surgical plans.

---

### 7. **AI for Mental Health**
   - **Early Detection**: AI models are analyzing speech, text, and behavioral data to detect signs of mental health conditions like depression and anxiety.
   - **Therapeutic Tools**: AI-powered apps are providing cognitive behavioral therapy (CBT) and other mental health interventions.

---

### 8. **AI in Healthcare Administration**
   - **Automating Billing and Coding**: AI is streamlining revenue cycle management by reducing errors and speeding up claims processing.
   - **Resource Optimization**: AI is being used to predict patient admissions, optimize staff schedules, and manage hospital resources more efficiently.

---

### 9. **AI in Public Health**
   - **Disease Outbreak Prediction**: AI models are analyzing data from various sources to predict and track disease outbreaks, such as COVID-19 or influenza.
   - **Vaccine Development**: AI is accelerating the development of vaccines by predicting antigenic targets and optimizing trial designs.

---

### 10. **Ethical AI and Explainability**
   - **Bias Mitigation**: Efforts are being made to ensure AI models are fair and unbiased, especially in diverse patient populations.
   - **Explainable AI (XAI)**: Researchers are developing methods to make AI decision-making processes more transparent and understandable to clinicians.

---

### 11. **AI in Emergency Medicine**
   - **Stroke Detection**: AI algorithms are being used to rapidly detect strokes from CT scans, enabling faster treatment.
   - **Trauma Triage**: AI systems are helping prioritize patients in emergency rooms based on severity.

---

### 12. **AI in Rare Disease Diagnosis**
   - **Symptom Analysis**: AI tools are helping diagnose rare diseases by analyzing patient symptoms and medical history.
   - **Patient Matching**: AI is connecting patients with rare diseases to clinical trials and specialized care.

---

These advancements are not without challenges, including regulatory hurdles, data privacy concerns, and the need for robust validation. However, the potential for AI to revolutionize healthcare remains immense, promising improved outcomes, reduced costs, and enhanced access to care.

1️⃣ Grammar Mode with BNF for Healthcare Data

What is Grammar Mode?

Grammar Mode ensures that the model outputs responses that conform to a strict structure, preventing unexpected variations in responses. This is particularly useful for generating structured data, such as medical records.

How Grammar Mode Works

  • Uses a GBNF (Grammar-Based Normal Form) to constrain the model's output.
  • Ensures the output adheres to predefined rules for valid healthcare data.

Read more about GBNF, and how to use it.

[22]
[23]
[24]
🔹 Grammar Mode Output: Patient Name: John Doe Age: 40 Gender: Male Diagnosis: Hypertension Treatment: Lifestyle Changes Medications: Lisinopril Notes: Patient shows good adherence to treatment.

2️⃣ JSON Mode for Healthcare Data

JSON mode is a subset of grammar mode and is a feature that allows you to specify a JSON schema to force a language model to respond in a structured JSON format. This has several benefits:

  • Clarity and precision in responses
  • Easy parsing and processing of output
  • Improved integration with healthcare systems
  • Standardized format for consistent data handling
[25]
[26]
[27]
{"name":"Anupriya Ashokan","age":45,"gender":"Female","diagnosis":"Type 2 Diabetes Mellitus","treatment":"Metformin 500 mg twice daily, lifestyle modifications","medications": "Metformin 500 mg twice daily, Lisinopril 10 mg once daily, Atorvastatin 20 mg once daily","notes":"Patient advised to monitor blood glucose levels regularly and follow a diabetic diet. Scheduled for follow-up in 3 months."}

3️⃣ Reasoning Model JSON Mode for Computer Specifications

3️⃣ Reasoning Model JSON Mode for Healthcare Data

🧠 Reasoning Model JSON Mode for Healthcare Data

🔹 What is Reasoning JSON Mode?

Reasoning JSON Mode extends structured JSON generation by adding an explanation of the model’s decision-making process. This is done by generating a reasoning section enclosed within <think>...</think> tags, followed by a structured JSON response.

This approach enhances transparency and interpretability by providing insight into why the model made certain clinical recommendations.

🔹 Why Use Reasoning JSON Mode for Healthcare Data?

For tasks like clinical documentation, medical decision support, or patient record validation, Reasoning JSON Mode provides:

  • ✅ Explainability → Understand why certain diagnoses and treatments were selected.
  • ✅ Debugging Capability → Identify potential inconsistencies in AI-generated medical recommendations.
  • ✅ Structured Data → JSON output is ready for integration into healthcare databases.
[28]
[29]
show response content <think>
Okay, I need to generate a structured healthcare record for a patient with hypertension, including the reasoning behind each section. Let me start by recalling the typical components of a medical record. There's usually patient demographics, chief complaint, history of present illness, past medical history, etc. 

First, I'll outline the basic structure. The user gave an example that starts with Patient Demographics, so maybe follow that example. I need to make sure each section is clear and comprehensive. 

For each section, I need to include the necessary details and then the reasoning. For instance, under Chief Complaint, the patient would mention symptoms like headache or fatigue. The reasoning would explain why those symptoms are relevant to hypertension.

In the History of Present Illness, I should include the onset, duration, and progression of symptoms. Maybe the patient noticed symptoms a few weeks ago and they've been getting worse. Also, triggers like stress or diet. The reasoning here connects those triggers to hypertension.

Past Medical History: Existing conditions like obesity or diabetes. Medications like NSAIDs that can affect blood pressure. Family history is important because hypertension can be hereditary. The reasoning here emphasizes risk factors and family history.

Social History: Smoking, alcohol, diet, exercise. These lifestyle factors contribute to hypertension. Reasoning would link these habits to increased BP.

Physical Exam: Vital signs including BP readings, maybe elevated BMI. Other findings like retinal changes. Reasoning explains how these physical signs relate to hypertension.

Diagnostic Tests: Lab tests like CBC, lipid panel, urine analysis. Imaging like echocardiogram. Reasoning justifies each test to check for organ damage or underlying causes.

Assessment: The diagnosis of primary hypertension, staging based on guidelines like ACC/AHA. Reasoning here would mention ruling out secondary causes and confirming primary hypertension.

Plan: Lifestyle modifications, medications (like ACE inhibitors or diuretics), follow-up plans. Comorbidities management like statins for high cholesterol. Reasoning for each part of the treatment plan.

Education and Counseling: Diet advice, exercise, medication adherence. Reasoning ties these to effective hypertension management.

Prognosis: Good if adherent to treatment. Reasoning based on risks of complications if uncontrolled.

Conclusion: Summarizing the approach. References to guidelines for credibility.

Wait, I need to make sure each section is properly separated, with clear headings for the Record and the Reasoning. Let me check the example to ensure alignment. Maybe use headings like "Healthcare Record" with subheadings, then a "Clinical Reasoning" section with corresponding points.

Also, terminology should be accurate. Use terms like "Stage 2 Hypertension" based on current guidelines. Medications should be appropriate first-line treatments. Avoid errors like wrong drug classes.

Maybe the patient is on lisinopril as an ACE inhibitor. Confirm that's a standard choice. Lifestyle changes: DASH diet, sodium reduction. Ensure recommendations align with standard practices.

For diagnostic tests, include basics like electrolytes, kidney function, lipid profile. Echocardiogram if suspecting heart involvement. Urinalysis for proteinuria.

Under Assessment, don't forget to mention exclusion of secondary hypertension, which requires different tests.

Prognosis should mention potential complications like stroke or kidney disease if untreated.

Let me structure this step by step, first drafting the healthcare record with all sections, then the reasoning for each part. Make sure reasoning is concise but explains the clinical rationale.

Check for consistency: if the patient has a family history, the reasoning links that to primary hypertension. Physical exam findings like retinal changes support chronic hypertension.

I think that covers most aspects. Now, organize it properly under each heading, ensure flow, and validate the medical content for accuracy.
</think>
{"name": "Jane Doe", "age": 55, "gender": "Female", "diagnosis": "Hypertension (Primary, Stage 2)", "treatment": "Lifestyle modifications, Lisinopril 10 mg daily, Scheduled follow-up in 4 weeks", "medications": "Lisinopril, Atorvastatin" ,"notes": "Requires monitoring for medication adherence and potential side effects like hyperkalemia."}
Reasoning:
Okay, I need to generate a structured healthcare record for a patient with hypertension, including the reasoning behind each section. Let me start by recalling the typical components of a medical record. There's usually patient demographics, chief complaint, history of present illness, past medical history, etc. 

First, I'll outline the basic structure. The user gave an example that starts with Patient Demographics, so maybe follow that example. I need to make sure each section is clear and comprehensive. 

For each section, I need to include the necessary details and then the reasoning. For instance, under Chief Complaint, the patient would mention symptoms like headache or fatigue. The reasoning would explain why those symptoms are relevant to hypertension.

In the History of Present Illness, I should include the onset, duration, and progression of symptoms. Maybe the patient noticed symptoms a few weeks ago and they've been getting worse. Also, triggers like stress or diet. The reasoning here connects those triggers to hypertension.

Past Medical History: Existing conditions like obesity or diabetes. Medications like NSAIDs that can affect blood pressure. Family history is important because hypertension can be hereditary. The reasoning here emphasizes risk factors and family history.

Social History: Smoking, alcohol, diet, exercise. These lifestyle factors contribute to hypertension. Reasoning would link these habits to increased BP.

Physical Exam: Vital signs including BP readings, maybe elevated BMI. Other findings like retinal changes. Reasoning explains how these physical signs relate to hypertension.

Diagnostic Tests: Lab tests like CBC, lipid panel, urine analysis. Imaging like echocardiogram. Reasoning justifies each test to check for organ damage or underlying causes.

Assessment: The diagnosis of primary hypertension, staging based on guidelines like ACC/AHA. Reasoning here would mention ruling out secondary causes and confirming primary hypertension.

Plan: Lifestyle modifications, medications (like ACE inhibitors or diuretics), follow-up plans. Comorbidities management like statins for high cholesterol. Reasoning for each part of the treatment plan.

Education and Counseling: Diet advice, exercise, medication adherence. Reasoning ties these to effective hypertension management.

Prognosis: Good if adherent to treatment. Reasoning based on risks of complications if uncontrolled.

Conclusion: Summarizing the approach. References to guidelines for credibility.

Wait, I need to make sure each section is properly separated, with clear headings for the Record and the Reasoning. Let me check the example to ensure alignment. Maybe use headings like "Healthcare Record" with subheadings, then a "Clinical Reasoning" section with corresponding points.

Also, terminology should be accurate. Use terms like "Stage 2 Hypertension" based on current guidelines. Medications should be appropriate first-line treatments. Avoid errors like wrong drug classes.

Maybe the patient is on lisinopril as an ACE inhibitor. Confirm that's a standard choice. Lifestyle changes: DASH diet, sodium reduction. Ensure recommendations align with standard practices.

For diagnostic tests, include basics like electrolytes, kidney function, lipid profile. Echocardiogram if suspecting heart involvement. Urinalysis for proteinuria.

Under Assessment, don't forget to mention exclusion of secondary hypertension, which requires different tests.

Prognosis should mention potential complications like stroke or kidney disease if untreated.

Let me structure this step by step, first drafting the healthcare record with all sections, then the reasoning for each part. Make sure reasoning is concise but explains the clinical rationale.

Check for consistency: if the patient has a family history, the reasoning links that to primary hypertension. Physical exam findings like retinal changes support chronic hypertension.

I think that covers most aspects. Now, organize it properly under each heading, ensure flow, and validate the medical content for accuracy.

Patient Record (JSON Data):
{
    "name": "Jane Doe",
    "age": 55,
    "gender": "Female",
    "diagnosis": "Hypertension (Primary, Stage 2)",
    "treatment": "Lifestyle modifications, Lisinopril 10 mg daily, Scheduled follow-up in 4 weeks",
    "medications": "Lisinopril, Atorvastatin",
    "notes": "Requires monitoring for medication adherence and potential side effects like hyperkalemia."
}

Conclusion

To learn more, visit Fireworks AI Docs or join our Discord community.