Невозможно отправить запрос в openai с проанализированной подсказкой.Python

Программы на Python
Ответить
Anonymous
 Невозможно отправить запрос в openai с проанализированной подсказкой.

Сообщение Anonymous »

Я не могу отправить правильный JSON в openai.

Код: Выделить всё

def process_report(report):
model="gpt-4o-mini",
text = report.rstrip()
prompt = Template(graph_prompt_template).substitute(ctext=text)
messages=[
{"role": "system", "content": "You are a helpful assistant with a background in Radiology."},
{"role": "user", "content": prompt}
]
print(type(messages))
print(messages)
response = client.chat.completions.create(
model = model,
messages = messages,
temperature = 0,
)

# Extract the model's response
return response.choices[0].message.content

for report in report_list:
result = process_report(report)
results.append(result)
Это возвращает

класс 'list'
[{'role': 'system', 'content': 'Вы полезный помощник с опытом работы в радиологии.'}, {'role': 'user', 'content': '\nШаг 1: Организуйте отчеты радиолога в базе данных графиков. Диагноз находится в FULL_REPORT.\nИзвлеките ключевую информацию из отчетов рентгенологов, FULL_REPORT, например:\na. Название заболевания\nb. Расположение (например, вверху слева, внизу справа)\nc. Размер аномалий (например, большие или маленькие поражения или узелки)\nd. Количество отклонений\n\nОбратите внимание на заболевание. Можно сказать, небольшие повреждения. Никаких признаков пневмонии\n\nСтруктурируйте эту информацию в графическом формате базы данных. Для этого вы можете выбрать любой инструмент, но структура Neo4j настоятельно рекомендуется для обеспечения гибкости и визуализации.\n\nПример структуры узлов и связей:\na. Узлы: идентификатор пациента, заболевание, поражение, местоположение, размер\nb. Отношения: HAS_DISEASE, HAS_LESION, LOCATED_IN\n\nСохраните базу данных графиков в общем формате файла (например, .graphml, .csv, .json).\n\nДанные отчета:\nФронтальный и боковой вид грудной клетки. СРАВНЕНИЕ: Нет. ВЫВОДЫ: Линии/трубки: Нет. Легкие: Легкие хорошо раздуты и чисты. Признаков пневмонии или отека легких нет. Плевра: Плевральный выпот или пневмоторакс отсутствуют. Сердце и средостение: Сердце и средостение не изменены. Снова выявляются кальцинаты дуги аорты. Кости: Грудной скелет не изменен при многоуровневом дегенеративном заболевании. ВПЕЧАТЛЕНИЕ: Никаких признаков пневмонии или отека легких.\n'}]

И выдает ошибку:

Код: Выделить всё

BadRequestError: Error code: 400 - {'error': {'message': "We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON. If you have trouble figuring out how to fix this, please contact us through our help center at help.openai.com.)", 'type': 'invalid_request_error', 'param': None, 'code': None}}
Я попробовал не использовать подсказку в качестве переменной и жестко запрограммировал текст для проверки работоспособности.

Код: Выделить всё

messages = [
{"role": "system", "content": "You are a helpful assistant with a background in Radiology."},
{"role": "user", "content": "\nStep 1: Organize Radiologist Reports into a Graph Database. The diagnosis is in FULL_REPORT.\nExtract key information from the radiologists' reports, FULL_REPORT, such as:\na. Disease Name\nb. Location (e.g., top-left, bottom-right)\nc. Size of abnormalities (e.g., large or small lesions, or nodules)\nd. Number of abnormalities\n\nPay attention to the disease. It might say small lesions. No evidence of pneumonia\n\nStructure this information into a graph database format. You can choose any tool for this, but the Neo4j structure is highly recommended for flexibility and visualization.\n\nExample node and relationship structure:\na. Nodes: Patient ID, Disease, Lesion, Location, Size\nb. Relationships: HAS_DISEASE, HAS_LESION, LOCATED_IN\n\nSave your graph database as a shareable file format (e.g., .graphml, .csv, .json).\n\nReport Data:\nXR CHEST PORTABLE   A single AP view of the chest.   COMPARISON: XR CHEST PA AND LATERAL 2 VIEWS [REDACTED] .   FINDINGS:  Lines/tubes:  None.   Lungs:  There is perihilar fullness and blurring of the pulmonary vasculature consistent with interstitial edema.   Pleura:  There is no pleural effusion or pneumothorax.   Heart and mediastinum:  Patient is status post midline sternotomy with pacemaker. There is cardiomegaly.   Bones:  The thoracic skeleton is unremarkable.   IMPRESSION:  Moderate pulmonary edema.              \n"}
]
response = client.chat.completions.create(
model=GPT_MODEL,
messages=messages,
temperature=0
)
Однако это выполняется без каких-либо ошибок.
Я также сравнил два запроса, чтобы увидеть, в чем именно они различаются:
Случай ошибки:

Код: Выделить всё

[{'role': 'system', 'content': 'You are a helpful assistant with a background in Radiology.'}, {'role': 'user', 'content': '\nStep 1: Organize Radiologist Reports into a Graph Database. The diagnosis is in FULL_REPORT.\nExtract key information from the radiologists reports, FULL_REPORT, such as:\na. Disease Name\nb. Location (e.g., top-left, bottom-right)\nc. Size of abnormalities (e.g., large or small lesions, or nodules)\nd. Number of abnormalities\n\nPay attention to the disease. It might say small lesions. No evidence of pneumonia\n\nStructure this information into a graph database format. You can choose any tool for this, but the Neo4j structure is highly recommended for flexibility and visualization.\n\nExample node and relationship structure:\na. Nodes: Patient ID, Disease, Lesion, Location, Size\nb. Relationships: HAS_DISEASE, HAS_LESION, LOCATED_IN\n\nSave your graph database as a shareable file format (e.g., .graphml, .csv, .json).\n\nReport Data:\nFrontal and lateral views of the chest.   COMPARISON: None   FINDINGS:  Lines/tubes:  None.   Lungs:  The lungs are well inflated and clear. There is no evidence of pneumonia or pulmonary edema.   Pleura:  There is no pleural effusion or pneumothorax.   Heart and mediastinum:  The heart and the mediastinum are unchanged. Aortic arch calcifications are again identified.   Bones:  The thoracic skeleton is unchanged with multilevel degenerative disease.   IMPRESSION:  No evidence of pneumonia or pulmonary edema.\n'}]
Проходной вариант:

Код: Выделить всё

[{'role': 'system', 'content': 'You are a helpful assistant with a background in Radiology.'}, {'role': 'user', 'content': "\nStep 1: Organize Radiologist Reports into a Graph Database. The diagnosis is in FULL_REPORT.\nExtract key information from the radiologists' reports, FULL_REPORT, such as:\na. Disease Name\nb. Location (e.g., top-left, bottom-right)\nc. Size of abnormalities (e.g., large or small lesions, or nodules)\nd. Number of abnormalities\n\nPay attention to the disease. It might say small lesions. No evidence of pneumonia\n\nStructure this information into a graph database format. You can choose any tool for this, but the Neo4j structure is highly recommended for flexibility and visualization.\n\nExample node and relationship structure:\na. Nodes: Patient ID, Disease, Lesion, Location, Size\nb. Relationships: HAS_DISEASE, HAS_LESION, LOCATED_IN\n\nSave your graph database as a shareable file format (e.g., .graphml, .csv, .json).\n\nReport Data:\nXR CHEST PORTABLE   A single AP view of the chest.   COMPARISON: XR CHEST PA AND LATERAL 2 VIEWS [REDACTED] .   FINDINGS:  Lines/tubes:  None.   Lungs:  There is perihilar fullness and blurring of the pulmonary vasculature consistent with interstitial edema.   Pleura:  There is no pleural effusion or pneumothorax.   Heart and mediastinum:  Patient is status post midline sternotomy with pacemaker. There is cardiomegaly.   Bones:  The thoracic skeleton is unremarkable.   IMPRESSION:  Moderate pulmonary edema.             \n"}]
Но не удалось найти ничего, что могло бы привести к такой проблеме.
Я понимаю, что это должно быть что-то чрезвычайно тривиальное, но я как бы застрял здесь.Спасибо за понимание и ваше терпение.

Подробнее здесь: https://stackoverflow.com/questions/793 ... sed-prompt
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»