<НА ГЛАВНУЮ

Освойте JSON-промпты для LLM: практическое руководство с примерами на Python

'Руководство по использованию JSON-промптов с примерами на Python, показывающее, как структурированные запросы повышают точность и удобство интеграции результатов.'

Что такое JSON-промпты

JSON-подход к формированию промптов структурирует инструкции для моделей ИИ с использованием формата JavaScript Object Notation (JSON), делая их понятными, явными и пригодными для машинной обработки. В отличие от свободного текстового ввода, который может быть неоднозначным, JSON-промпты организуют требования в виде пар ключ-значение, массивов и вложенных объектов. Это превращает расплывчатые запросы в точные шаблоны, которым модель может следовать, повышая согласованность и точность при сложных или повторяющихся задачах.

Почему важна структура

Указывая такие поля, как задача, тема, аудитория и формат вывода, вы убираете двусмысленность и упрощаете парсинг ответа. Многие крупные LLM, включая GPT-4, Claude и Gemini, показывают лучшие результаты при предсказуемом, структурированном вводе. JSON-подход особенно полезен для генерации сводок, извлечения данных, интеграции с трекерами задач, панелями мониторинга и автоматизированными обработчиками электронной почты.

Установка и зависимости

Установите клиентскую библиотеку OpenAI и задайте API-ключ перед запуском примеров.

pip install openai
import os
from getpass import getpass
os.environ["OPENAI_API_KEY"] = getpass('Enter OpenAI API Key: ')

Для получения ключа OpenAI посетите https://platform.openai.com/settings/organization/api-keys и создайте новый ключ. Новым пользователям может потребоваться добавить данные для оплаты и совершить минимальный платеж для активации доступа.

from openai import OpenAI
client = OpenAI()

Структурированные промпты обеспечивают согласованность

Мыслить в терминах полей и значений помогает получить предсказуемый формат ответа. Фиксируя структуру вывода, вы устраняете догадки и гарантируете, что каждый ответ будет иметь одинаковую схему. Ниже приведены практические примеры сравнения свободного текста и JSON-промптов.

Пример 1 — Сводка письма (свободный формат)

Свободный текстовый промпт:

prompt_text = """
Summarize the following email and list the action items clearly.
 
Email:
Hi team, let's finalize the marketing plan by Tuesday. Alice, prepare the draft; Bob, handle the design.
"""
 
response_text = client.chat.completions.create(
    model="gpt-5",
    messages=[{"role": "user", "content": prompt_text}]
)
 
text_output = response_text.choices[0].message.content
print(text_output)

Типичный вывод в свободной форме:

Summary:
The team needs to finalize the marketing plan by Tuesday. Alice will prepare the draft, and Bob will handle the design.
 
Action items:
- Alice: Prepare the draft of the marketing plan by Tuesday.
- Bob: Handle the design by Tuesday.
- Team: Finalize the marketing plan by Tuesday.

Пример 1 — Сводка письма (JSON-промпт)

Тот же запрос, но требующий строгий JSON-формат:

prompt_json = """
Summarize the following email and return the output strictly in JSON format:
 
{
  "summary": "short summary of the email",
  "action_items": ["task 1", "task 2", "task 3"],
  "priority": "low | medium | high"
}
 
Email:
Hi team, let's finalize the marketing plan by Tuesday. Alice, prepare the draft; Bob, handle the design.
"""
 
response_json = client.chat.completions.create(
    model="gpt-5",
    messages=[
        {"role": "system", "content": "You are a precise assistant that always replies in valid JSON."},
        {"role": "user", "content": prompt_json}
    ]
)
 
json_output = response_json.choices[0].message.content
print(json_output)

Пример JSON-выхода:

{
  "summary": "Finalize the marketing plan by Tuesday; Alice to draft and Bob to handle design.",
  "action_items": [
    "Alice: prepare the draft",
    "Bob: handle the design",
    "Team: finalize the marketing plan by Tuesday"
  ],
  "priority": "medium"
}

Этот JSON-результат легко парсится программно и интегрируется в инструменты.

Пример 2 — Рыночное обновление (свободный формат)

Свободный промпт с запросом на краткую сводку, сентимент, возможности, риски и оценку уверенности:

plain_text_prompt = """
Analyze the following market update:
 
Market Text:
Tesla's Q2 earnings beat expectations due to higher Model Y sales, but rising competition from BYD is a risk.
Apple reported steady revenue growth driven by iPhone sales, but services revenue slightly declined.
Amazon's AWS division continues to dominate cloud computing, though regulatory scrutiny in Europe is increasing.
 
Generate:
- A 2-line market summary
- Sentiment for each company (positive, negative, neutral)
- Key growth opportunities and risks
- A confidence score from 0 to 10
"""
 
response_plain = client.chat.completions.create(
    model="gpt-5",
    messages=[{"role": "user", "content": plain_text_prompt}]
)
 
plain_output = response_plain.choices[0].message.content
print(plain_output)

Типичный свободный вывод:

Market summary:
- Earnings updates skew constructive: Tesla beat on Q2 with strong Model Y, Apple grew on iPhone, and AWS remains the cloud leader.
- Offsetting risks include BYD pressure on Tesla, Apple's services dip, and rising European scrutiny on Amazon.
 
Sentiment:
- Tesla: Positive
- Apple: Neutral
- Amazon: Positive
 
Key growth opportunities and risks:
- Tesla
  - Opportunities: Sustain Model Y momentum; scale production and pricing to drive volume.
  - Risks: Intensifying competition from BYD could pressure share and margins.
- Apple
  - Opportunities: Monetize large iPhone base; re-accelerate services via bundles and ecosystem engagement.
  - Risks: Services softness; dependence on iPhone for top-line growth.
- Amazon (AWS)
  - Opportunities: Leverage leadership to win more enterprise/AI workloads and multi-year commitments.
  - Risks: European regulatory scrutiny may lead to fines, compliance costs, or contract/pricing constraints.
 
Confidence score: 7/10

Пример 2 — Рыночное обновление (JSON-промпт)

То же анализ с требованием формата JSON:

json_prompt = """
Analyze the following market update and return the response in this JSON format:
 
{
  "summary": "2-line market overview",
  "companies": [
    {
      "name": "string",
      "sentiment": "positive | negative | neutral",
      "opportunities": ["list of opportunities"],
      "risks": ["list of risks"]
    }
  ],
  "confidence_score": "integer (0-10)"
}
 
Market Text:
Tesla's Q2 earnings beat expectations due to higher Model Y sales, but rising competition from BYD is a risk.
Apple reported steady revenue growth driven by iPhone sales, but services revenue slightly declined.
Amazon's AWS division continues to dominate cloud computing, though regulatory scrutiny in Europe is increasing.
"""
 
response_json = client.chat.completions.create(
    model="gpt-5",
    messages=[
        {"role": "system", "content": "You are a precise assistant that always outputs valid JSON."},
        {"role": "user", "content": json_prompt}
    ]
)
 
json_output = response_json.choices[0].message.content
print(json_output)

Пример JSON-ответа:

{
  "summary": "Markets saw mixed corporate updates: Tesla beat expectations on strong Model Y sales and AWS maintained cloud leadership.\nHowever, Apple's growth was tempered by softer services revenue while Tesla and AWS face competition and regulatory risks.",
  "companies": [
    {
      "name": "Tesla",
      "sentiment": "positive",
      "opportunities": [
        "Leverage strong Model Y demand to drive revenue and scale production",
        "Sustain earnings momentum from better-than-expected Q2 results"
      ],
      "risks": [
        "Intensifying competition from BYD",
        "Potential price pressure impacting margins"
      ]
    },
    {
      "name": "Apple",
      "sentiment": "neutral",
      "opportunities": [
        "Build on steady iPhone-driven revenue growth",
        "Revitalize Services to reaccelerate growth"
      ],
      "risks": [
        "Slight decline in services revenue",
        "Reliance on iPhone as the primary growth driver"
      ]
    },
    {
      "name": "Amazon (AWS)",
      "sentiment": "positive",
      "opportunities": [
        "Capitalize on cloud leadership to win new enterprise workloads",
        "Expand higher-margin managed services and deepen customer spend"
      ],
      "risks": [
        "Increasing regulatory scrutiny in Europe",
        "Potential compliance costs or operational restrictions"
      ]
    }
  ],
  "confidence_score": 8
}

JSON-подход упрощает автоматическую обработку результатов и гарантирует предсказуемую структуру данных.

Лучшие практики

  • Четко определяйте схему ответа с нужными полями.
  • Используйте системные сообщения для жесткого соблюдения формата, например 'always return valid JSON'.
  • Валидируйте выход модели и при необходимости реализуйте повторный запрос или обработку ошибок.
  • Держите схему компактной и однозначной, чтобы снизить вероятность неправильной интерпретации.
  • Используйте готовые шаблоны для интеграции в пайплайны и совместной работы команд.

Переиспользуемые JSON-шаблоны обеспечивают масштабируемость, скорость и аккуратную передачу данных между командами и сервисами.

🇬🇧

Switch Language

Read this article in English

Switch to English