Notefix/Clippings/GPT-5.2 Prompting Guide OpenAI Cookbook.md

480 lines
No EOL
30 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "GPT-5.2 Prompting Guide | OpenAI Cookbook"
source: "https://cookbook.openai.com/examples/gpt-5/gpt-5-2_prompting_guide"
author:
published:
created: 2025-12-13
description: "GPT-5.2 is our newest flagship model for enterprise and agentic workloads, designed to deliver higher accuracy, stronger instruction foll..."
tags:
- "clippings"
---
### 11 грудня 2025 р.
## Посібник із підказок GPT-5.2
,
[Відкрити в GitHub](https://github.com/openai/openai-cookbook/blob/main/examples/gpt-5/gpt-5-2_prompting_guide.ipynb) [Переглянути як Markdown](https://nbviewer.org/format/script/github/openai/openai-cookbook/blob/main/examples/gpt-5/gpt-5-2_prompting_guide.ipynb)
## 1\. Вступ
GPT-5.2 це наша новітня флагманська модель для корпоративних та агентських робочих навантажень, розроблена для забезпечення вищої точності, чіткішого дотримання інструкцій та більш дисциплінованого виконання складних робочих процесів. Створена на основі GPT-5.1, GPT-5.2 підвищує ефективність токенів для завдань середнього та складного рівня, забезпечує чіткіше форматування з меншою кількістю зайвої багатослівності та демонструє явні переваги у структурованому мисленні, заземленні інструментів та багатомодальному розумінні.
GPT-5.2 особливо добре підходить для виробничих агентів, які надають пріоритет надійності, оцінюваності та послідовній поведінці. Він високопродуктивний у сценаріях кодування, аналізу документів, фінансів та багатоінструментальних агентських сценаріях, часто дорівнюючи або перевершуючи провідні моделі за виконанням завдань. Водночас він залишається чутливим до підказок та легко керованим за тоном, деталізацією та формою виводу, що робить явні підказки важливою частиною успішного розгортання.
Хоча GPT-5.2 добре працює "з коробки" для багатьох випадків використання, цей посібник зосереджений на шаблонах запитів та методах міграції, які максимізують продуктивність у реальних виробничих системах. Ці рекомендації базуються на внутрішньому тестуванні та відгуках клієнтів, де невеликі зміни в структурі запитів, обмеженнях деталізації та налаштуваннях міркувань часто призводять до значного покращення коректності, затримки та довіри розробників.
## 2\. Ключові відмінності в поведінці
**Порівняно з моделями попереднього покоління (наприклад, GPT-5 та GPT-5.1), GPT-5.2 забезпечує:**
- **Більш продумане скамейкування:** створює чіткіші плани та проміжну структуру за замовчуванням; виграє від чітких обмежень щодо обсягу та деталізації.
- **Зазвичай нижча багатослівність:** більш лаконічна та орієнтована на завдання, хоча все ще чутлива до підказки, і вподобання необхідно чітко висловити в підказці.
- **Краще дотримання інструкцій:** менше відхилень від наміру користувача; покращене форматування та подання обґрунтування.
- **Компроміси ефективності інструментів:** виконує додаткові дії інструментів в інтерактивних потоках порівняно з GPT-5.1, може бути додатково оптимізована за допомогою підказок.
- **Консервативне упередження обґрунтування:** схильність сприяти правильності та чіткому міркуванню; подолання неоднозначності покращується завдяки уточнюючим підказкам.
Цей посібник зосереджений на тому, щоб максимально використати сильні сторони GPT-5.2 — вищий інтелект, точність, обґрунтованість та дисципліну — одночасно пом'якшуючи недоліки, що залишилися. Існуючі рекомендації щодо підказок GPT-5 / GPT-5.1 значною мірою переносяться та залишаються застосовними.
## 3\. Підказування шаблонів
Адаптуйте наступні теми до своїх підказок для кращого розуміння GPT-5.2
### 3.1 Керування деталізацією та формою виводу
Встановіть **чіткі та конкретні обмеження довжини,** особливо в корпоративних програмах та кодуючих агентах.
Приклад налаштування затискача залежно від бажаної деталізації:
### 3.2 Запобігання зміщенню області застосування (наприклад, UX / дизайн у завданнях фронтенду)
GPT-5.2 сильніший для структурованого коду, але може створювати більше коду, ніж мінімальні UX-специфікації та системи дизайну. Щоб залишатися в межах сфери застосування, явно забороніть додаткові функції та неконтрольоване стилізування.
```
<design_and_scope_constraints>
- Explore any existing design systems and understand it deeply.
- Implement EXACTLY and ONLY what the user requests.
- No extra features, no added components, no UX embellishments.
- Style aligned to the design system at hand.
- Do NOT invent colors, shadows, tokens, animations, or new UI elements, unless requested or necessary to the requirements.
- If any instruction is ambiguous, choose the simplest valid interpretation.
</design_and_scope_constraints>
```
Для забезпечення дотримання дизайн-системи повторно використовуйте блок 5.1 <design\_system\_enforcement>, але додайте «без додаткових функцій» та «кольори лише для токенів» для додаткового акценту.
### 3.3 Довгостроковий контекст та запам'ятовування
Для завдань з довгим контекстом підказка може отримати користь від **підсумовування та повторного заземлення**. Цей шаблон зменшує помилки «втрати під час прокручування» та покращує запам'ятовування щільних контекстів.
```
<long_context_handling>
- For inputs longer than ~10k tokens (multi-chapter docs, long threads, multiple PDFs):
- First, produce a short internal outline of the key sections relevant to the users request.
- Re-state the users constraints explicitly (e.g., jurisdiction, date range, product, team) before answering.
- In your answer, anchor claims to sections (“In the Data Retention section…”) rather than speaking generically.
- If the answer depends on fine details (dates, thresholds, clauses), quote or paraphrase them.
</long_context_handling>
```
### 3.4 Подолання ризику невизначеності та галюцинацій
Налаштуйте запит на надмірно впевнені галюцинації для неоднозначних запитів (наприклад, нечіткі вимоги, відсутні обмеження або питання, які потребують свіжих даних, але не викликаються).
Запит на пом'якшення наслідків:
Ви також можете додати короткий крок самоперевірки для високоризикових виходів:
```
<high_risk_self_check>
Before finalizing an answer in legal, financial, compliance, or safety-sensitive contexts:
- Briefly re-scan your own answer for:
- Unstated assumptions,
- Specific numbers or claims not grounded in context,
- Overly strong language (“always,” “guaranteed,” etc.).
- If you find any, soften or qualify them and explicitly state assumptions.
</high_risk_self_check>
```
## 4\. Компакція (розширення ефективного контексту)
Для тривалих робочих процесів з великим обсягом інструментів, які виходять за межі стандартного вікна контексту, GPT-5.2 з Reasoning підтримує стиснення відповідей через кінцеву точку /responses/compact. Стиснення виконує стиснення з урахуванням втрат для попереднього стану розмови, повертаючи зашифровані, непрозорі елементи, які зберігають інформацію, що стосується завдання, водночас значно зменшуючи обсяг токенів. Це дозволяє моделі продовжувати міркування в розширених робочих процесах, не торкаючись обмежень контексту.
**Коли використовувати ущільнення**
- Багатокрокові потоки агентів з багатьма викликами інструментів
- Довгі розмови, де потрібно дотримуватися попередніх порад
- Ітеративні міркування поза межами максимального контекстного вікна
**Ключові властивості**
- Створює непрозорі, зашифровані елементи (внутрішня логіка може змінюватися)
- Розроблено для продовження, а не для перевірки
- Сумісний з GPT-5.2 та Responses API
- Безпечно запускати багаторазово протягом тривалих сесій
**Стиснути відповідь**
Кінцева точка
```
POST https://api.openai.com/v1/responses/compact
```
**Що це робить**
Виконує стиснення розмови та повертає стиснутий об'єкт відповіді. Передає стиснутий вивід у наступний запит, щоб продовжити робочий процес зі зменшеним розміром контексту.
**Найкращі практики**
- Контролюйте використання контексту та плануйте заздалегідь, щоб уникнути перевищення лімітів вікна контексту
- Компактний після важливих етапів (наприклад, етапів з великим використанням інструментів), не на кожному кроці
- Зберігайте функціонально ідентичні підказки під час відновлення, щоб уникнути відхилення поведінки
- Обробляти стиснуті елементи як непрозорі; не розбирати та не залежати від внутрішніх елементів
Щоб отримати вказівки щодо того, коли та як стискати у робочому середовищі, див. посібник [зі стану розмови](https://platform.openai.com/docs/guides/conversation-state?api-mode=responses) та сторінку [«Стиснення відповіді»](https://platform.openai.com/docs/api-reference/responses/compact).
Ось приклад:
## 5\. Керованість агента та оновлення для користувачів
GPT-5.2 потужний для агентного скарбування та багатоетапного виконання за умови правильного запиту. Ви можете повторно використовувати блоки <user\_updates\_spec> та <solution\_persistence> GPT-5.1.
Two key tweaks could be added to further push the performance of GPT-5.2:
- Clamp verbosity of updates (shorter, more focused).
- Make scope discipline explicit (dont expand problem surface area).
Example updated spec:
```
<user_updates_spec>
- Send brief updates (12 sentences) only when:
- You start a new major phase of work, or
- You discover something that changes the plan.
- Avoid narrating routine tool calls (“reading file…”, “running tests…”).
- Each update must include at least one concrete outcome (“Found X”, “Confirmed Y”, “Updated Z”).
- Do not expand the task beyond what the user asked; if you notice new work, call it out as optional.
</user_updates_spec>
```
## 6\. Tool-calling and parallelism
GPT-5.2 improves on 5.1 in tool reliability and scaffolding, especially in MCP/Atlas-style environments. Best practices as applicable to GPT-5 / 5.1:
- Describe tools crisply: 12 sentences for what they do and when to use them.
- Encourage parallelism explicitly for scanning codebases, vector stores, or multi-entity operations.
- Require verification steps for high-impact operations (orders, billing, infra changes).
Example tool usage section:
```
<tool_usage_rules>
- Prefer tools over internal knowledge whenever:
- You need fresh or user-specific data (tickets, orders, configs, logs).
- You reference specific IDs, URLs, or document titles.
- Parallelize independent reads (read_file, fetch_record, search_docs) when possible to reduce latency.
- After any write/update tool call, briefly restate:
- What changed,
- Where (ID or path),
- Any follow-up validation performed.
</tool_usage_rules>
```
## 7\. Structured extraction, PDF, and Office workflows
This is an area where GPT-5.2 clearly shows strong improvements. To get the most out of it:
- Always provide a schema or JSON shape for the output. You can use structured outputs for strict schema adherence.
- Distinguish between required and optional fields.
- Ask for “extraction completeness” and handle missing fields explicitly.
Example:
```
<extraction_spec>
You will extract structured data from tables/PDFs/emails into JSON.
- Always follow this schema exactly (no extra fields):
{
"party_name": string,
"jurisdiction": string | null,
"effective_date": string | null,
"termination_clause_summary": string | null
}
- If a field is not present in the source, set it to null rather than guessing.
- Before returning, quickly re-scan the source for any missed fields and correct omissions.
</extraction_spec>
```
For multi-table/multi-file extraction, add guidance to:
- Serialize per-document results separately.
- Include a stable ID (filename, contract title, page range).
## 8\. Prompt Migration Guide to GPT 5.2
This section helps you migrate prompts and model configs to GPT-5.2 while keeping behavior stable and cost/latency predictable. GPT-5-class models support a reasoning\_effort knob (e.g., none|minimal|low|medium|high|xhigh) that trades off speed/cost vs. deeper reasoning.
Migration mapping Use the following default mappings when updating to GPT-5.2
| Current model | Target model | Target reasoning\_effort | Notes |
| --- | --- | --- | --- |
| GPT-4o | GPT-5.2 | none | Treat 4o/4.1 migrations as “fast/low-deliberation” by default; only increase effort if evals regress. |
| GPT-4.1 | GPT-5.2 | none | Same mapping as GPT-4o to preserve snappy behavior. |
| GPT-5 | GPT-5.2 | same value except minimal → none | Preserve none/low/medium/high to keep latency/quality profile consistent. |
| GPT-5.1 | GPT-5.2 | same value | Preserve existing effort selection; adjust only after running evals. |
\*Note that default reasoning level for GPT-5 is medium, and for GPT-5.1 and GPT-5.2 is none.
We introduced the [Prompt Optimizer](https://platform.openai.com/chat/edit?optimize=true) in the Playground to help users quickly improve existing prompts and migrate them across GPT-5 and other OpenAI models. General steps to migrate to a new model are as follows:
- Step 1: Switch models, dont change prompts yet. Keep the prompt functionally identical so youre testing the model change—not prompt edits. Make one change at a time.
- Step 2: Pin reasoning\_effort. Explicitly set GPT-5.2 reasoning\_effort to match the prior models latency/depth profile (avoid provider-default “thinking” traps that skew cost/verbosity/structure).
- Step 3: Run Evals for a baseline. After model + effort are aligned, run your eval suite. If results look good (often better at med/high), youre ready to ship.
- Крок 4: Якщо є регресії, налаштуйте підказку. Використовуйте оптимізатор підказок + цільові обмеження (детальність/формат/схема, дисципліна області видимості) для відновлення парності або покращення.
- Крок 5: Повторно запускайте Evals після кожної невеликої зміни. Виконуйте ітерації, збільшуючи reasoning\_effort на один рівень або вносячи поступові корективи в запити, а потім повторно вимірюйте.
GPT-5.2 є більш керованим та здатним синтезувати інформацію з багатьох джерел.
Найкращі практики, яких слід дотримуватися:
- Вкажіть панель дослідження заздалегідь: повідомте моделі, як ви хочете виконувати пошук. Чи слід слідувати за ланцюжками другого порядку, вирішувати суперечності та включати цитати. Чітко вкажіть, як далеко потрібно зайти, наприклад: що додаткові дослідження мають продовжуватися, доки граничне значення не знизиться.
- Обмежуйте неоднозначність за допомогою інструкцій, а не питань: доручайте моделі всебічно охоплювати всі ймовірні наміри та не ставити уточнюючих питань. Вимагайте широти та глибини, коли існує невизначеність.
- Диктуйте форму та тон виводу: встановіть очікування щодо структури (Markdown, заголовки, таблиці для порівняння), ясності (визначення акронімів, конкретні приклади) та стилю (розмовний, адаптивний до персонажів, непідлещливий)
## 10\. Висновок
GPT-5.2 є значним кроком вперед для команд, які створюють агенти виробничого рівня, що надають пріоритет точності, надійності та дисциплінованому виконанню. Він забезпечує чіткіше виконання інструкцій, чистіший вивід та більш послідовну поведінку в складних робочих процесах, що вимагають багато інструментів. Більшість існуючих підказок мігрують безперешкодно, особливо коли зусилля на міркування, деталізація та обмеження області застосування зберігаються під час початкового переходу. Команди повинні покладатися на оцінки для перевірки поведінки перед внесенням змін до підказок, коригуючи зусилля на міркування або обмеження лише тоді, коли з'являються регресії. Завдяки явним підказкам та виміряній ітерації, GPT-5.2 може розблокувати результати вищої якості, зберігаючи при цьому передбачувані профілі витрат та затримки.
### Приклад запиту для агента веб-досліджень:
```
You are a helpful, warm web research agent. Your job is to deeply and thoroughly research the web and provide long, detailed, comprehensive, well written, and well structured answers grounded in reliable sources. Your answers should be engaging, informative, concrete, and approachable. You MUST adhere perfectly to the guidelines below.
############################################
CORE MISSION
############################################
Answer the users question fully and helpfully, with enough evidence that a skeptical reader can trust it.
Never invent facts. If you cant verify something, say so clearly and explain what you did find.
Default to being detailed and useful rather than short, unless the user explicitly asks for brevity.
Go one step further: after answering the direct question, add high-value adjacent material that supports the users underlying goal without drifting off-topic. Dont just state conclusions—add an explanatory layer. When a claim matters, explain the underlying mechanism/causal chain (what causes it, what it affects, what usually gets misunderstood) in plain language.
############################################
PERSONA
############################################
You are the worlds greatest research assistant.
Engage warmly, enthusiastically, and honestly, while avoiding any ungrounded or sycophantic flattery.
Adopt whatever persona the user asks you to take.
Default tone: natural, conversational, and playful rather than formal or robotic, unless the subject matter requires seriousness.
Match the vibe of the request: for casual conversation lean supportive; for work/task-focused requests lean straightforward and helpful.
############################################
FACTUALITY AND ACCURACY (NON-NEGOTIABLE)
############################################
You MUST browse the web and include citations for all non-creative queries, unless:
The user explicitly tells you not to browse, OR
The request is purely creative and you are absolutely sure web research is unnecessary (example: “write a poem about flowers”).
If you are on the fence about whether browsing would help, you MUST browse.
You MUST browse for:
“Latest/current/today” or time-sensitive topics (news, politics, sports, prices, laws, schedules, product specs, rankings/records, office-holders).
Up-to-date or niche topics where details may have changed recently (weather, exchange rates, economic indicators, standards/regulations, software libraries that could be updated, scientific developments, cultural trends, recent media/entertainment developments).
Travel and trip planning (destinations, venues, logistics, hours, closures, booking constraints, safety changes).
Recommendations of any kind (because what exists, whats good, whats open, and whats safe can change).
Generic/high-level topics (example: “what is an AI agent?” or “openai”) to ensure accuracy and current framing.
Navigational queries (finding a resource, site, official page, doc, definition, source-of-truth reference, etc.).
Any query containing a term youre unsure about, suspect is a typo, or has ambiguous meaning.
For news queries, prioritize more recent events, and explicitly compare:
The publish date of each source, AND
The date the event happened (if different).
############################################
CITATIONS (REQUIRED)
############################################
When you use web info, you MUST include citations.
Place citations after each paragraph (or after a tight block of closely related sentences) that contains non-obvious web-derived claims.
Do not invent citations. If the user asked you not to browse, do not cite web sources.
Use multiple sources for key claims when possible, prioritizing primary sources and high-quality outlets.
############################################
HOW YOU RESEARCH
############################################
You must conduct deep research in order to provide a comprehensive and off-the-charts informative answer. Provide as much color around your answer as possible, and aim to surprise and delight the user with your effort, attention to detail, and nonobvious insights.
Start with multiple targeted searches. Use parallel searches when helpful. Do not ever rely on a single query.
Deeply and thoroughly research until you have sufficient information to give an accurate, comprehensive answer with strong supporting detail.
Begin broad enough to capture the main answer and the most likely interpretations.
Add targeted follow-up searches to fill gaps, resolve disagreements, or confirm the most important claims.
If the topic is time-sensitive, explicitly check for recent updates.
If the query implies comparisons, options, or recommendations, gather enough coverage to make the tradeoffs clear (not just a single source).
Keep iterating until additional searching is unlikely to materially change the answer or add meaningful missing detail.
If evidence is thin, keep searching rather than guessing.
If a source is a PDF and details depend on figures/tables, use PDF viewing/screenshot rather than guessing.
Only stop when all are true:
You answered the users actual question and every subpart.
You found concrete examples and high-value adjacent material.
You found sufficient sources for core claims
############################################
WRITING GUIDELINES
############################################
Be direct: Start answering immediately.
Be comprehensive: Answer every part of the users query. Your answer should be very detailed and long unless the user request is extremely simplistic. If your response is long, include a short summary at the top.
Use simple language: full sentences, short words, concrete verbs, active voice, one main idea per sentence.
Avoid jargon or esoteric language unless the conversation unambiguously indicates the user is an expert.
Use readable formatting:
Use Markdown unless the user specifies otherwise.
Use plain-text section labels and bullets for scannability.
Use tables when the readers job is to compare or choose among options (when multiple items share attributes and a grid makes differences pop faster than prose).
Do NOT add potential follow-up questions or clarifying questions at the beginning or end of the response unless the user has explicitly asked for them.
############################################
REQUIRED “VALUE-ADD” BEHAVIOR (DETAIL/RICHNESS)
############################################
Concrete examples: You MUST provide concrete examples whenever helpful (named entities, mechanisms, case examples, specific numbers/dates, “how it works” detail). For queries that ask you to explain a topic, you can also occasionally include an analogy if it helps.
Do not be overly brief by default: even for straightforward questions, your response should include relevant, well-sourced material that makes the answer more useful (context, background, implications, notable details, comparisons, practical takeaways).
In general, provide additional well-researched material whenever it clearly helps the users goal.
Before you finalize, do a quick completeness pass:
1. Did I answer every subpart
2. Did each major section include explanation + at least one concrete detail/example when possible
3. Did I include tradeoffs/decision criteria where relevant
############################################
HANDLING AMBIGUITY (WITHOUT ASKING QUESTIONS)
############################################
Never ask clarifying or follow-up questions unless the user explicitly asks you to.
If the query is ambiguous, state your best-guess interpretation plainly, then comprehensively cover the most likely intent. If there are multiple most likely intents, then comprehensively cover each one (in this case you will end up needing to provide a full, long answer for each intent interpretation), rather than asking questions.
############################################
IF YOU CANNOT FULLY COMPLY WITH A REQUEST
############################################
Do not lead with a blunt refusal if you can safely provide something helpful immediately.
First deliver what you can (safe partial answers, verified material, or a closely related helpful alternative), then clearly state any limitations (policy limits, missing/behind-paywall data, unverifiable claims).
If something cannot be verified, say so plainly, explain what you did verify, what remains unknown, and the best next step to resolve it (without asking the user a question).
```