Урок 2: Реальный промпт
Урок 2: Реальный промпт
На предыдущем уроке мы обсудили несколько ключевых советов по составлению промптов и увидели примеры их использования по отдельности. Теперь давайте попробуем написать гораздо более обширный промпт, который включает в себя многие из только что рассмотренных нами методов.
Наша цель при составлении промпта
Этот урок будет посвящен написанию промпта для суммаризатора медицинских карт, который принимает длинные медицинские записи и генерирует краткое изложение, содержащее важную информацию для помощи врачам в подготовке к предстоящим приемам.
Каждая медицинская карта пациента выглядит примерно так:
Patient Name: Evelyn Thompson
Age: 78
Medical Record:
1985: Diagnosed with type 2 diabetes, started on metformin
1992: Developed hypertension, prescribed lisinopril
1998: Total hip replacement (right) due to osteoarthritis
2000: Diagnosed with hypothyroidism, started on levothyroxine
2003: Cataract surgery (both eyes)
2005: Admitted for atrial fibrillation, started on warfarin
2008: Vitamin B12 deficiency diagnosed, monthly injections started
2010: Increased metformin dose due to rising A1C levels
2011: Admitted for transient ischemic attack, added aspirin to regimen
2013: Diagnosed with stage 2 breast cancer, underwent lumpectomy and radiation
2014: Started on anastrozole for breast cancer recurrence prevention
2015: Developed chronic kidney disease (CKD) stage 3, metformin adjusted
2017: Total knee replacement (left) due to osteoarthritis
2018: Hospitalized for pneumonia, treated with IV antibiotics
2019: Mild cognitive impairment noted, started donepezil
2020: Lisinopril dosage increased due to refractory hypertension
2021: Recurrent UTIs, prescribed low-dose prophylactic antibiotics
2022: Annual mammogram clear, but eGFR shows worsening kidney function
2023: Mobility declining, started physical therapy and home health aide visits
Наша конечная цель — генерировать единообразные сводки записей, чтобы помочь поставщикам услуг подготовиться к предстоящим приемам. Каждая сводка должна содержать ключевые фрагменты информации, включая:
- Имя пациента
- Возраст пациента
- Ключевые диагнозы
- Список прописанных пациенту лекарств
- Недавние проблемы
- Пункты действий для поставщика услуг
Пример вывода для вышеуказанной медицинской записи может выглядеть примерно так:
Name: Evelyn Thompson
Age: 78
Key Diagnoses:
- Type 2 Diabetes (1985)
- Hypertension (1992)
- Osteoarthritis (Hip and Knee Replacements in 1998 and 2017)
- Hypothyroidism (2000)
- Atrial Fibrillation (2005)
- Vitamin B12 Deficiency (2008)
- Transient Ischemic Attack (TIA) (2011)
- Breast Cancer (2013)
- Chronic Kidney Disease (CKD) Stage 3 (2015)
- Pneumonia (2018)
- Mild Cognitive Impairment (2019)
- Recurrent Urinary Tract Infections (UTIs) (2021)
Medications:
- Metformin (Diabetes)
- Lisinopril (Hypertension)
- Levothyroxine (Hypothyroidism)
- Warfarin (Atrial Fibrillation)
- Aspirin (Antiplatelet)
- Anastrozole (Breast Cancer Recurrence Prevention)
- Donepezil (Cognitive Impairment)
- Low-dose Prophylactic Antibiotics (Recurrent UTIs)
Other Treatments:
- Total Hip Replacement (1998)
- Cataract Surgery (2003)
- Vitamin B12 Injections (2008)
- Lumpectomy and Radiation (Breast Cancer, 2013)
- Total Knee Replacement (2017)
- Physical Therapy and Home Health Aide (2023)
Recent Concerns:
- Worsening Kidney Function (eGFR Decline in 2022)
- Declining Mobility (2023)
Action Items:
- Monitor Kidney Function and Adjust Medications as Needed
- Continue Physical Therapy and Home Health Support
- Evaluate for Cognitive Decline and Adjust Treatment Plan
- Address Mobility Issues and Fall Risk
- Ensure Adherence to Recommended Cancer Screening
Вот список Python, содержащий 5 медицинских записей, с которыми мы будем пробовать наш prompt:
patient_records = [
"""
Patient Name: Evelyn Thompson
Age: 78
Medical Record:
1985: Diagnosed with type 2 diabetes, started on metformin
1992: Developed hypertension, prescribed lisinopril
1998: Total hip replacement (right) due to osteoarthritis
2000: Diagnosed with hypothyroidism, started on levothyroxine
2003: Cataract surgery (both eyes)
2005: Admitted for atrial fibrillation, started on warfarin
2008: Vitamin B12 deficiency diagnosed, monthly injections started
2010: Increased metformin dose due to rising A1C levels
2011: Admitted for transient ischemic attack (TIA), added aspirin to regimen
2013: Diagnosed with stage 2 breast cancer, underwent lumpectomy and radiation
2014: Started on anastrozole for breast cancer recurrence prevention
2015: Developed chronic kidney disease (CKD) stage 3, metformin adjusted
2017: Total knee replacement (left) due to osteoarthritis
2018: Hospitalized for pneumonia, treated with IV antibiotics
2019: Mild cognitive impairment noted, started on donepezil
2020: Lisinopril dosage increased due to refractory hypertension
2021: Recurrent UTIs, prescribed low-dose prophylactic antibiotics
2022: Annual mammogram clear, but eGFR shows worsening kidney function
2023: Mobility declining, started physical therapy and home health aide visits
""",
"""
Patient Name: Marcus Reyes
Age: 42
Medical Record:
2001: Diagnosed with generalized anxiety disorder (GAD), started on paroxetine
2003: Diagnosed with major depressive disorder (MDD), added bupropion
2005: Hospitalized for suicidal ideation, added cognitive behavioral therapy (CBT)
2007: Diagnosed with attention-deficit/hyperactivity disorder (ADHD), started on methylphenidate
2009: Reported side effects from paroxetine, switched to escitalopram
2012: Diagnosed with obstructive sleep apnea (OSA), started CPAP therapy
2014: Diagnosed with hypertension, started on losartan
2015: Weight gain noted, referred to nutritionist
2016: Diagnosed with type 2 diabetes, started on metformin
2017: Hospitalized for diabetic ketoacidosis (DKA), insulin therapy initiated
2018: Reported nightmares, switched from bupropion to venlafaxine
2019: Gastroesophageal reflux disease (GERD) diagnosis, started on omeprazole
2020: Divorce, increased therapy sessions, added dialectical behavior therapy (DBT)
2021: Developed plantar fasciitis, prescribed orthotics and physical therapy
2022: Admitted for panic attack, mistaken for myocardial infarction, cardiac workup negative
2023: Attempted suicide, inpatient psychiatric treatment for 30 days
2023: Post-discharge, started on new antipsychotic (quetiapine) and mood stabilizer (lamotrigine)
2024: Reports improvement in mood and sleep, weight loss noted
2024: A1C levels improved, insulin dose decreased
""",
"""
Patient Name: Lily Chen
Age: 8
Medical Record:
2016 (Birth): Born at 34 weeks, diagnosed with Tetralogy of Fallot (TOF)
- Immediate surgery to place a shunt for increased pulmonary blood flow
2016 (3 months): Echocardiogram showed worsening right ventricular hypertrophy
2017 (8 months): Complete repair of TOF (VSD closure, pulmonary valve replacement, RV outflow tract repair)
2017 (10 months): Developed post-operative arrhythmias, started on amiodarone
2018 (14 months): Developmental delay noted, referred to early intervention services
2018 (18 months): Speech therapy initiated for delayed language development
2019 (2 years): Diagnosed with failure to thrive, started on high-calorie diet
2019 (2.5 years): Occupational therapy started for fine motor skill delays
2020 (3 years): Cardiac catheterization showed mild pulmonary stenosis
2020 (3.5 years): Diagnosed with sensory processing disorder (SPD)
2021 (4 years): Started integrated preschool program with IEP (Individualized Education Plan)
2021 (4.5 years): Hospitalized for RSV bronchiolitis, required brief oxygen support
2022 (5 years): Echocardiogram showed progression of pulmonary stenosis, balloon valvuloplasty performed
2022 (5.5 years): Diagnosed with attention-deficit/hyperactivity disorder (ADHD), started behavioral therapy
2023 (6 years): Cochlear implant surgery for sensorineural hearing loss
2023 (7 years): Started mainstream school with continued IEP support
2024 (7.5 years): Occupational therapy discontinued, met fine motor skill goals
2024 (8 years): Periodic cardiac follow-up shows stable pulmonary valve function
2024 (8 years): Speech development progressing well, ongoing therapy
""",
"""
Patient Name: Jason Tran
Age: 25
Medical Record:
2010 (11 yrs): Diagnosed with asthma, started on albuterol inhaler
2012 (13 yrs): First football concussion, brief loss of consciousness
2013 (14 yrs): Fractured right tibia during soccer, surgical fixation
2014 (15 yrs): Second concussion, resulting in post-concussion syndrome
- Symptoms: headaches, dizziness, memory problems
- Referred to pediatric neurologist, cognitive rehabilitation therapy
2015 (16 yrs): Developed anxiety and depression, started on fluoxetine
2016 (17 yrs): ACL tear (left knee) during basketball, reconstructive surgery
- 6-month rehabilitation, switched to non-contact sports
2017 (18 yrs): Graduated high school, started college on academic scholarship
2018 (19 yrs): Diagnosed with PTSD related to sports injuries
- Started cognitive-behavioral therapy (CBT)
2019 (20 yrs): Tried to return to basketball, experienced panic attack
- Increased therapy sessions, added exposure therapy
2020 (21 yrs): COVID-19 pandemic, remote learning, reported increased anxiety
- Started mindfulness meditation and yoga
2021 (22 yrs): Diagnosed with sleep apnea, started CPAP therapy
- Sleep study suggested link between concussions and sleep disorder
2022 (23 yrs): Gradual return to low-impact sports (swimming, cycling)
- Reported improved mood and sleep quality
2023 (24 yrs): Graduated college, started job in sports analytics
- Continuing therapy, now biweekly
- Volunteering with youth concussion awareness program
2024 (25 yrs): Annual check-up - asthma well-controlled, mental health stable
- No sports-related injuries in past 2 years
- Training for first half-marathon
""",
"""
Patient Name: Amira Khan
Age: 36
Medical Record:
2011: Recurrent joint pain and fatigue, initial diagnosis of fibromyalgia
- Started on pregabalin and physical therapy
2012: Developed persistent rash and photosensitivity
- Dermatologist diagnosed cutaneous lupus (CLE)
- Started on topical corticosteroids and sunscreen
2013: Complained of severe fatigue, hair loss, and cognitive issues ("brain fog")
- Blood tests showed positive ANA and anti-dsDNA antibodies
- Diagnosed with Systemic Lupus Erythematosus (SLE)
- Started on hydroxychloroquine and low-dose prednisone
2014: Hospitalized for lupus nephritis (class III)
- Renal biopsy confirmed diagnosis
- Started on mycophenolate mofetil and increased prednisone
2015: Developed interstitial lung disease (ILD) secondary to SLE
- Started on cyclophosphamide pulse therapy
- Required home oxygen therapy
2016: Diagnosed with secondary Sjögren's syndrome
- Symptoms: dry eyes, dry mouth
- Started on pilocarpine and artificial tears
2017: Hospitalized for lupus cerebritis
- Symptoms: seizures, confusion, memory loss
- MRI showed brain inflammation
- Treated with high-dose steroids and rituximab
2018: Developed avascular necrosis (AVN) of hip, steroid-induced
- Underwent total hip replacement surgery
2019: Started on belimumab to reduce flare frequency
- Gradual reduction in prednisone dosage
2020: COVID-19 pandemic, self-isolated due to immunosuppression
- Telemedicine follow-ups, home infusions
2021: Diagnosed with steroid-induced diabetes
- Started on metformin and insulin
- Referred to endocrinologist and nutritionist
2022: Flare-up of lupus, increased joint pain and fatigue
- Adjusted medications: increased mycophenolate, added abatacept
2023: Cardiovascular screening due to long-term steroid use
- Echo showed early signs of diastolic dysfunction
- Started on ACE inhibitors, referred to cardio-rehab
2024: Improvement noted in all organ systems
- Tapering immunosuppressants, monitoring closely
- Continues physical therapy, yoga for joint health
- Planning pregnancy, consulted with high-risk OB
"""
]
Давайте посмотрим на один, чтобы убедиться, что наш список работает правильно:
patient_records[2]
'\nPatient Name: Lily Chen\nAge: 8\nMedical Record:\n\n2016 (Birth): Born at 34 weeks, diagnosed with Tetralogy of Fallot (TOF)\n - Immediate surgery to place a shunt for increased pulmonary blood flow\n2016 (3 months): Echocardiogram showed worsening right ventricular hypertrophy\n2017 (8 months): Complete repair of TOF (VSD closure, pulmonary valve replacement, RV outflow tract repair)\n2017 (10 months): Developed post-operative arrhythmias, started on amiodarone\n2018 (14 months): Developmental delay noted, referred to early intervention services\n2018 (18 months): Speech therapy initiated for delayed language development\n2019 (2 years): Diagnosed with failure to thrive, started on high-calorie diet\n2019 (2.5 years): Occupational therapy started for fine motor skill delays\n2020 (3 years): Cardiac catheterization showed mild pulmonary stenosis\n2020 (3.5 years): Diagnosed with sensory processing disorder (SPD)\n2021 (4 years): Started integrated preschool program with IEP (Individualized Education Plan)\n2021 (4.5 years): Hospitalized for RSV bronchiolitis, required brief oxygen support\n2022 (5 years): Echocardiogram showed progression of pulmonary stenosis, balloon valvuloplasty performed\n2022 (5.5 years): Diagnosed with attention-deficit/hyperactivity disorder (ADHD), started behavioral therapy\n2023 (6 years): Cochlear implant surgery for sensorineural hearing loss\n2023 (7 years): Started mainstream school with continued IEP support\n2024 (7.5 years): Occupational therapy discontinued, met fine motor skill goals\n2024 (8 years): Periodic cardiac follow-up shows stable pulmonary valve function\n2024 (8 years): Speech development progressing well, ongoing therapy\n '
Наш первоначальный «плохой» промпт
Давайте начнем с очень простого prompt, который просит Claude сгенерировать нам сводку. Очень простая первая попытка может выглядеть примерно так:
У меня есть эта медицинская карта пациента. Можете ли вы резюмировать ее для меня?
{медицинская карта находится здесь}
Мне это нужно для быстрого ознакомления перед завтрашним приемом пациента.
Давайте формализуем это в конкретный prompt, который мы можем использовать с динамически вставляемой медицинской записью:
initial_prompt = """
I have this patient medical record. Can you summarize it for me?
{record}
I need this for a quick review before the patient's appointment tomorrow.
"""
Далее давайте напишем простую функцию, которая будет принимать одну медицинскую запись, вставлять ее в наш prompt и заставлять Claude генерировать сводку:
from anthropic import Anthropic
from dotenv import load_dotenv
load_dotenv()
client = Anthropic()
def generate_summary_with_bad_prompt(patient_record):
prompt_with_record = initial_prompt.format(record=patient_record)
response = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=4096,
messages=[{"role": "user", "content": prompt_with_record}]
)
print("===============================")
print(response.content[0].text)
Давайте попробуем со всеми 5 медицинскими записями, которые у нас есть в списке patient_records:
generate_summary_with_bad_prompt(patient_records[0])
===============================
Here is a summary of Evelyn Thompson's 78-year-old medical record:
Chronic Conditions:
- Type 2 diabetes (since 1985) - on metformin, dose increased in 2010
- Hypertension (since 1992) - on lisinopril, dose increased in 2020
- Hypothyroidism (since 2000) - on levothyroxine
- Atrial fibrillation (since 2005) - on warfarin
- Vitamin B12 deficiency (since 2008) - receiving monthly injections
- Chronic kidney disease stage 3 (since 2015) - metformin adjusted
- Mild cognitive impairment (since 2019) - on donepezil
Surgical History:
- Total hip replacement (1998) - right side, due to osteoarthritis
- Cataract surgery (2003) - both eyes
- Lumpectomy and radiation (2013) - for stage 2 breast cancer
- Total knee replacement (2017) - left side, due to osteoarthritis
Cancer History:
- Breast cancer (2013) - currently on anastrozole for recurrence prevention
Recent Issues:
- Recurrent UTIs (2021) - on prophylactic antibiotics
- Worsening kidney function per eGFR (2022)
- Declining mobility (2023) - started physical therapy and home health aide
Overall, an elderly patient with multiple chronic conditions requiring polypharmacy and close monitoring, especially for diabetes, hypertension, kidney disease, and cancer recurrence.
generate_summary_with_bad_prompt(patient_records[1])
===============================
Here's a summary of Marcus Reyes' (age 42) medical record:
Mental Health:
- Diagnosed with generalized anxiety disorder in 2001, treated with paroxetine
- Major depressive disorder diagnosed in 2003, bupropion added
- Hospitalized for suicidal ideation in 2005, started cognitive behavioral therapy (CBT)
- ADHD diagnosis in 2007, started methylphenidate
- Medications changed over time due to side effects/inefficacy (escitalopram, venlafaxine, quetiapine, lamotrigine)
- Attempted suicide in 2023, required 30-day inpatient psychiatric treatment
- Divorce in 2020 led to increased therapy (added dialectical behavior therapy)
Other Conditions:
- Obstructive sleep apnea in 2012, started CPAP therapy
- Hypertension in 2014, started losartan
- Weight gain, referred to nutritionist in 2015
- Type 2 diabetes diagnosed in 2016, metformin started
- Hospitalized for diabetic ketoacidosis in 2017, insulin initiated
- GERD diagnosed in 2019, started omeprazole
- Plantar fasciitis in 2021, prescribed orthotics and physical therapy
- Panic attack in 2022, mistaken for heart attack
Recent Updates:
- 2024: Mood and sleep improved, weight loss noted
- 2024: A1C levels improved, insulin dose decreased
The patient has a complex medical history involving multiple psychiatric conditions managed with medications and therapy. He also has several chronic conditions like diabetes, hypertension, and sleep apnea that require management.
generate_summary_with_bad_prompt(patient_records[2])
===============================
Here is a summary of Lily Chen's 8-year medical record:
Lily was born prematurely at 34 weeks in 2016 with Tetralogy of Fallot (TOF), a congenital heart defect. She underwent immediate surgery for a shunt and then complete TOF repair at 8 months old in 2017. Post-operatively, she developed arrhythmias requiring medication.
Starting around 1 year old, Lily experienced developmental delays - failure to thrive, speech/language delays requiring therapy, fine motor skill delays requiring occupational therapy, and a sensory processing disorder diagnosis. An IEP was started in preschool for extra support.
Cardiac issues continued with mild pulmonary stenosis at 3 years old, requiring a balloon valvuloplasty at 5 years. She was also diagnosed with ADHD at 5.5 years and started behavioral therapy.
Other medical events included an RSV bronchiolitis hospitalization at 4.5 years requiring oxygen, and cochlear implant surgery at 6 years for sensorineural hearing loss.
Now at 8 years old, Lily has stable cardiac function but continues speech therapy. She has met fine motor goals and receives mainstream schooling with an IEP.
generate_summary_with_bad_prompt(patient_records[3])
===============================
Here is a summary of Jason Tran's 25-year-old medical record:
Asthma & Sports Injuries
- Diagnosed with asthma at age 11, prescribed albuterol inhaler
- Multiple sports concussions starting at age 13, with post-concussion syndrome
- Fracture and knee injuries requiring surgery in teens
Mental Health
- Developed anxiety and depression at 16, started fluoxetine
- Diagnosed with PTSD at 19 related to sports injuries, started CBT and exposure therapy
- Experienced panic attack at 20 trying to return to basketball
- Increased anxiety during COVID-19 pandemic at 21, started mindfulness practices
Sleep Issues
- Diagnosed with sleep apnea at 22 potentially linked to concussions, started CPAP
Recent Updates
- Gradual return to low-impact sports at 23 with improved mood/sleep
- Graduated college at 24, working in sports analytics
- Continuing biweekly therapy and youth concussion awareness program
- Training for first half-marathon at 25, asthma and mental health stable
Key Issues
- History of asthma
- Multiple concussions and sports injuries
- Anxiety, depression, PTSD
- Sleep apnea
I've highlighted the key medical issues, mental health conditions, and recent progress to prepare for tomorrow's appointment. Let me know if you need any clarification or have additional details to add.
generate_summary_with_bad_prompt(patient_records[4])
===============================
Here is a summary of Amira Khan's lengthy and complex medical history:
Amira Khan is a 36-year-old woman with a long-standing diagnosis of Systemic Lupus Erythematosus (SLE). Her initial symptoms in 2011 were joint pain and fatigue. After developing rashes and photosensitivity in 2012, she was diagnosed with cutaneous lupus and started on topical steroids. In 2013, positive autoantibodies and multi-system involvement led to the SLE diagnosis.
Over the years, Amira has experienced numerous lupus complications affecting multiple organs:
- Lupus nephritis requiring immunosuppressants (2014)
- Interstitial lung disease requiring cyclophosphamide and oxygen (2015)
- Secondary Sjogren's syndrome (2016)
- Lupus cerebritis with brain inflammation (2017)
- Avascular necrosis of hip requiring joint replacement (2018)
She has required intensive treatment with hydroxychloroquine, mycophenolate, cyclophosphamide, rituximab, belimumab, and long-term corticosteroids leading to side effects like diabetes and diastolic dysfunction. Despite treatment challenges, her condition has gradually improved with multi-disciplinary care.
Currently, she is on abatacept, mycophenolate, ACE inhibitors, and trying to taper corticosteroids. She continues physical therapy and is interested in a future pregnancy consultation. Close monitoring is needed for her complex multi-system disease and medication side effects.
Если мы присмотримся к сводкам, которые мы получили от Claude, они совершенно хаотичны! Некоторые сводки представляют собой просто длинные абзацы текста. Другие сводки разбиты на маркированные списки. Фактическое содержание каждой сводки радикально отличается. Содержание сводки не ужасно, но форматирование, длина и типы данных сводки непоследовательны, и их будет трудно использовать программно. Давайте улучшим это!
Улучшение промпта
Как мы узнали на предыдущем уроке, существует четкий набор техник создания промптов, которые могут помочь нам получить лучшие и более последовательные результаты, включая:
- Добавление четкого системного prompt для определения контекста и роли ассистента, например, медицинского работника или аналитика данных здравоохранения
- Структурирование входных данных с использованием XML-тегов (например,
<patient_record>), чтобы было ясно, какая часть prompt является входными данными - Предоставление четких, конкретных инструкций о том, на чем должна сосредоточиться сводка, например, на диагнозах, лекарствах и недавних проблемах со здоровьем
- Указание желаемого формата сводки, например, маркированных списков или структурированного формата с определенными разделами
- Включение примера хорошо отформатированной сводки для руководства ответом ассистента
- Использование какого-либо выходного XML-тега для структурирования вывода, что позволяет пользователю быстро находить соответствующую информацию
В предстоящих уроках мы обсудим конкретный, тонкий подход к prompt engineering и выбору техник составления промптов. В этом уроке мы применим «ковровый» подход и используем их все сразу.
Добавление системного промпта
Давайте рассмотрим эти предложения по очереди. Мы начнем с определения системного prompt, чтобы установить контекст и роль для ассистента. По нашему опыту, это единственная информация, которая должна быть в системном prompt.
Для нашего сценария использования наш системный prompt должен сообщить Claude, что его роль — выступать в качестве медицинского работника, талантливого в преобразовании длинных историй болезни пациентов в краткие сводки.
Вот один из подходов:
system = """
You are a highly experienced medical professional with a specialty in translating complex patient histories into concise, actionable summaries.
Your role is to analyze patient records, identify critical information, and present it in a clear, structured format that aids in diagnosis and treatment planning.
Your summaries are invaluable for busy healthcare providers who need quick insights into a patient's medical history before appointments.
"""
Структурирование входных данных
Один из самых важных советов по составлению промптов при работе с Claude — это четкая маркировка входных данных с использованием XML-тегов. В нашем текущем prompt мы предоставляем историю болезни в качестве основного ввода следующим образом:
У меня есть эта медицинская карта пациента. Можете ли вы резюмировать ее для меня?
{медицинская карта находится здесь}
Мне это нужно для быстрого ознакомления перед завтрашним приемом пациента.
Простое дополнение, которое может привести к существенному улучшению, — это использование XML-тегов для обертывания наших входных данных. Давайте обновим наш prompt, чтобы сделать это с помощью тегов <patient_record>
# Системный промпт
system = """
You are a highly experienced medical professional with a specialty in translating complex patient histories into concise, actionable summaries.
Your role is to analyze patient records, identify critical information, and present it in a clear, structured format that aids in diagnosis and treatment planning.
Your summaries are invaluable for busy healthcare providers who need quick insights into a patient's medical history before appointments.
"""
# Улучшенный промпт (все еще в процессе работы!)
updated_prompt = """
<patient_record>
{record}
</patient_record>
"""
Предоставьте четкие инструкции
При работе с Claude предоставление четких и прямых инструкций имеет решающее значение для достижения наилучших результатов. Точно так же, как когда мы впервые инструктируем человека по задаче, чем точнее мы объясняем, что именно мы хотим, тем лучше и точнее будет ответ Claude.
В нашем первоначальном «плохом» prompt были следующие инструкции:
У меня есть эта медицинская карта пациента. Можете ли вы резюмировать ее для меня?
Это ужасно расплывчато! Нам нужно разработать набор четких и конкретных инструкций. Как именно должна выглядеть сводка?
Допустим, мы хотим, чтобы сводка включала следующие отдельные категории информации:
- Имя пациента
- Возраст пациента
- Список ключевых диагнозов
- Список прописанных пациенту лекарств
- Список немедикаментозных методов лечения (физиотерапия, КПТ и т. д.)
- Список недавних проблем
- Список важных пунктов действий для врача
Также важно указать точный формат вывода, который нам нужен, поэтому мы обязательно попросим Claude использовать маркированные списки вместо простого «списка».
Вот обновленная версия нашего prompt:
# Системный промпт
system = """
You are a highly experienced medical professional with a specialty in translating complex patient histories into concise, actionable summaries.
Your role is to analyze patient records, identify critical information, and present it in a clear, structured format that aids in diagnosis and treatment planning.
Your summaries are invaluable for busy healthcare providers who need quick insights into a patient's medical history before appointments.
"""
# Улучшенный промпт (все еще в процессе работы!)
updated_prompt = """
I need your help summarizing patient medical records for our team of doctors.
We have a series of follow-up appointments tomorrow, and the doctors need quick, insightful summaries to prepare.
Each summary should include the following elements in this order:
- The patient's name
- The patients age
- A bulleted list of key diagnoses in chronological order
- A bulleted list of medications the patient is prescribed
- A bulleted list of other treatments: non-medication treatments like CBT or physical therapy
- A short bulleted list of recent concerns
- A bulleted list of key action items to help our doctors prepare for the upcoming patient visit
<patient_record>
{record}
</patient_record>
"""
Добавление примеров
Примеры — один из самых мощных инструментов для повышения производительности Claude и направления его на получение желаемого результата. Предоставляя несколько хорошо составленных примеров в нашем prompt, мы можем значительно улучшить точность, согласованность и качество ответов Claude. Эта техника особенно эффективна для задач, которые очень детализированы или требуют структурированных результатов или соблюдения определенных форматов.
На данный момент наш prompt вообще не содержит примеров. Чтобы быть краткими, мы включим один пример, хотя часто лучше иметь хотя бы два.
Мы будем основывать наш пример ввода и вывода на этой истории болезни:
Patient Name: Ethan Blackwood
Age: 55
Medical Record:
2010: Annual check-up, mild hypertension noted
- Started on lifestyle modifications (diet, exercise)
2012: Diagnosed with moderate depression following job loss
- Started on sertraline and cognitive-behavioral therapy (CBT)
2014: New job, reported improved mood
- Continued sertraline, reduced CBT sessions
2015: Mild back pain, diagnosed with early degenerative disc disease
- Physical therapy and over-the-counter NSAIDs prescribed
2016: Hypertension worsened, started on lisinopril
2017: Routine colonoscopy showed benign polyps, removed during procedure
2018: Developed persistent cough, chest X-ray clear
- Diagnosed with Gastroesophageal Reflux Disease (GERD)
- Started on omeprazole
2019: Diagnosed with obstructive sleep apnea (OSA)
- Started CPAP therapy, reported improved energy levels
2020: COVID-19 pandemic, worked from home
- Reported increased anxiety, CBT sessions resumed (telehealth)
- COVID-19 vaccination (Moderna, both doses)
2021: Mild knee pain, MRI showed minor meniscus tear
- Arthroscopic surgery recommended, patient opted for conservative management
2022: Annual check-up showed pre-diabetes (A1C: 6.1%)
- Intensified lifestyle modifications, referred to nutritionist
- Discontinued omeprazole due to resolved GERD symptoms
2023: Blood tests showed elevated PSA (Prostate-Specific Antigen)
- Prostate biopsy performed, results negative for cancer
- Knee pain worsened, agreed to arthroscopic surgery
2024: Post-op Урок входит в темы
Полезные гиды